# Question
Title: How to render a very large amount of objects in a single call to drawelementarrays() in OpenGL?
The gist of the situation is as follows. I have hundreds of cubes that need to be rendered. The cubes share the exact same mesh, but they will be rendered at different positions. The position of the cubes is mostly static but can change at any point.

The cube object looks as follows:

```
class Cube
{
    private:
        static Geometry *mesh;
        static Texture *texture;

        static string Default_Mesh;
        static string Default_Texture;

    public:
        static void make_template(string wavefront_file, string t);
        static void cleanup();

        vec3 position;

        Cube(vec3 p);
        Cube();
        ~Cube();

        void render_cube();
};

```

My goal is to try to render all cubes in a single call to drawElementArrays() by passing all vertices to the GPU, all Translation matrices to the GPU and then specify that the first 36 vertices use the first translation matrix, the next 36 vertices use the next translation matrix...

But also, even though they share the same geometry, they all have different textures, so I also need to specify the sampler 2D object that each vertiex uses.

Thanks in advance.

# Answer
glDrawArraysInstanced() is appropriate here.

In your case, I assume all cubes have the same size and orientation? That means you only have to feed the drawcall a position per instance, instead of a full transformation matrix per instance.

A different texture per instance doesn't work though, what you would need to do is use a texture atlas, and supply UV offsets for each instance that points to the correct sub-image in the texture.

You would build a VBO with shared vertex data, which comprises:

36 vertex positions, 36 surface normals (if you do lighting), 36 UV coordinates. This can be interleaved if so desired:

```
X0,Y0,Z1,NX0,NY0,NZ0,U0,V0, X1,Y1,Z1,NX1,NY1,NZ1,U1,V1, ...

```

This defines the geometry of your cube.

Then, you append it with per-instance data. Let's say you are drawing 1024 cubes, then in your case this would be:

1024 cube positions, 1024 UV offsets.

Note that this data can be interleaved if required:

```
X0,Y0,Z0,UOFF0,VOFF0, X1,Y1,Z1,UOFF1,VOFF1, ....

```

Now all of these, both the shared stuff, and per-instance stuff, are plain old vertex attributes like a normal VBO would have, and how your shader will see them.

You need to tell OpenGL which of these vertex attributes are specific to instances, and you do this with glVertexAttribDivisor().

This is easily accomplished by setting the divisor to 1 for per-instance vertex attributes. So call this for your cubepos and UV offset attributes.

Note that in your shader you would typically still have a ModelViewProjection uniform that you apply. Instead of applying it to the vanilla vertex position, you apply it to a position that has been offset with the cube's position.

Also note: in your shader, you would transform your UV coordinate before sampling your texture, based on the per-instance UV offset value. So that you map the correct image from your atlas to each cube.
> 1 votes

# Answer
Seems like you want to either make use of:

1. 3D texturing. That way you load the textures once and the same models can have different textures depending on the "depth" of the texture.
2. Or a simpler way to is to have multiple textures saved as a new larger texture split into different sections. So for example, you have 4 512\*512 textures, then you put them into a 1024\*1024 the top left is for object 1, top right for object 2, etc. There'll probably be unused space if you do this, but it's a lot easier to understand and you can just change it in future if you feel the need. Then you just include that in your shader to take in a new uniform that translates the texture co-ordinate
> 0 votes

# Answer
If you have access to geometry shaders, then you can duplicate the primitives right on the GPU, and use an array of translation matrices to change their position, and assign a texture. ( but there is a limit )

Otherwise, you can define 2 vertex buffers vec3 position vec3 uvs

where uv.xy maps the image coordinates to the vertex position, and uv.z picks a layer of TEXTURE\_2D\_ARRAY.

Furthermore, the uv.xy portion of each cube likely won't change, so you can map it once, or use glVertexID (e.g. glVertexID % 8) to determine the uv.xy portion and map a 1D buffer that stores the texture.

You can map uniforms with names like "translation\[0\]", then define it as a uniform in the shader as uniform translation\[size\];
> 0 votes

---
Tags: opengl, textures, rendering
---


title: Persisting Data with C#

text:
# Question
Title: Persisting Data with C#
In Unity, I'm trying to save the game data to a file to be loaded upon the game reopening. But for some reason it is not saving and I cannot figure out why.

I have it so that if it cannot find that save file, it gives the player 3 items to start with and then tries to save that to the PersistingData. But then I close and reopen the game and it does not stay, and gets defaulted to 0.

Anyone know what I did wrong?

The PersistentData code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class PersistentData : MonoBehaviour {

    public static PersistentData dataObject;

    //Persistent Data here
    public int amps = 0;
    //Capacitors
    public int cap1v;
    public int cap3v;
    public int cap5v;
    public int cap9v;
    public int cap12v;
    public int cap24v;
    //Statistics
    public int totalDistance;
    public int lifetimeAmps;
    public int totalCapsUsed;
    public float lifetimeTimeInSeconds;
    public int numberOfRuns;
    public int distanceRecordNoCaps;
    public int distanceRecordWithCaps;
    public float highestAvgVoltage;
    public float longestRunInSeconds;
    public float highestAmpsEarned;

    //check if this object already exists and make sure its not destroyed every level
    private void Awake() {
        if (dataObject == null) {
            DontDestroyOnLoad(gameObject);
            dataObject = this;
        }
        else if (dataObject != this) {
            Destroy(gameObject);
        }
    }

    public void Save() {
        //setup for saving
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");

        //Add the data here too
        PlayerData data = new PlayerData();
        data.amps = amps;

        data.cap1v = cap1v;
        data.cap3v = cap3v;
        data.cap5v = cap5v;
        data.cap9v = cap9v;
        data.cap12v = cap12v;
        data.cap24v = cap24v;
        //Statistics
        data.totalDistance = totalDistance;
        data.lifetimeAmps = lifetimeAmps;
        data.totalCapsUsed = totalCapsUsed;
        data.lifetimeTimeInSeconds = lifetimeTimeInSeconds;
        data.numberOfRuns = numberOfRuns;
        data.distanceRecordNoCaps = distanceRecordNoCaps;
        data.distanceRecordWithCaps = distanceRecordWithCaps;
        data.highestAvgVoltage = highestAvgVoltage;
        data.longestRunInSeconds = longestRunInSeconds;
        data.highestAmpsEarned = highestAmpsEarned;

        //actually writing the data
        bf.Serialize(file, data);
        file.Close();
    }

    public void Load() {
        if (File.Exists(Application.persistentDataPath + "/playerInfo.dat")) {
            print("Save File Found");
            //setup for loading
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            PlayerData data = (PlayerData)bf.Deserialize(file);

            //Data Here Too
            amps = data.amps;

            data.cap1v = cap1v;
            data.cap3v = cap3v;
            data.cap5v = cap5v;
            data.cap9v = cap9v;
            data.cap12v = cap12v;
            data.cap24v = cap24v;
            //Statistics
            data.totalDistance = totalDistance;
            data.lifetimeAmps = lifetimeAmps;
            data.totalCapsUsed = totalCapsUsed;
            data.lifetimeTimeInSeconds = lifetimeTimeInSeconds;
            data.numberOfRuns = numberOfRuns;
            data.distanceRecordNoCaps = distanceRecordNoCaps;
            data.distanceRecordWithCaps = distanceRecordWithCaps;
            data.highestAvgVoltage = highestAvgVoltage;
            data.longestRunInSeconds = longestRunInSeconds;
            data.highestAmpsEarned = highestAmpsEarned;

            file.Close();
        }
        else if(!File.Exists(Application.persistentDataPath + "/playerInfo.dat")) { //If no save file, default the settings
            print("No Save File Found");
            dataObject.cap1v = 3;
            Save();
        }
    }

    private void Update() {
        print(dataObject.cap1v);
    }
}

[Serializable]
class PlayerData {

    //Persistent Data goes here
    public int amps = 0;
    //Capacitors
    public int cap1v = 0;
    public int cap3v = 0;
    public int cap5v = 0;
    public int cap9v = 0;
    public int cap12v = 0;
    public int cap24v = 0;
    //Statistics
    public int totalDistance;
    public int lifetimeAmps;
    public int totalCapsUsed;
    public float lifetimeTimeInSeconds;
    public int numberOfRuns;
    public int distanceRecordNoCaps;
    public int distanceRecordWithCaps;
    public float highestAvgVoltage;
    public float longestRunInSeconds;
    public float highestAmpsEarned;
}

```

And the Script trying to access the code:

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

public class MainMenuUI : MonoBehaviour {

    public Text capText;
    public Text ampText;

    private int capCount;
    private int ampCount;

    // Use this for initialization
    void Start () {
        PersistentData.dataObject.Load(); //Load data

        ampCount = PersistentData.dataObject.amps; //Load Correct Amp Count
        LoadCapCount(); //Load the total Cap count

        ampText.text = ((int)ampCount).ToString(); //Set amp count on UI
        capText.text = ((int)capCount).ToString(); //Set amp count on UI
    }

    void LoadCapCount() {
        capCount =
        PersistentData.dataObject.cap1v +
        PersistentData.dataObject.cap3v +
        PersistentData.dataObject.cap5v +
        PersistentData.dataObject.cap9v +
        PersistentData.dataObject.cap12v +
        PersistentData.dataObject.cap24v;
    }
}

```

# Answer
Let's work though this logically:

`dataObject.cap1v` prints zero. But in the path where no save file was found, we set it to 3. So (barring outside interference) we must not have taken that path.

Which means we did find a save file. So why didn't we load its saved value into `dataObject.cap1v`?

Because we loaded it into a new object called `data`, `data.cap1v`. Then did nothing with this temporary object reference, so it vanishes from the scope at the end of the `Load` method, leaving all our data still at its default values.
> 4 votes

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


title: CG: 4+ color gradient

text:
# Question
Title: CG: 4+ color gradient
I am trying to write a shader that takes multiple colors and applies them to a B&W texture. Now, 3 colors works just fine, but i will need 6 in order for this to function. If somebody could please explain how adding more colors would work or refer me to some documentation that would be appreciated!

What i have so far is the following (tex = B&W texture, \_Middle = 0.5):

```
fixed4 c = lerp(_ColorA, _ColorB, tex.y / _Middle) * step(tex.y, _Middle);
c += lerp(_ColorB, _ColorC, (tex.y - _Middle) / (1 - _Middle)) * step(_Middle, tex.y);

```

Source: http://answers.unity3d.com/questions/1108472/3-color-linear-gradient-shader.html

# Answer
The following code creates a 4 color gradient texture and applies it to the shader. The code needs to be attached to the object that has the shader on it.

private Texture2D _tex; //Texture that will go into the shader
private Renderer _rend; //Renderer of the object

```
private void Awake () {
    _rend = this.GetComponent<Renderer> ();

    //create new texture, width == amount of colors
    _tex = new Texture2D (4, 1);

    //Set each pixel to specified color (StarGradient is function below)
    _tex.SetPixels32 (StarGradient (
        new Color32 (255, 186, 0, 1),
        new Color32 (224, 100, 45, 1),
        new Color32 (118, 73, 41, 1),
        new Color32 (60, 73, 55, 1))
    );
    _tex.filterMode = FilterMode.Trilinear;
    _tex.wrapMode = TextureWrapMode.Clamp;
    _tex.Apply ();

    //Pass _tex to the material
    _rend.material.SetTexture ("_RampTex", _tex);
}

//Returns a Color32 array of specified colors
private Color32[] StarGradient(Color32 a, Color32 b, Color32 c, Color32 d) {
    Color32[] _colors = new Color32[4];
    _colors [0] = a;
    _colors [1] = b;
    _colors [2] = c;
    _colors [3] = d;
    return _colors;
}

```

> 1 votes

# Answer
if any one still need it.

```
 Shader "Custom/Gradient_4Color" {
     Properties {
         [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
         _ColorTop ("Top Color", Color) = (1,1,1,1)
         _ColorMidTop ("MidTop Color", Color) = (1,1,1,1)
         _ColorMidBot ("MidBot Color", Color) = (1,1,1,1)
         _ColorBot ("Bot Color", Color) = (1,1,1,1)
         _MiddleBot ("MiddleBot", Range(0.001, 0.999)) = 0.33
          _MiddleTop ("MiddleTop", Range(0.001, 0.999)) = 0.66
     }

     SubShader {
         Tags {"Queue"="Background"  "IgnoreProjector"="True"}
         LOD 100

         ZWrite On

         Pass {
         CGPROGRAM
         #pragma vertex vert
         #pragma fragment frag
         #include "UnityCG.cginc"

         fixed4 _ColorTop;
         fixed4 _ColorMidTop;
         fixed4 _ColorMidBot;
         fixed4 _ColorBot;

          float  _MiddleBot;
          float  _MiddleTop;

         struct v2f {
             float4 pos : SV_POSITION;
             float4 texcoord : TEXCOORD0;
         };

         v2f vert (appdata_full v) {
             v2f o;
             o.pos = UnityObjectToClipPos (v.vertex);
             o.texcoord = v.texcoord;
             return o;
         }

         fixed4 frag (v2f i) : COLOR {

             fixed4 c = lerp(_ColorBot, _ColorMidBot, i.texcoord.y / _MiddleBot) * step(i.texcoord.y, _MiddleBot);
             c += lerp(_ColorMidBot, _ColorMidTop, (i.texcoord.y - _MiddleBot) /(_MiddleTop - _MiddleBot) ) * step(_MiddleBot,i.texcoord.y) * step(i.texcoord.y,_MiddleTop);
             c += lerp(_ColorMidTop, _ColorTop, (i.texcoord.y - _MiddleTop) / (1 - _MiddleTop)) * step(_MiddleTop, i.texcoord.y);
             c.a = 1;

             return c;
         }
         ENDCG
         }
     }
 }

```
> 1 votes

---
Tags: unity, shaders, cg, nvidia
---


title: What does linearDamping mean in Box2D?

text:
# Question
Title: What does linearDamping mean in Box2D?
If I set linearDamping on a body, it's velocity will be decreased slowly, until it stops. The documentation says, that the units are 1/time, which is unclear for me.

If the velocity of a body is 10 m/s, and the linearDamping is 0.5, then how can I calculate that when will the velocity be decreased to 1 m/s ?

# Answer
I worked out a closed formula to calculate the velocity `v'` after some elapsed time `t` with a given `linearDamping` `D` and original velocity `v`:

```
v' = v*exp(-D*t)

```

To calculate how much time is needed to reach a given velocity `v'`:

```
t = ln(v' / v) / (-D)

```

Using the parameters from the question:

```
t = ln(1 / 10) / (-0.5) = 4.605

```

The object needs 4,6 seconds to decelerate from 10 m/s to 1 m/s

**Note:**

The original source code to calculate new velocity inside the step function:

```
v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f);

```

To calculate the distance the object should move over this interval, assuming continuous physics decoupled from any timestep, we can take the integral of the speed over that interval.

$$\begin{align} v(T) &= v\_0 e^{-D T}\\ \Delta p(T) &= \int\_0^T v\_0 e^{-D t} dt\\ \Delta p(T) &= \left\[ \frac {v\_0} {-D} e^{-Dt} \right\] \bigg\rvert\_0^T\\ \Delta p(T) &= \frac {v\_0} {-D} \left(e^{-DT} - e^0\right)\\ \Delta p(T) &= \frac {v\_0} {D} \left( 1 - e^{-DT}\right)\\ \end{align}$$

So we can see the object asymptotically approaches a distance of \\$\frac {v\_0} {D}\\$ from its initial position.
> 8 votes

# Answer
I looked at the Box2D source code, where it applies damping:

```
v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f);

```

So the loss of velocity is certainly not a fixed number of units per second, despite what the manual says.

Your example of 10m/s to 1m/s would also slightly depend on timestep. Let's assume 120Hz simulation step...

```
#!/usr/bin/python

v = 10
step = 0
h = 1/120.0
time = 0.0

while v > 1 :
    v *= ( 1 - h * 0.5 )
    step += 1
    time += h
    print( "step %d, time %f, v %f" % ( step, time, v ) )

```

Then it would take 4.6 seconds to slow down by that much.

```
...
step 551, time 4.591667, v 1.001957
step 552, time 4.600000, v 0.997783

```

I checked with 1/60 timestep as well, and the result is almost the same, btw.

I am not sure if you can determine this time delay in a single expression, though, without stepping through it.
> 5 votes

---
Tags: c++, 2d, physics, box2d
---


# Question
Title: How do I access device camera in GameMaker Studio 1.4?
I've looked everywhere in the documentation for GameMaker and I didn't find anything about how to access the camera.

# Answer
GameMaker doesn't have native support for device cameras, that's the reason you didn't find anything about it in the docs.

On the other hand, you can try to access the webcam on desktop devices using DLL libraries, like the one mentioned in this Reddit post, or looking for some plug-ins.
> 3 votes

---
Tags: android, camera, ios, game-maker
---


title: How to create a 2D fog shader?

text:
# Question
Title: How to create a 2D fog shader?
I am trying to write a fragment shader in GLSL for a fog effect in a 2D game.

Here are some links showing what I'm after.

Here the fog is in the foreground and near the ground:  https://twitter.com/i/status/992811158318075904

Here the fog is on a background layer and fills the screen:  https://twitter.com/i/status/963889084337983488

Here the fog is more subtle and denser near the ground:  https://twitter.com/i/status/1001926421856563205

I am interested in learning how to create these effects. Unfortunately, I am pretty new to shaders and only know how to do elementary stuff like color swaps, outlines, and simple vignettes. It doesn't help that it's hard to find resources on shaders with a bent toward 2D.

In the environment in which I'm working, I can attach a shader script to any of my sprites, parallax background layers, etc.

**Does anyone have advice on creating these kinds of effects?**

# Answer
> 2 votes
I made a little demo :

Edit:

-Extra version: Applied with color banding

-Even better version : inverted the uv mapping as @Mario suggested

-Better version: Texture addressing/Wrapping set to Mirror - still fades on overlap

-First version: Texture addressing/Wrapping set to Repeat, non repeating texture

Basically what I've done here is taken a noise map ( source ):

And sampled it twice with 2 different uv coordinates ( see quad.frag.glsl ). In my example I just used a timer to offset in positive and negative direction. Then simply subtracted the second sample from the first.

```
vec4 n = texture(iTex,uv+iTime*0.1);
vec4 n2 = texture(iTex,uv-iTime*0.1);
n-=n2;
fragColor = n;

```

improved version using Mirror addressing and uv swapping;

```
vec4 n = texture(iTex,uv+iTime*0.1);
vec4 n2 = texture(iTex,vec2(uv.y,uv.x)-iTime*0.1);
n-=n2;
fragColor = n;

```

Alternatively you could have a second noise map and offset/subtract from the first image, or use an actual perlin noise function and calculate two different values. If you play around with this concept I'm sure you'll find something satisfactory. How you blend and color it is all up to you. It doesn't have to be a noise map, could be any arbitrary grey scale image.

I hope others can provide their solutions too, I too am interested in this concept further.

edit:

Here is an example with perlin noise

and with color

I snatched the code from computergraphics

---
Tags: opengl, 2d, shaders, glsl, graphic-effects
---


# Question
Title: How to Work With Arbitrarily Oriented Vectors
I'm brushing up for a pending game jam and just for kicks I thought I'd let the gravity in my 2D platformer push at an arbitrary angle. Normally gravity points downward (3 PI / 2), but if I wanted it to point to the right (0) then the character would rotate accordingly and be able to walk along walls as though they were floor. In that case, pressing left would cause the player to move downward on the screen, as that would be left relative to the current angle of gravity.

The problem comes when I try to implement jumping or falling. As I'm now realizing, I lack the mental language to even properly describe my problem, but I clearly don't intuitively grasp how to handle rotated vectors.

For example: I'd like to know when the player is falling. Normally I'd just check if their velocity.y \> 0, but that only makes sense if gravity is pointing downward. If it's pointing to the right, then a velocity.y \> 0 implies that they're moving to the left, relative to gravity.

How do I go about understanding and working with 2D vectors that have an arbitrary global rotation applied to them?

# Answer
> 2 votes
If I understand correctly, you are making gravity a vector, and that is messing the rest of your code base.

So, first of all, as Anonymous Anonymous points out you will have to make velocity a vector. In fact, any other thing will probably have to be a vector too.

**Note**: I will not define what a vector is. Also, everything I say here is for working in 2D. However, there are similar and sometimes equivalent concepts for 3D, but that is beyond the scope of the answer.

Please use a library that does vector and matrix operations. I will explain enough to implement one yourself, just so you understand what is going on, but I will not cover optimizations.

---

## Vector addition and substraction

If we consider a vector a movement (from one place to another). The addition of the vectors is the result of doing both movements:

```
va + vb = {x: va.x + vb.x, y: va.y + vb.y}

```

As you can see the order does not matter in vector addition.

Now, if a vector is a movement that takes you a place, and another vector is another movement that takes you to another place... the movement needed to go from one place to the other is is their difference, we get it by vector substraction:

```
va - vb = {x: va.x - vb.x, y: va.y - vb.y}

```

Here, the order matters. `va - vb` is the vector that goes from the place that `vb` takes you to the place that `va` takes you.

You might be doing this vector substraction to place objects respect to the screen. You have world coordinates, a camera that has a position, and you need to figure out where on the screen the objects in the world are. That is, you need the difference from the position of the camera to the world object. To get that, you take the world object and subtract the position of the camera.

The difference is also useful to measure the distance between two places, to do that we need the norm of the vector.

---

## Norm and unit vectors

You will need to be able to measure the norm of a vector and to normalize it (make a unit vector out of it).

Assuming you are using euclidean geometry (a.k.a. normal, regular, everyday geometry), you compute the norm of the vector by the Pythagorean theorem: the square root of the squares of the components.

```
norm(v) = sqrt(v.x * v.x + v.y * v.y)

```

You get a unit vector by dividing the components of the vector by the norm of the vector. The norm of the resulting unit vector is 1 (within rounding error).

```
unit(v) = {x: v.x/norm(v), y: v.y/norm(v)}

```

The unit vector will be useful to specify directions, you will be able to scale it (multiply its components by a scalar) to get a vector of the appropiate norm you need.

```
scale(v, l) = {x: l * v.x, y: l * v.y}

```

**Note**: That is scalar product, and I will write it like this: `v * l`. We can also say that the unit vector is `unit(v) = v * 1/norm(v)`.

---

## Orthogonal vectors

You will need to be able to rotate vectors. For example, if you need the jump to always be against gravity, you can take the gravity vector, normalize it, rotate it half turn, and sacale it to the magnitud you need.

```
jump_velocity = rotateHalfTurn(unit(gravity)) * initial_velocity

```

The quarter turn and half turn rotations are easy. For a half turn - counterclockwise - rotation, you flip the components (X becoems Y and Y becomes X) and change the sign of the new X. And of course, you can reverse the process to rotate the other way. For half turn the short-cut is to change the sings of both components.

```
rotateQuarterTurn(v) = {x: -v.y, y: v.x}
rotateHalfTurn(v) = {x: -v.x, y: -v.y}
rotateThreeQuartersTurn(v) = {x: v.y, y: -v.x}

```

**Note**: This are equivalent as interpreting the vector as a complex number and multiplying by the imaginary unit multiple times. *No, that you need that fact, but it might help you link the concept.*

This way, you will be able to create your velocity vectors for the jump.

---

## Other rotations

So, you want to know if the character is falling. *For whatever reason.* But your coordinates are not aligned with the gravity vector.

If the gravity vector is just rotated a multiple of quarter turns, you can rotate the velocity of your character accordingly, and then check the component you need.

That is, if you need to check that the Y component of the velocity is greater than 0 when gravity is down... but gravity has been rotated a quarter turn, you rotate the velocity of the character a quarter turn too and then check the Y component of the resulting vector.

This will be more problematic if the rotation is not a multiple of quarter turns. To solve those, we can do some trigonometrics.

To rotate by an arbitrary angle... just get the formula:

```
rotate(v, theta) = {
                       x: v.x * cos(theta) - v.y * sin(theta),
                       y: v.x * sin(theta) + v.y * cos(theta)
                   }

```

We can begin understand this as defined an inclined line by an angle, and then walking a certain length along that line, and then figuring out where we end. In that case we have a length over the hypothenuse, one adjacent angle, and of course the opposite angle to the hypothenuse is a right angle... then we solve with trigonometrics.

However, we do not only have movement along the line, but also across (perpendicular). We have to solve a second triangle for that, then simplify and you get these formulas.

You will also find these emerge if you consider the vector a complex number, and we describe rotations by euler to the power the imaginary unit multiplied by the angle... and then when we separate the components we get trigonometric functions by the euler's formula. *Again, not that you need to know that, but it could be useful to link some concepts.*

Notice that both X and Y components affect both of the resulting components. *Unlike the scalar product where X only affects X.*

---

## Matrix transformations

**Note**: please use a library that provides vector and matrix operations.

We can put the transformation described by a rotation by an arbitrary angle in a matrix. And then we multiply by this matrix to transform the vectors.

```
                   |¯ cos(theta)   -sin(theta) ¯|
rotate(v, theta) = |                            | * v
                   |_ sin(theta)    cos(theta) _|

```

The product works like this:

```
|¯ A  B ¯|   |¯ v.x ¯|   |¯ v.x * A + v.y * B ¯|
|        | * |       | = |                     |
|_ C  D _|   |_ v.y _|   |_ v.x * C + v.y * D _|

```

As you can imagine, we can multiply by multiple matrices to apply multiple transformations. In fact, we can compose transformations by multiplying the matrices.

This is also useful to apply the same transformation to a large number of vectors. In particular if we can take advantage of SIMD to do matrix multiplication, or if we can get the GPU to do them for us. *That is beyond the scope of this answer*.

Futhermore, if we compute the multiplicative inverse of the matrix, we will have a matrix that reverses the transformation. Alternatively, you can create an method that does the inverse of the matrix product.

You will find that this matrices are also useful to describe scaling, shear and other transformations aside from rotation.

---

You will also find augmented transformation matrices (those are matrices with an extra column) with translation information.

I like to resolve them as a 3 by 3 matrix with the last row being 0, although that can make the inverse a bit complicated. Usually you do not have to implement this (you use a library), just in case, this is a solution:

If we have a matrix:

```
    |¯ A B C ¯|
M = |  D E F  |
    |_ G H I _|

```

Then:

```
transform = function (m, v) {
    var w = v.x * m.g + v.y * m.h + m.i;
    var x = (v.x * m.a + v.y * m.b + m.c) / w;
    var y = (v.x * m.d + v.y * m.e + m.f) / w;
    return new Vector(x, y);
};

transformInverse = function (m, v) {
    var w = (v.x * (m.d * m.h - m.e * m.g) + v.y * (m.b * m.g - m.a * m.h) + m.a * m.e - m.b * m.d);
    var y = (v.x * (m.f * m.g - m.d * m.i) + v.y * (m.a * m.i - m.c * m.g) + m.c * m.d - m.a * m.f) / w;
    var x = (v.x * (m.e * m.i - m.f * m.h) + v.y * (m.c * m.h - m.b * m.i) + m.b * m.f - m.c * m.e) / w;
    return new Vector(x, y);
}

```

**Note**: Yes, that code is for 2D vectors. You can simply it if `m.g == 0`, `m.h == 0` and `m.i == 0`.

---

## Coordinate systems

You can understand the default location, orientation and scale of your world as a coordinate system.

We can do the same for the view port... for example, the upper left corner is usually the origin, and the axis are aligned with the screen, with the vertical one being positive downwards, and une unit is a pixel.

However, even if the axis of the world are aligned with the view port, the origin usually isn't. This way, you can implement a camera that follows the playwer along the world.

Then, to transform a position from the world coordinates to the view coordinates, we can use a matrix transformation (that will automatically support rotation, flipping axis, scaling zooming, and similar effects). And if the player click on the screen, and we want to know what on the world is there, we can do the inverse transformaton to get wolrd coodinates from screen coordinates.

Futhermore, we can have auxiliary coordinates systems. For example, if we have an elevator (a moving platform), instead of having it push the objects on top of it by collision and physics engine, we can *hack* it by defining the position of those objects respect to the position of the elevator.

Under the same idea, it is possible to construct esqueleton animation if we place *bones* respect to each other. For instance, the weapon is placed respect to the hand, the hand is placed respect to the arm, and so on.

**Notes**:

* In the above paragraphs, read "respect to" as "using a matrix transformation relative to".
* What I describe here is not appropiate for every game, it may not be a good idea for yours, however it is a tool you are better of being aware of.
* When I said that you rotate the velocity the same way that you rotated the gravity, what I should have said is that you transform the velocity to a coordinate system that is rotated according to the gravity vector. However, I had not explained what that means yet.

---

## Convergence

If we want a measure of how similar is the direction of two vectors. We can use the dot product:

```
 dot(va, vb) = va.x * vb.x + va.y * vb.y

```

**Note**: that is a dot product, from now on I will write it as `va · vb`, and we will computed as described above.

The dot product is also equivalent to:

```
 va · vb = norm(va) * norm(vb) * cos(angle(va, vb))

```

As you know, if both vectors go in the same direction, the angle between them will be 0. And the cosine of 0 is 1 (which is the maximun value for cosine). On the other hand, if the vectors go in opposite directions, the angle between them will be a half turn. And the cosine of half turn is -1 (which is the minimun value for consie).

Thus, dot product will give you a measure of how convergent the vectors are (how similar is their direction).

**Addendum**: for a quick and dirty check of convergence, we can check if the vectors are in the same quadrant. As you may already know, we can get the angle of a vector (respect the horizonal axis) with `atan`. And we can use `atan2` for an angle that allows us to check the quadrant (just by checking how many quarter of turn fit in the angle).

We can go an step futher and solve `angle(va, vb)` out of the equation above:

```
 va · vb = norm(va) * norm(vb) * cos(angle(va, vb))

 =>

 (va · vb)/(norm(va) * norm(vb)) = cos(angle(va, vb))

 =>

 arccos((va · vb)/(norm(va) * norm(vb))) = angle(va, vb)

```

And of course, we already have a way to compute the dot product.

---

## Curl

Some times we need an idea of the rotation of angles. For example, if we have a series of angles that describe a polygon, and we want to know if the polygon is concave or convex. We can do this with a projection of the cross product of the vectors.

The cross product exists in 3D. What we will do is assume Z = 0. The resulting product is a kind of wedge product (which is the name I will use here), and can be computed as follows:

```
 wedge_product(va, vb) = va.x * vb.y - va.y * vb.x;

```

You will find that if the vectors converge, the wedge product is 0. The value will be positive if the rotation from va to vb is counterclockwise, and negative otherwise.

There is a link between this and the sine of the angle between the vectors, however that is clearer in 3D and I will not go there.

---

## Projection, rejection and reflection

While these names imply light (for example, we have a light source and we want to compute where the shadow is projected over a given surface), they are an useful tool in solving collisions (I consider collisions beyond the scope of this answer).

To do a projection of a vector over another, we need a vector that goes in the same direction as the other vector. In fact, what we want is to rotate the first vector to a coordinate system that is rotated according to the second vector. And then take the component that goes in the same direction of the second vector.

*Yes, that is the thing you do for the velocity and gravity. You are projecting it.*

Now, using matrices to do a projection is overkill. We have a simpler solution:

```
project = function (a, b) {
    var factor = (a.x * b.x + a.y * b.y) / (b.x * b.x + b.y * b.y);
    return new Vector(b.x * factor, b.y * factor);
}

```

**Addendum**: What you get from the projection is a vector. That vector is the component of of your projected vector that is in the direction of the vector over which you projected... expressed in your regular coordinate system. If you want to know how long that component was, you take the norm of the projection. However, note that you lose directionality when you take the norm (by squaring the components their sign is lost), so a measure of convergence (read "convergence" above) can help you know if the vector goes in the same direction or against.

---

If the projection is the component that goes along the second vector. The rejection is the other component. Or, the vector that goes from the projection to the original vector.

```
reject = function (a, b) {
    var factor = (a.x * b.x + a.y * b.y) / (b.x * b.x + b.y * b.y);
    return new Vector(a.x - b.x * factor, a.y - b.y * factor);
}

```

---

Finally, a reflection is what you use to bounce along an inclined surface. As you know, the angle to the normal must be preserved (that is, we flip along the normal):

```
reflect = function (v, normal) {
    var val = 2 * ((v.x * normal.x) + (v.y * normal.y));
    return new Vector(v.x - (normal.x * val), v.y - (normal.y * val));
}

```

---

## Your questions

> In that case, pressing left would cause the player to move downward on the screen, as that would be left relative to the current angle of gravity.

This makes me think that you either: A) want to rotate the world instead of rotating gravity (which I have mentioned how to do, read "coordinate systems" and "matrix transformations"). Or B) you will define the effects of the input commands in terms of the gravity, in which case you will have to transform them accordingly (which I have mentioned too, read "other rotations" and "matrix transformations").

> As I'm now realizing, I lack the mental language to even properly describe my problem, but I clearly don't intuitively grasp how to handle rotated vectors.

Hopefully I have fixed that, or at least gave you keywords to search.

> Normally I'd just check if their velocity.y \> 0, but that only makes sense if gravity is pointing downward. If it's pointing to the right, then a velocity.y \> 0 implies that they're moving to the left, relative to gravity.

You can use projections for the check. The concept of "relative to gravity" is the coordinate system rotated according to gravity. If projections fall short of what you want to do, use matrix transformations (I think you will end there anyway, given the other things you mention).

> How do I go about understanding and working with 2D vectors that have an arbitrary global rotation applied to them?

You are working on a different coordinate system, one that is rotated. And that you can describe with a matrix transformation.

---

I will plug other two other answers by me here:

---
Tags: 2d, rotation, vector, orientation
---


title: For loop only checking the last object

text:
# Question
Title: For loop only checking the last object
Hi I am using a for loop to check and see if my players character is colliding with a collision object in the game. But for some reason it only checks the last Rectangle of the list.

```
private void collisionDetection()
{
    for(Rectangle rectangle : colrect) {
        Rectangle rect2 = new Rectangle(posX, posY, 64, 64);
        if (rectangle.overlaps(rect2))
        {
            m.setTileCollision(true);
        }
        else
        {
            m.setTileCollision(false);
        }
    }
}

```

Why and how is this happening? I gave up on looking for an answer so I'm here. I want to check all of the Rectangles in the list not the last... I even for looped text through Bitmap font to see the positions and set text at all Rectangles and that works properly, but this doesn't. Another solution perhaps is in order?

# Answer
> 3 votes
This is because you are (presumably) overwriting the `tileCollision` boolean for every rectangle you check. Changing your if-statements to something like this might do the trick:

```
m.setTileCollision(false); // Do this OUTSIDE the for loop

// Then, inside the for loop...
if (rectangle.overlaps(rect2)) {
    m.setTileCollision(true);
    break; // No need to check the other rects, we already found a collision
}
// Remove else statement since it's no longer needed

```

---
Tags: libgdx, collision-detection
---


# Question
Title: Implementing a score system similar to Moon Patrol
I am working on an Android game scenario inspired by Moon Patrol.

My beta version is available for beta test from https://play.google.com/store/apps/details?id=dev.android.buggy

In my case, I got the elapsed time in seconds for reaching a checkpoint, and I could reward either a fixed bonus or a bonus based on the time, perhaps the difference between the time and the average time, or another bonus if it is a high score. My specific implementation for completing a checkpoint looks as follows at the moment:

```
if (checkpointComplete) {
    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //
        }
    });
    canvas.drawColor(Color.BLACK);
    ((ParallaxActivity) getContext()).stopWatch.stop();
    paint.setTextSize(60);
    String s2 = "TIME TO REACH POINT \"" + Background.checkpoint + "\"\n";
    if (runOnce) {
        for (int q = 0; q < s2.length(); q++) {
            final String s2f = s2;
            final int r = q;
            ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    checkpointtextview.setTextColor(Color.RED);
                    checkpointtextview.append(Character.toString(s2f.charAt(r)));
                }
            });
            try {
                Thread.sleep(50);
            } catch (InterruptedException ie) {
            }
        }
    }
    String str = String.format("%03d", ((ParallaxActivity) this.getContext()).countUp);
    String s3 = "YOUR TIME                :   " + str;
    if (runOnce) {
        for (int q = 0; q < s3.length(); q++) {
            final String s3f = s3;
            final int r = q;
            ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    checkpointtextview2.setTextColor(Color.parseColor("#ADD8E6"));
                    checkpointtextview2.append(Character.toString(s3f.charAt(r)));

                }
            });
            try {
                Thread.sleep(50);
            } catch (InterruptedException ie) {
            }
        }
    }
    runOnce = false;
    // canvas.drawText("CHECKPOINT COMPLETE", (float) (screenWidth * 0.35), (float) (screenHeight * 0.45), paint);
    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((ParallaxActivity) getContext()).startTime = SystemClock.elapsedRealtime();
                    ((ParallaxActivity) getContext()).stopWatch.setBase(((ParallaxActivity) getContext()).startTime);
                    ((ParallaxActivity) getContext()).stopWatch.start();
                    checkpointtextview.setText("");
                    checkpointtextview2.setText("");
                    checkpointtextview3.setText("");
                    checkpointtextview4.setText("");
                    checkpointtextview5.setText("");
                    checkpointtextview6.setText("");
                    String str = "Player 1  " + String.format("%06d", score);
                    tvId.setText(str);
                    scoring = false;
                    buggyXDistance = 0;
                    distanceDelta = 0;
                    retardation = 0;
                    checkpointComplete = false;
                    runOnce = true;

                }
            }, 3000);
        }
    });
}

```

I want to calculate bonus for completing a checkpoint but how is it calculated? If we look at the original it looks like below.

Is it possible to deduce the formula for calculating the bonus? My bonus screen looks the same. So if your time is x and the average time is y and the record is z, what is the formula?

# Answer
The formula is available at this link:

```
COURSE ONE                                POINTS
Completing each section of five markers     1000
Each second under 55 seconds it takes        100
to complete section 1 or 2
Each second under 60 seconds it takes        100
to complete section 3 or 4
Each second under 65 seconds it takes        100
to complete section 5
Completing the entire first course          5000

```
> 1 votes

---
Tags: mathematics, algorithm
---


title: Map progression

text:
# Question
Title: Map progression
I’m developing a 2d Metroidvania Game with a few huge (separated) Areas. In an in-game Menu the Player will be able to view a Map of the current Area. For this Map I want to implement a Map progression.

At first the complete Map is blacked out. When the walks around, the Map will become visible (coloured) at those Positions. Further more there will be several Shrines in an Area which make parts of the Map semi-visible (greyed).

Since the Map has three States: Unknown (blacked), Known (greyed) and Visited (coloured), I thought of a Graph (for each Area) which nodes represents small section of an Area. But the Areas are quite large and the section must be very small therefore the Graph seems impractical (too many Nodes).

Another Idea was to use an Alpha-Map with some kind of a Brush and everywhere where the player walks this brush paints the Alpha Map (at those positions) white. And for the Shrines pre-painting Paths manually (in grey) and set them on the Alpha Map if the Player activates a Shrine. But since the Areas can change (for better balance or to remove glitches/bugs) I would constantly have to repaint those Paths.

So has anyone some better ideas how to create a map progression?

# Answer
> 2 votes
You could draw just one colored map and use the least significant bits of each RGB component to convey a state (part of a shrine, visited). Your brush would flip these bits according to the player's movements and your needs.

---
Tags: 2d, game-design, maps
---


# Question
Title: How to add custom control shapes to a rig in Maya
I find most Maya animation videos has these circle lines to control character part rotation:

Why does my imported fbx not have these circle lines?

# Answer
In Maya those are controls set up as part of the rig for the character so that the animator can easily move the character around and set keys on the controls and not the geometry. I'm not sure what fbx is (as I am just a student studying animation using Maya), but you might want to google how to create your own controls (creating controls using nurbsCurves and set driven keys or costume attributes), or how to move your fbx without the controls.
> 0 votes

---
Tags: animation, maya, rigging
---


# Question
Title: Unable to enable IK on someone else's rig
I'm using someone else's character rig for reference but I'm not sure how I can enable IK solvers for the arms. The hand controller has a NURBS control with an ikBlend attribute, but when I try to use the "Enable IK Solvers" tool, I get an error saying the attribute is locked or connected.

Clicking "Unlock Selected" on the attribute doesn't fix it. Breaking the connections also breaks the ability for it to drive the enabled/disabled state of the IK handle.

The rigged character can be downloaded here if anyone wants to try to help me out: http://www.antcgi.com/2014/06/03/free-model-15-kila-lods-rig-dynamics/

# Answer
I can't seem to download the file to try it out for you (it says page not sound). But you could try, instead of using the button, look in the channel box, where it says IK Blend type in 1 and see if it changes, or click in the nurb control that looks like a hand and look in that channel box for the same thing and try it there. Otherwise could your try posting your file then I could have a look.
> 0 votes

---
Tags: animation, maya, rigging
---


# Question
Title: Vertex with too many connections in Maya
After some mesh editing in Maya I got one vertex with a lot of connections. Please help, how can I fix it? Don't even know how to google it.

# Answer
> 1 votes
If it were me, I would delete the faces connecting to that single vertex and the just re connect or clean up those areas how you want them to look. Its possible that you might have merged some vertices by accident. You can also try selecting the vertex and go to Edit Mesh \> Detach , this will disconnected them from each other so that you can move them how you want it to be.

---
Tags: 3d, maya
---


# Question
Title: make a unified image out of many sprites in unity
i made a customization character system that it has a seperate image UI for every part f body like eyes, hat, ears and...

now i want to make a unified texture out of it to be able to save it as an image file. how can i do this?

# Answer
> 2 votes
You could set up a second camera which would look at a copy of each of the UI elements making up the character on a background of your choice, make it render into a render texture and then blit that texture to a Unity Texture2D which has a method to EncodeToPNG() on that page there's also a good example of how to use it for what you want.

---
Tags: unity, gui, unityscript
---


# Question
Title: What's the use and difference between Forward, Deferred and Physically Based Rendering?
Maybe I'm still confused about my own understanding,

* **Forward Render**: render the lighting of an object according to the light source in the scene. (e.g Phong)
* **Deferred Render** : render the scene to get geometric information, store it in a buffer, and then apply lighting. (e.g ?)
* **PBR** : treats lights in the scene the way it behaves in the real world. (e.g Ray tracing, Photon Mapping)

I don't see how Forward and Deferred render are going to give much difference to the scene. Why do we need to store the geometrical value in Deferred Render before applying lighting ? Why don't we just compute lighting right away like Forward Render ?

Also for Physically Based Rendering, computing each light takes a lot of time, and almost impossible to be done in real time. But why this technique is always considered the best ?

# Answer
First, I wouldn't consider PBR to be separate from forward or deferred rendering. You can use PBR in either forward or deferred rendering, as I understand it. Physically-based rendering just means trying to simulate the actual physics of light. This gives more realistic results than other techniques, but like all techniques, it involves trade-offs between speed and accuracy.

I think your understanding of forward deferred rendering is correct. One issue you can run into with forward rendering is that there is a limit to the amount of data you can send to a single shader. If you have 100s of lights, you need to send the position, direction, type, color, etc. for each one to the shader. You can hit the limits of number of allowed uniforms in scenes with lots of lights. It's also possible to hit the limit of how much work can be done in a given draw call. I've had the OS kill drawing when a single shader took too long. (This was not with a game, though.) With deferred rendering, you simply make multiple passes sending a subset of the number of lights to each pass. Note, though, that every pass you add adds a lot of overhead to the rendering, making it slower.

> I don't see how Forward and Deferred render are going to give much difference to the scene.

The results of forward and deferred rendering may in fact be the same if you're sending the same numbers of lights and rendering them the same.

> Why do we need to store the geometrical value in Deferred Render before applying lighting? Why don't we just compute lighting right away like Forward Render?

If you computed it right away, it wouldn't be deferred anymore. That's the difference between the 2. Deferred rendering renders the geometry without taking into account lighting, then in subsequent passes calculates the lighting. Forward rendering does it all at once. (There may still be multiple passes for other reasons, like depth-peeling, etc.)

> Also for Physically Based Rendering, computing each light takes a lot of time, and almost impossible to be done in real time. But why this technique is always considered the best?

Computing each light takes more time than for something simple like Phong, but I wouldn't say it's "almost impossible to be done in real time," as there are plenty of games out there using it now. "Best" depends on your goals. If your goal is to run on low-powered hardware, PBR might not be best. Currently it gives realistic results, so it's easy for artists to understand (in that it matches the world they live in) and looks "right" to players. But it has limits, like any technique. It's been popular recently because it's been new and effective, when used appropriately.
> 2 votes

---
Tags: rendering, lighting, deferred-rendering, pbr
---


# Question
Title: MySQL for MMO-Development... What do i have to consider ?
Im currently developing an little mmo. Its pretty basic, players can walk around... gather some resources... build some simple buildings and craft things.

Before i began to develop i read a lot about benefits using MySQL... Now im not sure if MySQL was the right choice for such a project.

Currently i store player specific data in real time, that means... once a player crafted, builded or gathered something, a server request is send which triggers a MySQL - Query to insert a new Row into the specific table. This happens **everytime** a player moves, crafts, gathers or builds something.

I dont only store player-specific data in those tables... also world specific data, for example if one player visits a zone which was last updated 6 hours ago, i refresh this zone with resources and mobs. The server is generating them and after that, it inserts them as a bulk into the database.

With only one active player this works fine... but i have no idea if this will still work with dozens or hundreds active players at the same time. The serverside itself is able to handle them... but i have no idea if the database is able to.

I also heard bad stuff regarding table locks... That this is somekind of major iusse using MySQL, how does this effect dozends of database actions per seconds ? And could possible "share" be a solution for this ?

What else do i need to consider while using MySQL for a mmo ?

# Answer
Overusing the database like this is usually a very bad idea.

Database queries always require a network roundtrip between game server and database server. Even under ideal conditions (both run on the same physical server), those latency times are still magnitudes larger than accessing data you have in RAM.

So only use your database for data at rest. Use it to suspend the states of players who are currently not online. But any data about the players currently in the game should be in the game servers memory.

You might want to regularly suspend the ingame players so you don't lose too much game progress in case of a server crash. But this should happen every few minutes at most.
> 4 votes

# Answer
It's a trade-off between performance and data consistency.

A method that's often used in these kind of situations is saving data on specific intervals. For example, there's no reason to store the player's position in the database every time the player moves. This can easily be updated in the database every minute or every few minutes. The same goes for the player's stats, inventory, bank etc.

For more critical actions you can consider saving data immediately. It just depends on how often a specific action is done and how important the action is.

Also - mobs and depletable resource usually aren't added to the database when they spawn. That's a server state that's usually reset on server restart. When a user enters a zone that's empty of resources and mobs, just spawn them and leave it at that, no need to store this in your database.
> 2 votes

# Answer
I agree with what Basaa and Philipp said, but I'll add this:

A design like you're talking about isn't completely impractical (well, storing *every player movement* is, but in general i mean writing lots of data to your database often), but MySQL is probably the wrong choice\* for such a design.

MySQL and most relational SQL databases are usually optimized to be read-heavy. But the architecture you're talking about is hugely write-heavy. Unless you need the benefits of a relational database (i.e., relations - joining tables, ensuring constraints, etc) then I'd recommend starting with a NoSQL database that's more write-friendly. I'd recommend redis \- while it's not *perfect* for your needs, it's simple to set up and use. It will handle *a lot* more writes than MySQL.

---

(\* The situation is actually a lot better now than it was 5 years ago. There are multiple write-optimized storage backends for MySQL that have come out. But IHMO, those are fixes for an existing problem. Especially if you don't have an experienced DB admin, you'll be setting yourself up for a lot of work just on DB tuning with MySQL.)
> 2 votes

---
Tags: unity, architecture, mmo, server, mysql
---


# Question
Title: Godot installation errors: cache directory path, EditorSettings config path
I am using Windows 7. After installing Godot from a browser, I get two errors:

```
OpenGL ES 3.0 Renderer: GeForce GTX 980/PCIe/SSE2
ERROR: EditorSettings::create: Cannot find path for cache directory!
   At: editor\editor_settings.cpp:756
ERROR: EditorSettings::save: Cannot save EditorSettings config, no valid path
   At: editor\editor_settings.cpp:934

```

I am new to game engines, and I don't really understand what these errors mean. I had a similar problem with Unity before I gave up on it.

**Edit 01:**

If it helps any, when I try to open a demo project in Godot, it crashes and suggests I use Visual Studio to debug it. If I do this, the Visual Studio debugger reports this:

```
Unhandled exception at 0x0000000140003F05 in Godot_v3.0.2-stable_win64.exe: 0xC0000005:
Access violation reading location 0x0000000000000000.

```

# Answer
> 2 votes
After buying the book Sams Teach Yourself Godot Engine Game Development written by Ariel Manzur and George Marques, I have come across the solution, though I don't believe I can fully articulate what the problem actually is.

From the book:

> Godot usually stores the user settings in a global folder for the user profile (%APPDATA% on Windows, ~/.local/share on Linux, and ~/Library/Application Support on macOS). If you are running multiple versions or want a portable mode this behavior might not be desired. To fix this, you can run the editor in a self-contained mode. This is easily accomplished by adding an empty file called .\_sc\_ (or just \_sc\_ if you're on Windows) in the same folder as the executable. Godot will then create an editor\_data folder in the same place where all the settings will be stored. Note that temporary files are also stored there, so the folder can become quite heavy if there are many projects or big ones.

I inserted this \_sc\_ file into my Program Files folder where I stored the Godot application. From this point, I must launch the program in Administrator mode every time I use it. I am able to avoid my previous launching errors in this way, and the program no longer crashes.

---
Tags: godot
---


title: Rendering an isometric tilemap

text:
# Question
Title: Rendering an isometric tilemap
I have a tile which is 512x256 pixels and I'm trying to render it in an isometric fashion.

I have this helper function:

```
Pos cartToIso(Pos p) {
    xa := p.x - p.y;
    ya := (p.x + p.y) / 2;
    return new Pos(xa, ya);
}

```

And to render I do this:

```
// note this is smaller than the image since
// it's being scaled down
const tileWidth = 256;
const tileHeight = tileWidth / 2;

for (int y = 0; y < 32; y++) {
    for (int x = 0; x < 32; x++) {
        int ya = y * tileWidth;
        int xa = x * tileHeight;
        Pos p = cartToIso(xa, ya);

        drawImage(grassTile, p.x, p.y, tileWidth, tileHeight);
    }
}

```

This nearly works but there is a big black gap around the tiles. It's fixed when I change the rendering to this:

```
// note this is smaller than the image since
// it's being scaled down
const tileWidth = 256;
const tileHeight = tileWidth / 2;

for (int y = 0; y < 32; y++) {
    for (int x = 0; x < 32; x++) {
        int ya = y * tileHeight; // <- here!
        int xa = x * tileHeight;
        Pos p = cartToIso(xa, ya);

        drawImage(grassTile, p.x, p.y, tileWidth, tileHeight);
    }
}

```

But why? This seems to be counter-intuitive compared to what the isometric 2d tutorials I have read have said.

Is there a flaw to my rendering logic?

# Answer
Isometric Grids have the property of being Equilateral; which is to say that all four sides are the same length. By attempting to paint the texture in a 2x1 fashion, you're saying "don't fill in some of these pixels" giving you black edges (presumably quite thick ones) between the tiles.

---

IMO, You should probably be using an equilateral texture rather than one that is either going to be:

* Compressed in one direction by 2x
* Chopped off at the mid point in one direction
* Leave empty space (as happened in your case)
> 1 votes

---
Tags: java, mathematics, rendering, isometric
---


# Question
Title: How can I handle sharing storage units in multiplayer?
I have recently come across a certain problem in programming my MMORPG: the synchronization of shared storage units.

With shared storage unit I intend something like a "chest" that can be accessed by multiple users. Any user can take items from it or put items in it or even move items around and merge items stacks in the chest. To get the idea, think about the guild chest in WoW.

At the moment my approach with non-shared storage is to apply any transaction on the client (move/split/merge they take place instantly on the client) and then communicate to the server the change which also does validation and stuff. This works just fine: it's rather impossible that one client issues a transaction that would conflict with another of its transactions as he always sees an updated state of the storage (because he/she is the only one issuing transactions on that storage).

How do you keep a storage synchronized among its co-owners when they share a storage unit and therefore can issue conflicting transactions? For example: two players issue at the same time a move transaction of the same item.

An approach I was thinking about is scratching client-side prediction for shared storage but that adds some overhead to my work as clients at the moment are not aware (code-wise) that a storage unit is shared. Is there a smarter way to do it?

# Answer
To eliminate the possibility of conflicting transactions, the best (and also the easiest!) thing would be to queue the requests you get, and execute them in chronological order. Update their view once a transaction is complete; if they happened to submit the same request as somebody else, the queue will ensure that the person who did it first will have their request processed. Let the other person know that their request couldn't be completed because somebody else already grabbed the item.
> 2 votes

# Answer
What most games do is send a message to the server when the player starts interacting with the chest. The first player to do so gains exclusive access, until they send a message that they're done using it, and any other player trying to access the chest fails (e.g. gets a message that it's busy). If you make your inventory transactions on those chests require that the player is the one using the chest, then such collisions can't happen.
> 1 votes

---
Tags: networking, mmo, client-server, synchronization, inventory
---


title: ReorderableList in Unity with Enums

text:
# Question
Title: ReorderableList in Unity with Enums
I'm trying to setup a simple ReorderableList in Unity 2017.3 for a list of enums. Adding items workes fine but selecting, dragging and deleting items from the list does not (see gif).

Here is my code:

```
[Serializable]
public enum RoofType { HIP, GABLE, FLAT, NONE }

UnityEditorInternal.ReorderableList roofTypeList = new UnityEditorInternal.ReorderableList(roofTypes, typeof(RoofType), true, true, true, true);
roofTypeList.drawHeaderCallback = (Rect rect) =>
{
   EditorGUI.LabelField(rect, "Roof types");
};
roofTypeList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
   roofTypes[index] = (RoofType)EditorGUI.EnumPopup(rect, roofTypes[index]);
};
roofTypeList.DoLayoutList();

```

Any ideas why this does not work? My guess it is because I use enums and not classes but it is not documented anywhere.

# Answer
> 1 votes
It looks like you may be re-creating the ReorderableList on each execution of OnInspectorGUI(). Unlike other types of inspector UI elements, this one should be instantiated elsewhere, and a reference to that instance should be used in OnInspectorGUI() instead. For example (based on this article):

```
public class MyListEditor : Editor
{
    private ReorderableList list;
    private void OnEnable()
    {
        list = new UnityEditorInternal.ReorderableList(roofTypes, typeof(RoofType), true, true, true, true);
    }
    public override void OnInspectorGUI()
    {
        list.DoLayoutList();
    }
}

```

I'll also note that the above linked article recommends using the SerializedObject version of the ReorderableList() constructor. Give that a try if you're still having trouble.

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


# Question
Title: Why doesn't Unity let me build my project with TextMeshPro after updating to Unity 2017.4.5?
I have recently upgraded to Unity 2017.4.5. This required me to reimport TextMeshPro which I used previously in the project. Now I am trying to build (Android, Windows) and it is giving me hell a lot of errors, but I do not have any when I want to run the project. It is yelling about TMP, it does not find specific scripts. I tried to move around the runtime and the editor dll, reimporting all, googleing the error message, but it did not help.
Please see my errorlog: http://pasted.co/35185b3c.
Thanks

# Answer
> 1 votes
Actually, the problem was the version of the TMP, I'd had . I had to delete the TextMesh Pro Unitypackage from my:

```
C:\Users\MYUSERNAME\AppData\Roaming\Unity\Asset Store-5.x\Unity Technologies\Unity EssentialsBeta Content

```

and then I reinstalled TMP from the Asset Store, and it works now.

This post might be helpful for someone else, that is where I found my answer.

# Answer
> 1 votes
Have you tried uninstalling and reinstalling the TMP package ? It seems like unity is not finding any of the file corresponding to the asset. I know I had ussues too with TMP when I upgraded my unity version but it was solved after reinstalling unity as a whole (I formatted my computer for other reasons)

---
Tags: unity
---


title: How to arrange child objects in a grid

text:
# Question
Title: How to arrange child objects in a grid
i have a gameobject that have a group of plane meshes that created randomly as child every one of this planes have a "2f" offset in x axis between every plane

what i wanna do is i wanna make the parent object arrangement the child objects on rows and columns even if one of this child deleted during the game or added so if i have 8 planes mesh it should look like that 2 rows and 4 columns like that but i don't know how to do that ?

i know how to get child objects and making offset but i do't know how to get the format like that in the image

i wanna to arrangement the planes meshes that i can acces from this for loop

```
 void Update(){
          Transform[] children = new Transform[transform.childCount];

                 //Debug.Log(transform.childCount);
                     for (int i=0; i<transform.childCount; i++) {
                         children[i]=transform.GetChild(i);

                     }
      }

```

# Answer
> 2 votes
```
private const int Columns = 4;
private const float Space = 2.0f;
private void ArrangeChildren(Transform[] children) {
    for (int i = 0; i < children.Length; ++i) {
        int row = i / Columns;
        int column = i % Columns;
        children[i].position = new Vector2(column * Space, row * Space);
    }
}

```

Whenever you want to perform the layout, collect the children into an array, as you have done in your example, then call this method, passing in that array. Note however that I would recommend not necessarily calling this in Update, if nothing else is changing the children. I assume the children are changed while running the game (otherwise you wouldn’t need to have code to arrange them) so you only need to run this when a child is added or removed. You can do this inside of the method `OnTransformChildrenChanged`:

```
private void OnTransformChildrenChanged(){
    Transform[] children = new Transform[transform.childCount];
    for (int i=0; i<transform.childCount; i++) {
        children[i]=transform.GetChild(i);
    }
    ArrangeChildren(children);
}

```

Finally, I left your method of collecting children into an array in place, assuming you needed that array for something else as well. If that’s not the case, then there’s no need to allocate extra memory or loop through the children twice:

```
private const int Columns = 4;
private const float Space = 2.0f;
private void OnTransformChildrenChanged(){
    for (int i=0; i<transform.childCount; i++) {
        int row = i / Columns;
        int column = i % Columns;
        transform.GetChild(i).position = new Vector2(column * Space, row * Space);
    }
}

```

Explanation:

The interesting part is in these three lines:

```
int row = i / Columns;
int column = i % Columns;
transform.GetChild(i).position = new Vector2(column * Space, row * Space);

```

So what does it do?

First we calculate which row it should be in, by dividing the current index by the number of columns we want to use. Since these are two ints, the result is rounded down. So for the first four children we are performing the calculations: 0/4, 1/4, 2/4, and 3/4, all of which round down to row 0. The next four calculations are 4/4, 5/4, 6/4, and 7/4. These all round down to 1. If you add more children, they would go into row 2, 3, and so on.

Then we calculate the column, by calculating the remainder of those divisions, using the modulo operator (%). Those first four calculations, again, were 0/4, 1/4, 2/4, and 3/4. The remainder of each of those calculations are 0, 1, 2, and 3, respectively. The next four calculations have the same remainders (4/4, 5/4, 6/4, 7/4 go to 0, 1, 2, and 3)

We have now generated the row,column pairs necessary for layout: 0,0 0,1 0,2 0,3 1,0 1,1 1,2 and 1,3

Now that we know which row and column they belong in, we just need to get the world coordinates of those rows and columns. If I understood correctly, you wanted them each spaced apart by 2 units, so we multiply the current row and column by 2.0. 1,3 for example becomes 2.0,6.0

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


title: What is ambient occlusion?

text:
# Question
Title: What is ambient occlusion?
I've heard about ambient occlusion and it looks nice, but what exactly is it?

# Answer
Ambient occlusion is a method to approximate how bright light should be shining on any specific part of a surface, based on the light and it's environment. This is used to add realism.

Wikipedia has a nice paragraph that explains what is done.

> Ambient occlusion is most often calculated by casting rays in every direction from the surface. Rays which reach the background or “sky” increase the brightness of the surface, whereas a ray which hits any other object contributes no illumination. As a result, points surrounded by a large amount of geometry are rendered dark, whereas points with little geometry on the visible hemisphere appear light.

Here is a highly technical article about it.
> 38 votes

# Answer
Ambient light is a light type in computer graphics that is used to simulate global illumination. Ambient occlusion is simply a simulation of the shadowing caused by objects blocking the ambient light. Because ambient light is environmental, unlike other types of lighting, ambient occlusion does not depend on light direction. As such, it can be pre-computed for static objects.

Without AO (left) Note that the shadow in the left image is caused by directional light, with AO (right).

In traditional Ray Tracing ambient occlusion is simulated by sampling rays from a certain point, which takes a shape of a hemisphere, and then is checked for intersection with the scene (also called Object Space AO).

Notice how ray samples are used to simulate AO integration.

Notice the aliasing (dots) caused by ambient occlusion under-sampling.

Because the ray tracing sampling technique is too slow to be used in real time computer graphics, other methods emerged that simulate this behavior. One notable approach is called Screen Space Ambient Occlusion (SSAO).

SSAO is a screen-space technique developed by Crytek. The ambient occlusion is computed in a full-screen pass, using the Z-buffer as the only input.

The ambient occlusion factor `kA` of each pixel is estimated by testing a set of points distributed in a hemi-sphere around the pixel's location. This effectively simulates the traditional ray tracing approach in screen space.

The value of `kA` depends on the samples that are in front of the value in the Z-buffer. If half or more of the samples pass a depth test (that is, they arec closer to the camera than the center pixel), then `kA` receives a value of 1. A smaller number of samples result `kA` less than 1.

SSAO component of a typical game scene
> 83 votes

# Answer
http://en.wikipedia.org/wiki/Ambient\_occlusion

Ambient occlusion usually means applying data that represents how much ambient light hits a surface. That data is usually a gray scale texture or vertex colors depending on the implementation.

To compute the data the most common way is the render the scene with with a solid white texture and 1 point light multiple times, moving the point light each time to a different location on a sphere or hemisphere. The results of all the renders are averaged and that gives you the data about each particular location in the scene and how much light hits that location.

For example a place in the scene that in always bright no matter where you put the light will be bright where as a place that is dark no matter where you put the light will be dark. The result is that you get something that will put dark shadows in crevices and cracks and soft lighting where objects would generally cast a shadow.
> 7 votes

# Answer
Ambient occlusion is a method to compute lighting on a surface of an object that takes into account light brightness due to occlusion of the surface in relation to light source.

That is, ambient occlusion is a shading method that is global in nature which means light/illumination from each point in a scene can influence other points in a scene. In contrast with local shading methods like Phong/Blinn, this means shading with ambient occlusion adds more realism.

Here is a bit of a simplified explanation. Ambient occlusion is a neat trick way of simulating global lighting which is faster than other methods we have so far. Rays are cast from every direction from a surface point 'up' in relation to the surface. Rays that do not reach any object in its path, that is they reach the background void threshold (the 'sky'), increase the brightness of the surface. Rays which, on the other hand, hit geometry when cast from surface, add no brightness to surface. So surface points which are surrounded by lots of other geometry are kind of in a shade.

SSAO is just one way of doing ambient occlusion.
> 3 votes

# Answer
Ambient occlusion means where the light doesn't reach. Creases, and crevices don't get any ambient light bouncing around so they are usually absent of most light creating "darkest darks" usually depending on the atmosphere.
> -2 votes

# Answer
Ambient Occlusion.. for those who are not really familiar with gaming graphics technology, ambient occlusion adds specific amount of light in every object in the scene. every polygons are rendered in different angle, in that case the amount of light is uneven that makes the game more realistic and appealing to eye
> -7 votes

---
Tags: graphics, rendering, terminology
---


# Question
Title: How to make a class diagram and data model of a Unity3D game?
I'm developing a 3D platformer video game on Unity3D and I've been asked to present its UML class diagram and data model. If I'm not mistaken Unity uses an entity-component-system, which necessarily doesn't use heritage. How would a class diagram from a Unity game look like, in that case?

Also, I've been taught that usually data model refers to entity-relationship-models that represent a database. In the case my game doesn't use a database, how could I diagram the way the player's data is store on the game? I'm storing the player progress on a file in the user's computer.

# Answer
> 2 votes
It is possible to have MonoBehaviours which use inheritance, but in most Unity projects that's rather the exception than the norm. So an UML class diagram focusing on inheritance for a by-the-book Unity project would show many, many classes all inheriting from `MonoBehaviour`. But to improve readability, framework classes are usually omitted from class diagrams, so you would have a bunch of stand-alone classes not connected at all.

That would obviously not be very useful.

But what you could do instead is visualize dependency relations. Whenever one of your behaviors uses `GetComponent<OtherMonoBehaviour>()`, that behaviour has a dependency on the other behaviour. UML class diagrams have an arrow for that. When a behaviour keeps references to a group of other behaviours, then you have an aggregation. There is also an arrow for that.

You could also stretch the definition of "class" a bit and display different types of game objects as if they were classes. In that case:

* Prefab relations could be visualized as inheritance
* Objects which contain sub-objects can be visualized as a composition

# Answer
> 1 votes
Definitely check out doxygen. It's an open source tool which generates an API reference like documentation from source code. It's not the slickest tool out there but it does the job quite well and is used by many.

I use it from time to time to generate a technical but visual overview of all of the project's components. You'll get a good representation of how your code is organized and identifiy some design issues just by looking at some boxes and arrows. doxygen supports a couple of different languages like C/C++/C#/Java, so there's no issue by using Unity. It probably won't show you everything but it's a good start.

This is the (admittedly a bit dusty looking) general style of what doxygen does for you:

---
Tags: unity
---


title: C++ in Unity with dependencies

text:
# Question
Title: C++ in Unity with dependencies
I am currently creating a c++ program to eventually use in Unity. This c++ program contains references to libraries like OpenCV and dlib, referenced with a include statement which calls in other files, which are installed on my machine. My question is:

How do you compile your c++ project so that it runs in Unity completely self-contained? i.e no reference to external files are needed, and all that are references are included within the program. Is there a specific tool to use, or a useful tutorial on the net?

Thanks for the help.

# Answer
> 1 votes
Unity is able to call functions from dynamically linked libraries using the plugin system. When you are using C++, then you are dealing with a native plugin. Keep in mind that native plugins are not platform-independent. So if you want to publish your game for multiple platforms, you also need to manually build your library in formats which work for these platforms.

Regarding adding files to your library: Microsoft Visual Studio can pack files into a compiled Windows DLL in form of "resources". I am not familiar enough with library development on other operating systems to tell if there are equivalent mechanisms.

However, if you designed your program as a stand-alone executable, then turning it into a library might require some refactoring. If you would prefer to avoid that, then there is another option: Run both your Unity game and your C++ program as separate processes and have them communicate through network messages. Check the documentation of the Unity Transport Layer API for details.

---
Tags: unity, c++
---


# Question
Title: Showing Frame Rate Info in the Unity scene using Custom Script failed
I want to lock the framerate of my scene to 30fps, then I learned from this post that fps info in Editor Stat isn't reliable, that's why my fps is still around 100. This is my script for setting the framerate (vSync also has been set into Don't Sync) :

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

public class TargetFramerate : MonoBehaviour {
    public int frame_rate = 30;

    void Start () {
    }

    void Awake (){
        QualitySettings.vSyncCount = 0;
        Application.targetFrameRate = frame_rate;
    }

    void Update () {
        if (frame_rate != Application.targetFrameRate) {
            Application.targetFrameRate = frame_rate;
        }
    }
}

```

But it doesn't work. Where should I put this script ? The description says in any GameObject will be ok, so I put in one of my GameObject with camera attached on it. By the way, I'm also using SteamVR camera script for my GameObjects (for HMD device), is it affecting this script ?

**\[UPDATE\]**

I posted the same question on Reddit, and got several feedbacks. So, the code that I used before from Wiki Unity 3D - FramePerSecond is outdated and using deprecated OnGUI system. As of now I'll try to use FPSCounter from the Standard Assets and see if it works.

Here's how it looks like on the scene using FPSCounter from Standard Assets, it works on the Game tab, but it doesn't show on the device (I'm using HMD- HTC Vive).

Also, my framerate lock code above doesn't seem to work, since the FPS is still reaching 90fps. Any advice ?

# Answer
> 1 votes
Per the documentation:

> * When using VR Unity will use the target frame rate specified by the SDK and ignore values specified by the game.

# Answer
> 0 votes
Add "GUI Layer" component to your main camera

---
Tags: unity, unityscript, frame-rate, steam-vr
---


# Question
Title: Emit particles from only some parts of a mesh
I have a 3D mesh with 3 sub meshes in it, for 3 different materials.

I would like particles to spawn from the mesh, but only from location where one of the material is assigned.

How can I make this happen?

# Answer
If I understand correctly, you have a mesh with multiple materials, each one applied to a certain part of the mesh, which Unity does using sub meshes. You then want to emit particles from one specific sub mesh.

If this is correct, then it should be fairly simple to achieve. You will need to extract the relevant sub mesh into its own distinct mesh, then create a particle system with its Shape module set up as type `Mesh` and the target mesh being the one you extracted. More information about the Shape module can be found here in Unity’s documentation. Note that your mesh must be marked as readable in its import settings.

A simple script that performs these operations (warning: untested):

```
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(ParticleSysfem))]
public class SetupMeshEmitter {
    public int submeshIndex;

    private void Start() {
        var sourceMesh = GetComponent<MeshFilter>().sharedMesh;
        var mesh = new Mesh();
        mesh.vertices = sourceMesh.vertices;
        mesh.triangles = sourceMesh.GetTriangles(submeshIndex);

        var ps = GetComponent<ParticleSystem>();

        //this section taken from Unity docs
        var sh = ps.shape;
        sh.enabled = true;
        sh.shapeType = ParticleSystemShapeType.Mesh; //just in case you forgot to set it up in the inspector
        sh.mesh = mesh;
    }
}

```
> 0 votes

---
Tags: unity, 3d-meshes, particles, materials
---


title: Realtime Goal Oriented Action Planning

text:
# Question
Title: Realtime Goal Oriented Action Planning
I've recently discovered GOAP and interested in implementing it for the AI in a game I'm developing. Something I'm stuck on at the moment, is determining **when** to plan. I've read through an MIT paper on it:

http://alumni.media.mit.edu/~jorkin/GOAP\_draft\_AIWisdom2\_2003.pdf

It mentions *real-time planning* and specifically:

> The character follows this plan to completion, invalidation, or until another goal becomes more relevant

Should I then be planning every frame until a new plan is deemed better (lower cost)?

And if not, if I have multiple goals but pre-requisites for one goal are only met in the middle of a plan for another goal, when would be appropriate to re-evaluate?

# Answer
> 2 votes
It's pretty dependent on what your goals and planning are. If you look at the real-time case where replanning would create a new goal,

> The character follows this plan ... until another goal becomes more relevant

The answer will depend on your goals and how often they change. If the goals change every frame, then it is reasonable to plan every frame. If your goals change rarely, then planning only makes sense when certain events occur.

> I have multiple goals but pre-requisites for one goal are only met in the middle of a plan for another goal

This could be implemented by only doing the planning phase only at the time when a potential pre-requisite condition is met.

# Answer
> 2 votes
Planning every frame is almost certainly overkill.

So planning only when an action fails, or a goal changes makes sense.

However, I would also re-plan every few seconds, even if the goal did not change. This will make your AI react better to changes in the world.

If your AI is currently executing an expensive and complex plan to achieve something, it could be that an event in the world suddenly opens up a much cheaper way to a goal.

For example, an NPC wants to eat, and planned to drive across town, go shopping for ingredients, find a stove, bake a pizza, and eat it. But a few seconds later, a passer-by drops his uneaten hamburger. Not carrying out the original plan seems a lot smarter.

If you plan every few seconds, your AI will seem smarter for it, more flexible.

# Answer
> 0 votes
I know, I'm late.

Game AI Planning update can be done anytime you want. For instance, the Killzone series AI Update is every 200 ms (i.e. 5Hz); this series of games (Killzone 2 and Killzone 3) uses HTN Planning (i.e. not GOAP). Transformers 3: Fall of Cybertron also uses HTN Planning and its AI Update is every frame.

GOAP implementations (F.E.A.R. games, Shadow of Mordor, Deus Ex, Tomb Raider, etc) generally update every frame.

Updating every frame means Planning runtime budget can fit in the AI-per-frame budget. What is yours? Then test your planner offline with problems from your games (as many tests as you can) and see whether this fits. If it doesn't, optimize your planner, as today, Game AI Planning is an established solution which can be called up to 50 times per frame (e.g. Shadow of Mordor).

---
Tags: ai
---


title: Estimating costs in a GOAP system

text:
# Question
Title: Estimating costs in a GOAP system
I'm currently developing a GOAP system in Java. An explanation of GOAP can be found at http://web.media.mit.edu/~jorkin/goap.html. Essentially, it's using A\* to plot between Actions that mutate the world state.

To provide a fair chance for all Actions and Goals to execute, I'm using a heuristic function to estimate the cost of doing something. What is the best way to estimate this cost so that it is comparable to all the other costs?

As an example, estimating the cost of running away from an enemy versus attacking it - how should the cost be calculated to be comparable?

# Answer
To make all the costs comparable, you only need to use the same heuristic for all actions. For example, all actions have a list of potential outcomes and all outcomes have a certain value to the entity.

For example, there's a deep pool with water, and the entity is thirsty. So we look at an action the pool has available to satisfy that need:

First the entity priorities associated with these places, you could call these the modifiers. Some of these will change with time and depend on the entity. For example an ant might worry less about staying alive and more about colony concerns. Or if an entity has gone a while without drink, the satisfy thirst priority may override others.

**Entity priorities**:

Satisfy thirst: 40
Stay dry: 10
Stay alive: 100

Then what the location represents:

**Location**: Pool
**Action**: Collect water
**Potential outcomes: **:
Satisfy thirst - (-95)
Get wet - 10
Drown - 1

So we could calculate that action cost at: (40\*-95) + (10\*10) + (100\*1) = -3600

Where collecting water from a raging river might look like:

**Location**: Raging river
**Action**: Collect water
**Potential outcomes: **:
Satisfy thirst - (-95)
Get wet - 90
Drown - 60

(40\*-95) + (10\*90) + (100\*60) = 3100

So it's clearly a better choice to collect water from the pool. Maybe if the raging river was the only choice the entity would wait until its satisfy thirst priority went very high before trying the river.

You may want to keep things much simpler starting out. Just have a few variables that can apply more globally. Like staying alive, satisfy needs. In your fight or flight example, you'd need to give each entity a combat rating, so they could effectively rank themselves against the other entity for score purposes.
> 4 votes

# Answer
I know, I know, it's been quite a while.

Indeed, in GOAP as implemented in 2005 by Jeff Orkin in F.E.A.R. (and reused in the sequels, extension and... Shadow Of Mordor), actions have fixed costs, ranging from 0.5 to 8. In general, the cost of attacking is much more expensive than the cost of defending. These costs can be accessed in the game database of the Free F.E.A.R. SDK (2008); here they are:

---

**{{Animate, 1}, {Attack, 6}, {AttackBurstLimited, 5}, {AttackCrouch, 5}, {AttackFromAmbush, 4}, {AttackFromArmored, 4}, {AttackFromArmoredBounded, 4}, {AttackFromCover, 4}, {AttackFromVehicle, 1}, {AttackFromView, 4.5}, {AttackGrenadeFromCover, 2}, {AttackLunge3D, 1}, {AttackLungeMelee, 1}, {AttackLungeSuicide, 1}, {AttackLungeUncloaked, 1}, {AttackMelee, 3}, {AttackMeleeLong, 1}, {AttackMeleeUncloaked, 3}, {AttackReady, 7}, {AttackTurret, 6}, {AttackTurretCeiling, 6}, {BlindFireFromCover, 2}, {Charge, 1}, {DeathOnVehicle, 1}, {DismountNodeUncloaked, 1}, {DismountVehicle, 1}, {DodgeCovered, 1}, {DodgeOnVehicle, 1}, {DodgeRoll, 2}, {DodgeRollParanoid, 2}, {DodgeShuffle, 3}, {DrawWeapon, 1}, {EscapeDanger, 0.5}, {FaceNode, 1}, {FlushOutWithGrenade, 3}, {Follow, 3}, {FollowHeavyArmor, 2}, {FollowPlayer, 2}, {FollowPlayerFidget, 1.8}, {FollowWaitAtNode, 4}, {GetOutOfTheWay, 1}, {GotoNode, 1}, {GotoNode3D, 1}, {GotoNodeDirect, 1}, {GotoNodeOfType, 1}, {GotoTarget, 4}, {GotoTarget3D, 4}, {GotoTargetLost, 8}, {GotoValidPosition, 1}, {HolsterWeapon, 1}, {Idle, 2}, {IdleFidget, 1}, {IdleOnVehicle, 1}, {IdleTurret, 2}, {InspectDisturbance, 2}, {InstantDeath, 1}, {InstantDeathKnockDown, 1}, {KnockDownBullet, 2}, {KnockDownExplosive, 2}, {KnockDownMelee, 2}, {LongRecoilBullet, 3}, {LongRecoilExplosive, 3}, {LongRecoilHelmetPiercing, 3}, {LongRecoilMelee, 3}, {LookAtDisturbance, 1.5}, {LookAtDisturbanceFromView, 3}, {LopeToTargetUncloaked, 1}, {MountNodeUncloaked, 1}, {MountVehicle, 1}, {ReactToDanger, 1}, {Reload, 5}, {ReloadCovered, 1}, {ReloadCrouch, 5}, {ShortRecoilMelee, 4}, {Stunned, 1}, {SuppressionFire, 2}, {SuppressionFireFromCover, 1}, {SurveyArea, 1}, {TraverseBlockedDoor, 1}, {TraverseLink, 2}, {TraverseLinkUncloaked, 1}, {Uncover, 1}, {UseSmartObjectNode, 3}, {UseSmartObjectNodeMounted, 1}}**

---

But it's not the case in all GOAP implementations and, for instance, the Tomb Raiders have variable costs (e.g. the distance for a Goto action).

Actions also have preconditions and some actions must be played despite the GOAP architecture (e.g. play a "stunned" animation in reaction rapidly decreasing health -- despite the "Kill Enemy" Goal and the plan that GOAP returns to satisfy that Goal). In your exemple, i.e. running away vs attacking, health level can be a precondition (and no need to have variable costs).

Or a Check\_Costs() member function is executed before anything else, based on Michael's priorities, and returns the dynamic cost.

Now, please note that in Shadow Of Mordor game developers tried to play with the costs of the actions in order to influence what would be executed on screen. It turns out that it's not that easy and even cheap action don't show up so often: AI in a game supports the player; if the player doesn't do what is expected, the AI will just support that and... what will appear on screen won't be what game design expected.
> 0 votes

---
Tags: java, ai, path-finding
---


title: Unity codeless IAP

text:
# Question
Title: Unity codeless IAP
So I'm trying the "new" codeless IAP. I followed the instructions exactly. On my old testing device I'm getting purchase Failed : Duplicate transaction. This is expected because the product is a NonConsumable and I have already purchased it. But on a fresh new device with the exact same build I'm getting a message in the google play pop up : The selected product is unavailable( note I'm translating the message bacause it returns it in Bulgarian, so the exact text may not be the same but the meaning is). Has anyone encountered this ?

# Answer
> 1 votes
> To test the IAP, make a purchase on a device logged in with an Alpha Tester Google Account. A modified purchase dialog box appears to confirm the fact this product is under test and is free.

Source: Test IAP Details

---
Tags: unity, android, in-app-purchase
---


title: How to do "realistic" plastic material?

text:
# Question
Title: How to do "realistic" plastic material?
How can i do "realistic" plastic material in Unity 3d , using standard shader or other shader ?

Can you suggest me options ?

Thanks

# Answer
Use a standard shader for simple materials. If you are looking how to modify the standard shader to achieve a plastic-y effect, consult the documentation on material effects.

On the site it says that

> There are also hints on how to make realistic materials in these charts. In essence it is about choosing a workflow (default or metallic) and obtaining relevant values for your maps or colour pickers. For instance, if we wanted to make shiny white plastic, we would want a white Albedo. Since it is not a metal we would want a dark Specular (or a very low Metallic value) and finally a very high Smoothness.

For more specific effects, you may need to make your own shaders.
> 2 votes

---
Tags: unity, shaders, materials
---


# Question
Title: How do you get main camera move along a specific route?
I've got a scene in the starting of my project, and what I want to do is to get my main camera move along a specific direction and route. Let's imagine I've got a 3-Dimensional array which contains The Positions of The points thereon. This is what I want to do :

1-Set the camera position on The first point and then go along with The other points, delay X milliseconds in each point and then go with the rest of it.

2-Whenever I will be able to change any of these parameters inside the script and programmatically:X,Y,Z components of The Position and Rotation of The Transform hierarchical property.

I'm sure enough trying to write an algorithm on my own would be a relatively difficult job, so please give me some tips and if possible a pseudo-code. And finally I want this script to be launched at the beginning of the scene.

# Answer
I found a solution, special thanks to @DMGregory : https://www.youtube.com/watch?v=TkVR2Mf\_U8Y

It explains about 2 scripts written in C# and in my opinion is a good illustration. Ready and written scripts, fully have described my problem. Also there is a download link for The script. I extremely suggest this video.
> -1 votes

---
Tags: unity
---


# Question
Title: TouchPanel.GetState() Returns wrong touch locations XNA
I am trying to make my Desktop game playable on IOS. I have a `Button.cs` class, which has this code in it:

```
   public bool IsPressed(TouchCollection touches)
    {
        for (int i = 0; i < touches.Count; i++)
        {
            if (TouchTriggerRect.Contains(touches[i].Position.X, touches[i].Position.Y))
            {
                return true;
            }
        }

        return false;
    }

```

Where `TouchTriggerRect` is a rectangle describing the button coordinates on the screen

I have noticed that the `IsPressed` method only works on some buttons (specifically, on all the buttons on the left side of the screen in **Landscape orientation**)

After some debugging, I understood that the `IsPressed` method doesn't work on the buttons placed on the right side of the screen because touches made there are getting offset by some random **X and Y**

Any suggestions on how to fix this bug? Or what can be causing this problem?

P.S I am using a `Monogame.Extended.Camera2D` in my game

P.S.S I have tried to build a simpler app, which draws red circles at all the touch locations it receives, and it workes perfectly. So, the problem is not in my devices

P.S.S.S This is how I get my touch Input: `touches = TouchPanel.GetState();`

**UPD:**

This is the code I use for my *transformations*:

```
var bounds = camera.BoundingRectangle;

Vector2 pos;

//The button is basically a rectangle, so I give it an X, a Y, a Width and a Height
JumpButton = new Button(bounds.Right - 80, bounds.Bottom - 74, 64, 64);
pos = camera.WorldToScreen(JumpButton.X, JumpButton.Y);
JumpButton.ScreenX = pos.X;
JumpButton.ScreenY = pos.Y;
//Same for all the other buttons

```

And this is the code for `TouchTriggerRect`

```
public Rectangle TouchTriggerRect => new Rectangle((int)ScreenX, (int)ScreenY, Width, Height);

```

# Answer
Problem solved by rebooting the mac, the device and the computer with VS
> 0 votes

# Answer
Okay, well your transformation code is very strange. It looks like you're trying to transform the position of the button rather than the position of the *mouse* or *touch* coordinates.

The way you need to think about this stuff is that your positioning things in "virtual space" and letting the viewport adapter and camera transform things into "world space" or "screen space".

To illustrate my point let's pretend this image is our "virtual space".

Our "virtual" screen is 200x150 pixels. We place our button at 50,50 and the button is 100x50 pixels in size.

However, when we render our virtual space on the screen what we end up doing is scaling everything up to the screen resolution or window size. So now our 200x150 image is actually rendered at 800x600 pixels.

On the actual screen our button is drawn at 200,200 and is 400x200 pixels in size.

But here's the kicker. When we touch the center of the screen at 400,300 we're getting our touch / mouse coordinates in "screen space". What we want to do now is translate our input coordinates back into "virtual space".

This is the purpose of the `WorldToScreen` method.

```
var vp = camera.WorldToScreen(touches[i].Position.X, touches[i].Position.Y);

```

Now that our touch position is back into virtual space we can simply check to see if it's inside our button. We don't need to transform the size or position of the button because it's already defined in virtual space.
> 1 votes

---
Tags: c#, xna, monogame, touch, monogame-extended
---