# Question
Title: 2D racetrack collision bounce using angle of reflection (bounce angle)
I am currently working on a race game where I want to define the collision of my vehicle with the outer and inner borders of the track.

If that happens to be the case I want to vehicle to bounce of the track but still move forward using the angle of reflection.

My racetrack looks like this:

I am wondering if the implementation is possible especially since I have curves in my track. I was thinking of defining the inner and outer boundaries using color recognition, in this case white and red, and then check for collision.

Thank you.

Update 1:

To execute what @Zebraman suggested I plan on doing the following: To get the pixel color under the vehicle I think I have to iterate over all pixels and then check the colors of the pixels infront of the vehicle to make the vehicle bounce in the reflection angle.

How to perform the color check is for me still a question now. Hope Anatole could help. @Zebraman provided an explanation of how to get the pixels color. I don't understand it yet.

Hopefully someone would be able to explain.

Update 2:

I am going to use the following code to detect pixel collision:

```
static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
                            Rectangle rectangleB, Color[] dataB)
        {
            // Find the bounds of the rectangle intersection
            int top = Math.Max(rectangleA.Top, rectangleB.Top);
            int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
            int left = Math.Max(rectangleA.Left, rectangleB.Left);
            int right = Math.Min(rectangleA.Right, rectangleB.Right);

            // Check every point within the intersection bounds
            for (int y = top; y < bottom; y++)
            {
                for (int x = left; x < right; x++)
                {
                    // Get the color of both pixels at this point
                    Color colorA = dataA[(x - rectangleA.Left) +
                                         (y - rectangleA.Top) * rectangleA.Width];
                    Color colorB = dataB[(x - rectangleB.Left) +
                                         (y - rectangleB.Top) * rectangleB.Width];

                    // If both pixels are not completely transparent,
                    if (colorA.A != 0 && colorB.A != 0)
                    {
                        // then an intersection has been found
                        return true;
                    }
                }
            }

            // No intersection found
            return false;
        }

```

Could anyone point me where to next?

# Answer
> 1 votes
You can approximate to get a good enough reflection angle. Remember, most players (if not all) don't go over game footage frame-by-frame doing pixel measurements to check whether the angles match up.

So, first thing you should do is to polygonize the racetrack. This can be done by an algorithm, but if you have only relatively few levels, then writing the tool may require more time than it saves over doing it by hand (This doesn't mean that you should just use a text-editor and estimate where the points are, you should write a program that helps you, but don't create an image analyzer). If we take your original example, the polygon would look something like the following (I wasn't very exact, but you get the point):

Now we can do the collision detection. Due to the way your cars look like, you could take a circle that fully encloses your car and do a collision check on each side of the polygon separately. From this site we see, that to determine whether a circle and a line intersects, we need the start and end points of the line (`(x1; y1)` and `(x2; y2)` in order) and the radius of the circle (`r`).

If the formula

```
r^2 * ((x2 - x1)^2 + (y2 - y1)^2) - x1 * y2 - x2 * y1

```

is greater than or equal to 0, the circle and the line intersect. You can also get the intersection's position, but it's not necessary to calculate it if your cars don't go with a relatively high speed (more than around the car's size every frame).

So, now we know which line segment the car hit. Next thing we need to now is in which direction it bounces us. Luckily there's also a way to find this out, but it involves a bit of vector math, mainly the dot product. Let's take the following example:

Here line `AB` is the line segment, **d** is the car's direction and **e** is the direction you want to find. First you'll have to convert line `AB` to a vector, let's call it **c** for convenience. First you'll have to get the normal vector of **c**. The normal vector is a vector with a length of 1, that's perpendicular to **c**. You can get it by taking the `x` and `y` components of **c** and creating the vector `(y; -x)`, which is the rotated version of it, and normalizing it. Let's call this vector **n**. Now, to get the actual reflected direction, take **d** and the newly created **n** and using the formula:

```
e = d - 2 * (d ⋅ n) * n

```

And voilá, you got your new direction.

# Answer
> 0 votes
It's definitely possible but it's not simple.

Your velocity after collision will essentially be v - n. v being velocity, n being the normal of the wall scaled by your alignment with said normal.

In order to get the correct reflection you will need to know the "normal" of the wall you collide with. There's a couple ways to do this.

The fastest (in runtime) way would be to create a texture that holds this information. That way when you use your color detection to check for collisions you can use the same information to get the normal. Unfortunately, I'm not aware of any tools that will do this for you automatically so it's a pain to set up, but easy to work with once done. This is often done using a normal map. But since you're only working in 2 dimensions there would be no blue.

Each pixel represents a vector with red as the x component and green as the y component.

The other option is to calculate it n the fly. This would require your code to be able to recognize an edge, then use that calculate the tangent, then find the perpendicular line.

You would have to do the math for something that looks like this

---
Tags: c#, collision-detection, software-engineering, graphics-programming, color
---


# Question
Title: LibGDX Bomberman bomb arraylist iterator error
Here is the code of bomb:

```
private int x, y;
private Texture bTexture;
private boolean bomb_explode;

private Timer timer;
private TimerTask task;
private int timeLeft = 0;

private TileMap map;
public static List<Bomb> bombs = new ArrayList<Bomb>();

public Bomb(TileMap map, int x, int y) {
    this.map = map;
    this.x = x;
    this.y = y;
    bTexture = new Texture("bomb.png");
    bomb_explode = false;
    bombs.add(this);
    createTimer();
}

public void render(SpriteBatch batch, float delta) {
    batch.draw(bTexture, x * Settings.SCALED_TILE_SIZE, y * Settings.SCALED_TILE_SIZE,
        Settings.SCALED_TILE_SIZE, Settings.SCALED_TILE_SIZE);
    if(timeLeft > 1f) {
        bomb_explode = true;
    }
    if(bomb_explode) {
        for(int i = 0; i <= 1; i++) {
            if(x + i <= map.getWidth()) {
                batch.draw(new Texture("flame.png"),
                    ((x + i) * Settings.SCALED_TILE_SIZE), y * Settings.SCALED_TILE_SIZE,
                     Settings.SCALED_TILE_SIZE, Settings.SCALED_TILE_SIZE);
            }
            if(y + i <= map.getHeight()) {
                batch.draw(new Texture("flame.png"), x * Settings.SCALED_TILE_SIZE,
                   ((y + i) * Settings.SCALED_TILE_SIZE), Settings.SCALED_TILE_SIZE,
                   Settings.SCALED_TILE_SIZE);
            }
            if(x - i >= 0) {
                batch.draw(new Texture("flame.png"),
                    ((x - i) * Settings.SCALED_TILE_SIZE), y * Settings.SCALED_TILE_SIZE,
                    Settings.SCALED_TILE_SIZE, Settings.SCALED_TILE_SIZE);
            }
            if(y - i >= 0) {
                batch.draw(new Texture("flame.png"), x * Settings.SCALED_TILE_SIZE,
                ((y - i) * Settings.SCALED_TILE_SIZE), Settings.SCALED_TILE_SIZE,
                Settings.SCALED_TILE_SIZE);
            }
        }
    }

}

public void Boom() {
    bomb_explode = false;
    for(int i = 0; i <= 1; i++) {
        if(map.getTile(x, y).getPlayer() != null) {
            map.getTile(x, y).getPlayer().Die();
        }

        if(x + i <= map.getWidth() && map.getTile(x+i, y).getPlayer() != null) {
            map.getTile(x+i, y).getPlayer().Die();
        }

        if(x - i >= 0 && map.getTile(x-i, y).getPlayer() != null) {
            map.getTile(x-i, y).getPlayer().Die();
        }

        if(y + i <= map.getHeight() && map.getTile(x, y+i).getPlayer() != null) {
            map.getTile(x, y+i).getPlayer().Die();
        }

        if(y - i >= 0 && map.getTile(x, y-i).getPlayer() != null) {
            map.getTile(x, y-i).getPlayer().Die();
        }
    }
    bombs.remove(this);
}

public void createTimer() {
    timeLeft = 0;
    task = new TimerTask() {

        @Override
        public void run() {
            ++timeLeft;
            if(timeLeft > 3) {
                bomb_explode = true;
                Boom();
                clearTimer();
            }
        }
    };

    timer = new Timer();
    timer.schedule(task, 1, 500);
}

public void clearTimer() {
    timer.cancel();
    timer.purge();
    timer = null;
}

```

In the screen class, I'm rendering the bomb like this :

```
for(Bomb b : Bomb.bombs) {
    b.render(batch, delta);
}

```

---

Here is the error I'm getting:

> Exception in thread "LWJGL Application" java.util.ConcurrentModificationException
> at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
> at java.util.ArrayList$Itr.next(Unknown Source)
> at bomberman.screens.GameScreen.render(GameScreen.java:41)
> at com.badlogic.gdx.Game.render(Game.java:46)
> at bomberman.game.GameObject.render(GameObject.java:23)
> at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
> at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)

How can I fix it?

# Answer
Your problem (probably) comes from the fact that you call `bombs.remove(this);` in your bomb's `Boom()` method while you're iterating through your list. This will throw a `ConcurrentModificationException`. As stated in the javadocs:

> The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

To circumvent this I quote John Skeet's answer:

* Create a list of values you wish to remove, adding to that list within the loop, then call `originalList.removeAll(valuesToRemove)` at the end
* Use the `remove()` method on the iterator itself. Note that this means you can't use the enhanced for loop.

For you this could look something like this:

```
// In your Bomb class
public static ArrayList<Bomb> bombs = ...;
public static ArrayList<Bomb> bombsToRemove = ...;

// In your Boom() method
bomb_explode = false;
for(int i = 0; i <= 1; i++) {
    ...
}
bombsToRemove.add(this);

// In your render() method
for(Bomb b : Bomb.bombs) {
    ...
}
Bomb.bombs.removeAll(Bomb.bombsToRemove);
Bomb.bombsToRemove.clear();

```

Hopefully this resolves the issue for you!
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Mesh from MagicaVoxel cast a strange holed shadow
I have a problem with any mesh I import from MagicaVoxel into Unity. As you can see from the screenshot below, the mesh on the left cast a shadow that has holes in it. That's a basic 7-voxel mesh exported as OBJ and dragged into Unity. The light is the standard directional light Unity automatically creates in an empty scene. The glitch occurs in scene editor, preview and exported builds, I tried on multiple PCs as well.

The mesh on the right is a cube extruded on all faces created in Blender and exported as 3DS. As you can see from the wireframe, it is basically the same mesh, but its shadow looks good. Note that if I import the MagicaVoxel's OBJ in Blender first, and then I export in 3DS and into Unity, the shadow stays holed, so it's not a problem with the mesh format, but with something in the mesh itself.

What can it be? Can I solve it somehow or try some others approaches? Thank you.

# Answer
> 1 votes
I'd ordinarily make this a comment, but doubt there is a better answer given what you're seeing...

It likely has to do with them building the mesh without always using shared vertices, resulting in various submeshes leading to the artifact you see (if it had been a single manifold, there would have been no such issues). I'd suggest one of the following:

* Contact the MagicaVoxel team and ask if they've encountered this problem with lighting before. For all we know, it could be a change in Unity's lighting system since they last tested. They may be willing to fix. Or it could be a known "feature" and they may be unwilling to fix.
* There is also the possibility that there is a switch somewhere (in their code, perhaps) that can be changed to fix this. (It may, however, have performance impacts.)
* Failing them being willing to fix, you'll need to modify the existing lighting shader to do a screen space pass to remove such artifacts (possibly via edge dilation of shadows). Such edge dilation filters are common among shaders, and pretty trivial to achieve. I have no idea how challenging this would be to integrate with Unity's standard shader pipeline, however.

---
Tags: unity, 3d, lighting, voxels, shadows
---


# Question
Title: Is there something similar to XMFLOAT2 that has its operators overloaded?
Since `XMFLOAT2` is just a structure, I'm sure it does not have operator overloading which is what I need to make things a lot simpler. Is there something like `XMFLOAT2` where I can add two `(a) + (b)`. I also need to use the `=`.

Thanks

# Answer
`XMFLOAT2` doesn't provide the usual operator overloads. It does provide an `operator=` overload, but you'll have to write the others yourself. You can do this fairly easily, for example:

```
XMFLOAT2 operator+(const XMFLOAT2& left, const XMFLOAT& right) {
  return XMFLOAT2(left.x + right.x, left.y + right.y);
}

```

...and so on for any other operators you'd like.

Alternatively, if you'd like to use only the facilities provided by the DirectXMath API, store your `XMFLOAT2` objects into `XMVECTOR`s using `XMStoreFloat2`. `XMVECTOR` provides the suite of operators you are likely looking for.
> 1 votes

# Answer
DirectXMath generally tries to minimize use of "C++ magic" so that it's easier to write high-performance computation using it. For good SIMD performance, you want to be careful about when you read to or write from memory, minimize conversions between vector & scalar, and try to keep the bulk of your computation 'in-register'. For this reason, you are strongly encouraged by the design to use types like `XMFLOAT2` in your memory data structures, but to actually do all computation using `XMVECTOR` which is best thought of as the proxy for a SIMD register.

That said, some of the rules of usage around alignment and the resulting verbosity can be less than friendly to the developer just trying to write some code.

For this reason, I've also written a 'wrapper' library for DirectXMath that includes types like `Vector2` with all the overloads you are expecting. This uses C++ constructors, conversion operators, and extensive overloading to achieve what you are asking for. See the SimpleMath header which is part of the DirectX Tool Kit.

> If you'd rather write your own wrapper or use the same technique in your own math library 'outer types', feel free to look at the source ( / cpp)

See also DirectXMath on GitHub
> 1 votes

---
Tags: directx11, directxmath
---


# Question
Title: Check if a game object's component can be destroyed
Developing a game in Unity, I'm making liberal use of `[RequireComponent(typeof(%ComponentType%))]` to ensure components have all dependencies met.

I'm now implementing a tutorial system which highlights various UI objects. To do the highlighting, I'm taking a reference to the `GameObject` in the scene, then I clone it with Instantiate() and then recursively strip away all components which aren't needed for display. The problem is that with the liberal use of `RequireComponent` in these components, many cannot be simply removed in any order, since they are depended on by other components, which have not been deleted yet.

My question is: Is there a way to determine whether a `Component` can be removed from the `GameObject` it is currently attached to.

The code I'm posting technically works, however it throws Unity errors (not caught in try-catch block, as seen in the image

Here's the code:

```
public void StripFunctionality(RectTransform rt)
{
    if (rt == null)
    {
        return;
    }

    int componentCount = rt.gameObject.GetComponents<Component>().Length;
    int safety = 10;
    int allowedComponents = 0;
    while (componentCount > allowedComponents && safety > 0)
    {
        Debug.Log("ITERATION ON "+rt.gameObject.name);
        safety--;
        allowedComponents = 0;
        foreach (Component c in rt.gameObject.GetComponents<Component>())
        {
            //Disable clicking on graphics
            if (c is Graphic)
            {
                ((Graphic)c).raycastTarget = false;
            }

            //Remove components we don't want
            if (
                !(c is Image) &&
                !(c is TextMeshProUGUI) &&
                !(c is RectTransform) &&
                !(c is CanvasRenderer)
                )
            {
                try
                {
                    DestroyImmediate(c);
                }
                catch
                {
                    //NoOp
                }
            }
            else
            {
                allowedComponents++;
            }
        }
        componentCount = rt.gameObject.GetComponents<Component>().Length;
    }

    //Recursive call to children
    foreach (RectTransform childRT in rt)
    {
        StripFunctionality(childRT);
    }
}

```

So the way this code generated the last three lines of the debug log above is the following: It took as input a `GameObject` with two components: `Button` and `PopupOpener`. `PopupOpener` requies that a `Button` component is present in the same GameObject with:

```
[RequireComponent(typeof(Button))]
public class PopupOpener : MonoBehaviour
{
    ...
}

```

The first iteration of the while loop (denoted by the text "ITERATION ON Button Invite(clone)") attempted to delete the `Button` first, but couldn't as it is depended on by the `PopupOpener` component. this threw an error. Then it attempted to delete the `PopupOpener` component, which it did, since it is not depended on by anything else. In the next iteration (Denoted by the second text "ITERATION ON Button Invite(clone)"), it attempted to delete the remaining `Button` component, which it now could do, since `PopupOpener` was deleted in the first iteration (after the error).

So my question is whether it is possible to check ahead of time if a specified component can be removed from its current `GameObject`, without invoking `Destroy()` or `DestroyImmediate()`. Thank you.

# Answer
It is definitely possible, but it requires quite a lot of legwork: you can check if there is a `Component` attached to the `GameObject` which has an `Attribute` of type `RequireComponent` which has one of its `m_Type#` fields assignable to the component type you are about to remove. All wrapped in an extension method:

```
static class GameObjectExtensions
{
    private static bool Requires(Type obj, Type requirement)
    {
        //also check for m_Type1 and m_Type2 if required
        return Attribute.IsDefined(obj, typeof(RequireComponent)) &&
               Attribute.GetCustomAttributes(obj, typeof(RequireComponent)).OfType<RequireComponent>()
               .Any(rc => rc.m_Type0.IsAssignableFrom(requirement));
    }

    internal static bool CanDestroy(this GameObject go, Type t)
    {
        return !go.GetComponents<Component>().Any(c => Requires(c.GetType(), t));
    }
}

```

after dropping `GameObjectExtensions` anywhere in the project (or alternatively make it a regular method on the script), you can check if a component can be removed, e.g.:

```
rt.gameObject.CanDestroy(c.getType());

```

However there can be other means to make un-interactive GUI object - for example, rendering it to texture, overlaying it with almost-transparent panel which will intercept clicks or **disabling**(instead of destroying) all `Component`s deriving from `MonoBehaviour` or `IPointerClickHandler`.
> 9 votes

# Answer
Instead of removing the components on the clone, you can just disable them by setting `.enabled = false` on them. This won't trigger the dependency checks, because a component doesn't need to be enabled to fulfill the dependency.

* When a Behaviour is disabled, it will still be on the object and you can even change its properties and call its methods, but the engine will no longer call its `Update` method.
* When a Renderer is disabled, the object turns invisible.
* When a Collider is disabled, it won't cause any collision events to happen.
* When an UI component is disabled, the player can't interact with it anymore, but it will still be rendered, unless you also deactivate its renderer.
> 7 votes

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


# Question
Title: Default mipmap level & elements to use for CopyTexture in Unity Scripting?
I want to make a tiled map. I want to use the function CopyTexture to copy from a Texture2D (where is stored my tileset) to a RenderTexture.

I want to use the third overloading (with all the arguments) which allow me to choose from where in the source texture and where in the render texture I will copy. But I need to specify mipmap levels and elements.

I don't know what to use as mipmap levels and elements in this function. Thanks to everyone who can help me :)

# Answer
> 0 votes
`0`

The parameter name suggests it is which mip to *read from* and you will almost certainly want to read from the largest (original) texture which is mip-0.

---
Tags: unity, mipmaps, rendertexture
---


title: Fragment shader working so strange

text:
# Question
Title: Fragment shader working so strange
the fragment shader is working so strange, can someone explain me whats going on.

this one compiles fine but crashes when i use it-

```
#version 330 core
const float PI = 3.14159265359;
out vec4 coloroutfinal;

in vec3 fragpos;
uniform vec3 lightpos;
uniform vec3 camerapos;

vec3 wi;
vec3 normal;
float cosT;
uniform vec3 lightcolor;
vec3 incidentlight;

uniform float metallic;
uniform float roughness;
uniform vec3 albedo;
uniform float ao;

vec3 fresnel(float cosT,vec3 Fo);
float ND(vec3 H,vec3 N,float roughness);
float G(vec3 L,vec3 N,vec3 V,float roughness);

void main()
{
  coloroutfinal=vec4(1.0);

}

vec3 fresnel(float cosT,vec3 Fo)
{
  return Fo+(1.0-Fo)*pow((1-cosT),5);
}

float ND(vec3 H,vec3 N,float roughness)
{
   float roughness4=pow(roughness,4);
   float cosT=max(dot(N,H),0.0);
   float cosT2=cosT*cosT;
   float num=roughness4;
   float denom=cosT2*(1.0-roughness4)+1.0;
   return num/denom;
}

float GP(float cosT,float roughness)
{
roughness-=1.0;
   float r2=roughness*roughness;
   float k=r2/8;

float num=cosT;
float denom=cosT*(1.0-k)+k;
 return num/denom;

}

float G(vec3 L,vec3 N,vec3 V,float roughness)
{
  float cosTL=max(dot(N,L),0.0);
  float cosTV=max(dot(N,V),0.0);

  float GL=GP(cosTL,roughness);
  float GV=GP(cosTV,roughness);
  return GL*GV;
}

```

but this one is just the same as above but no function definitions but works fine(renders my object in white)-

```
#version 330 core
const float PI = 3.14159265359;
out vec4 coloroutfinal;

in vec3 fragpos;
uniform vec3 lightpos;
uniform vec3 camerapos;

vec3 wi;
vec3 normal;
float cosT;
uniform vec3 lightcolor;
vec3 incidentlight;

uniform float metallic;
uniform float roughness;
uniform vec3 albedo;
uniform float ao;

vec3 fresnel(float cosT,vec3 Fo);
float ND(vec3 H,vec3 N,float roughness);
float G(vec3 L,vec3 N,vec3 V,float roughness);

void main()
{
  coloroutfinal=vec4(1.0);

}

```

I never call the function so how are they interfearing. also both the shaders compile and link fine.

can someone point me to the mistake?

# Answer
> 1 votes
Thanks everyone i got the error.Silly actually i had the shader file reader's buffer size set to 500 bytes that was causing the smaller shader to run while not the large one. Not sure why it was linking still.

Still thanks for helping.

---
Tags: opengl, shaders, graphics, rendering
---


# Question
Title: Fragment shader code for simple shading is making the app crash
My fragment shader compilers fine but the my app crashes when i use it.

My bug hunting deducted that the shader is linking fine. Also it's curious that striping down the core and removing everything and outputting just a colour is showing the model in one colour off course.

What is wrong?

Fragment shader:

```
#version 330 core
const float PI = 3.14159265359;
out vec4 coloroutfinal;

in vec3 fragpos;
uniform vec3 lightpos;
uniform vec3 camerapos;

vec3 wi;
vec3 normal;
float cosT;
uniform vec3 lightcolor;
vec3 incidentlight;

uniform float metallic;
uniform float roughness;
uniform vec3 albedo;
uniform float ao;

vec3 fresnel(float cosT,vec3 Fo);
float ND(vec3 H,vec3 N,float roughness);
float G(vec3 L,vec3 N,vec3 V,float roughness);

void main()
{
  wi=normalize(lightpos-fragpos);
  normal=normalize(fragpos);
  cosT=max(dot(normal,wi),0.0);
  float attenuation=1.0/pow(length(lightpos-fragpos),2);
  incidentlight=attenuation*cosT*lightcolor;
  vec3 V=normalize(camerapos-fragpos);
  vec3 H=normalize(V+wi);

  vec3 Fo=vec3(0.04);
  Fo=mix(Fo,albedo,metallic);
  vec3 F=fresnel(max(dot(H,V),0.0),Fo);

  float ND=ND(H,normal,roughness);
  float G=G(wi,normal,V,roughness);

  vec3 BRDFn=F*ND*G;
  float BRDFd=4*max(dot(normal,wi),0.0)*max(dot(normal,V),0.0)+0.001;
  vec3 specular=BRDFn/BRDFd;

  vec3 KS=F;
  vec3 KD=1.0-KS;
  KD*=(1.0-metallic);

  vec3 lo=(KD*albedo/PI+specular)*incidentlight;
  vec3 colorout=lo+(ao*albedo*vec3(0.05));

  colorout=colorout/(colorout+1.0);
  colorout=pow(colorout,vec3(1/2.2));
  coloroutfinal=vec4(colorout,0.0);

}

vec3 fresnel(float cosT,vec3 Fo)
{
  return Fo+(1.0-Fo)*pow((1-cosT),5);
}

float ND(vec3 H,vec3 N,float roughness)
{
   float roughness4=pow(roughness,4);
   float cosT=max(dot(N,H),0.0);
   float cosT2=cosT*cosT;
   float num=roughness4;
   float denom=cosT2*(1.0-roughness4)+1.0;
   return num/denom;
}

float GP(float cosT,float roughness)
{
roughness-=1.0;
   float r2=roughness*roughness;
   float k=r2/8;

float num=cosT;
float denom=cosT*(1.0-k)+k;
 return num/denom;

}

float G(vec3 L,vec3 N,vec3 V,float roughness)
{
  float cosTL=max(dot(N,L),0.0);
  float cosTV=max(dot(N,V),0.0);

  float GL=GP(cosTL,roughness);
  float GV=GP(cosTV,roughness);
  return GL*GV;
}

```

# Answer
I found the problem. The shaders reader had the buffer size set too small.
> 1 votes

---
Tags: opengl, shaders, rendering, glsl
---


# Question
Title: How to maintain char widths of non-monospace fonts?
Having a font via spritesheet (as PNG), the easiest way to render fonts from that is just showing chars as monospace, but as you can imagine, that looks *not pretty* with chars like `l`, `i`, `:` and so on..

Is there a slick way to maintain the width of every char?

* I already thought of storing it into an extra file, telling the width of each char in pixels.
    + *Pro:* Fast rendering.
    + *Con:* That's one load of work for about 100 chars.
* I gave "counting" the pixel-width of each char on rendering it a thought.
    + *Pro:* Once that algorithm does it's job there's no work with that afterwards.
    + *Con:* As there is pretty much font-rendering going on each frame, this is plain *bullshit* \- performancewise.

I'm open to suggestions and/or known algorithms for this problem.

**EDIT:** TTF or some other *real* font is not an option, because they render wayy to pixelated on the small sizes needed.

**EDIT:** Thanks to lorenzo-gatti, made simple marker-pixels in the spritesheet like so:

Distance between these gets counted on startup of the game and the markers are replaced with transparent pixels. So no heavy additional logic in render which would slow down and startup-time is not really slower than before, thanks!

# Answer
> 3 votes
You need to input intended character widths, but not necessarily in a separate text file: the image itself can contain graphical markers at the boundaries of character sprites.

For example, you can put all characters next to each other, left to right, and add an extra row to the image that contains a colored pixel in the leftmost column of each character sprite.

You might also extend this technique, if needed, with an extra column containing colored pixels marking the baseline, x-height, ascender and descender extent and other vertical metrics of the font.

---
Tags: rendering, fonts, spritefont
---


# Question
Title: Adapting pen & paper RPG rule system for use in a video game
I want to make a browser based RPG. I am considering to use an existing pen & paper rule system (like FATE or GURPS) instead of developing my own rule system from scratch.

What pitfalls should I be aware of when adapting a pen&paper system for use in a video game?

# Answer
Generally, when you start without experience you should go with the existing solution instead of inventing something new.

**However**, your situation is different. Neither FATE nor GURPS are frameworks that are designed for browser based RPGs. So the question is about adapting them, not about using them. Adapting an existing tabletop system for an online RPG is non-trivial and likely an overwhelming task for an average person who writes their first online RPG.

If you make your own system, you still have to draw inspiration from somewhere, so I recommend making your own system **inspired** by FATE or GURPS. That way you can easily make changes that benefit the gameplay and simplify the implementation.
> 12 votes

# Answer
Making an engine is a lot of work. Since you're at the point in your development where you are asking this question, I would recommend making one. I think every game developer should write at least one engine.

Once you've written your own, and it works for your first game, that's awesome. You'll learn how and why frameworks work -- you'll learn about some of the goofy things that seem simple on the surface but are surprisingly difficult to handle in an abstract way. You'll also learn more about what the popular frameworks are doing behind the scenes.

At the end of the day, the most limiting resource is going to be your time. Do you want to dedicate your time to making a game or making a framework?
> -3 votes

---
Tags: game-design, game-mechanics, rpg, browser-based-games
---


# Question
Title: Polygon-Circle Collision Algorithm not working
EDIT: Updated code and video

I've been working on one of the last pieces of my collision detection system for my game, a polygon-circle collision method. I'm almost there with it, but there's a few minor issues that seem to pop up with it. I'll explain the few things I'm seeing, but it's probably easier just to watch the short video I have below:

https://1drv.ms/v/s!AjUDP95TjAMqje8AVA0LpPfeszVYoA

There are the three things I'm seeing:

* Little bit of bumpiness when going down a slope vs up (I'm guessing I just need to smooth out the movement adjustment a little bit
* When going around certain corners, the adjustment distance gets computed incorrectly, which results in either:
    + A **small** bit of excess distance
    + A **large** amount of excess distance

Below are the major components of my code, happy to update the post and add any other relevant code chunks that made be needed. Any assistance with this would be appreciated. Thanks!

**Physics World Update Method:**

```
IEnumerable<PhysicsFixtureBase> results = this.physicsTree.Query(fixture);
foreach (PhysicsFixtureBase otherFixture in results)
{
    Vector3 adjustment = Vector3.Zero;
    if (fixture.Body != otherFixture.Body && fixture.Intersects(otherFixture, out adjustment))
    {
        this.OnContact(fixture, otherFixture);
        body.SetVelocity(Vector3.Zero);
        body.MovePosition3D(adjustment);
    }
}

```

**Main Intersection Method:**

```
public static bool Intersects(PhysicsCircleFixture circle, PhysicsPolygonFixture otherPolygon, out Vector3 adjustment)
{
    bool result = PhysicsCollisionHandler.Intersects(otherPolygon, circle, out adjustment);
    adjustment *= -1;
    return result;
}

public static bool Intersects(PhysicsPolygonFixture polygon, PhysicsCircleFixture otherCircle, out Vector3 adjustment)
{
    adjustment = Vector3.Zero;

    Vector2 circleCenter = otherCircle.GetPosition2D();
    float circleRadius = otherCircle.GetSize2D().X;

    Vector2 closestPoint = Vector2.Zero;
    float closestDistance = float.MaxValue;

    foreach (Vector2 point in polygon.Points)
    {
        float distance = circleCenter.Distance(point);
        if (distance < closestDistance)
        {
            closestDistance = distance;
            closestPoint = point;
        }
    }

    Vector2 previousPoint = polygon.Points[polygon.Points.Count - 1];
    foreach (Vector2 currentPoint in polygon.Points)
    {
        Vector2 edge = currentPoint - previousPoint;
        float interp = edge.DotProduct(circleCenter - previousPoint) / edge.DotProduct(edge);
        if (0.0f < interp && interp < 1.0f)
        {
            Vector2 point = previousPoint + edge * interp;
            float distance = circleCenter.Distance(point);

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closestPoint = point;
            }
        }
        previousPoint = currentPoint;
    }

    if (closestDistance < circleRadius)
    {
        float penetrationDistance = circleRadius - closestDistance;
        Vector2 normalizedVector = (closestPoint - circleCenter) / closestDistance;
        adjustment = (normalizedVector * penetrationDistance).To3DVector3();
    }

    return (adjustment != Vector3.Zero);
}

```

**Helper Code:**

```
public static Vector2 Normal(this Vector2 vector) { return new Vector2(-vector.Y, vector.X); }

public class Range
{
    public float Min { get; set; }

    public float Max { get; set; }

    public Range(float min, float max)
    {
        this.Min = min;
        this.Max = max;
    }

    public float Length() { return this.Max - this.Min; }

    public Range Intersects(Range other)
    {
        Range longestDistance = new Range(Math.Min(this.Min, other.Min), Math.Max(this.Max, other.Max));
        if (longestDistance.Length() < (this.Length() + other.Length()))
        {
            return new Range(Math.Max(this.Min, other.Min), Math.Min(this.Max, other.Max));
        }
        return null;
    }
}

public Range PhysicsPolygonFixture.ProjectOnAxis(Vector2 axis)
{
    Range range = new Range(float.MaxValue, float.MinValue);
    foreach (Vector2 point in this.Points)
    {
        float projection = point.DotProduct(axis);
        if (projection < range.Min)
        {
            range.Min = projection;
        }
        if (projection > range.Max)
        {
            range.Max = projection;
        }
    }
    return range;
}

public Range PhysicsCircleFixture.ProjectOnAxis(Vector2 axis)
{
    float circleCenterProjection = this.GetPosition2D().DotProduct(axis);
    float circleRadius = this.GetSize2D().X;
    return new Range(circleCenterProjection - circleRadius, circleCenterProjection + circleRadius);
}

```

# Answer
The code that checks for edge collisions is definitely causing the problems you're seeing. Since it's also a little more complex than necessary, I think the right solution is to rewrite it completely.

Remove the entire `foreach (Vector2 edge in polygon.Edges)` loop, and add the following code above the line `if (closestDistance < circleRadius)`:

```
Vector2 pointPrev = polygon.Points[polygon.Points.Length - 1];
foreach (Vector2 pointCur in polygon.Points)
{
    Vector2 edge = pointCur - pointPrev;

    float interp = edge.DotProduct(circleCenter - pointPrev) / edge.DotProduct(edge);

    if (interp > 0.0f && interp < 1.0f)
    {
        Vector2 point = pointPrev + edge * interp;
        float distance = circleCenter.Distance(point);

        if (distance < closestDistance)
        {
            closestDistance = distance;
            closestPoint = point;
        }
    }

    pointPrev = pointCur;
}

```

**Note 1**

I tried to use your function and type names. The only thing I didn't have a reference for was whether `polygon.Points` is an array or a list.

**Note 2**

The only tricky bit there is the calculation of `interp`; it combines two calculations into one to avoid a square root. It normalizes the edge vector and also divides the projection of the circle's center onto the edge by the length of the edge vector.
> 2 votes

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: How to achieve good looking surface net normals?
**EDIT** After Victor T.'s suggestion (ignore seams):

I'm using elastic surface nets to convert a 3D voxels into a nice smooth mesh. The mesh part, is great, however, I can't seem to find a decent looking method of getting proper vertex normals for each voxel. I've been reading a couple of forums, like this one from reddit and this one from Stack Overflow. Using the method described in the stack overflow one, I got normals that looked like this:

(Shaded)

(Scaled Normals)

While this might seem okay, it doesn't work very well with flat surfaces, and if I try to add methods for dealing with flat surfaces, it messes everything else up. And yet it still doesn't look ideal.

Using cross products of the vertices to get the normal, I was only able to get a hard shaded mesh, that did look decent, however, it can't distinguish up and down, so it doesn't look right in overhangs. It also is hardshaded, and I want smooth shading.

**Question** : What are ways I can achieve a better looking normal? What techniques are common for this? Is there any way modified methods I can use that are better than the ones I am doing? I am okay if the best looking method is expensive.

I can post source code if needed.

Thanks

**UPDATE**

After Victor T.'s suggestion, I managed to get great looking surface normals! One problem, the corners don't look right, I was unable to find any correlation between why is the normals on the corners need to be flipped (0 - normal).

Here is a picture :

**EDIT 2:** Managed to particially solve the problem, however, when the vertice is on a 45 degree angle on all axises, it seems to mess up and needs to be flipped:

# Answer
A common way of generating vertex normals for a mesh is to sum the normals of the faces that touch each vertex, then normalize those sums. You're part-way there with taking cross-products from the faces.

A reasonable procedure would be:

* set all vertex normals to (0,0,0)
* iterate over the faces
    + calculate the face normal: `(vertex1 - vertex0) x (vertex2 - vertex0)`
    + add the face normal into the normal for each vertex of the face
* normalize the vertex normals

Note: This assumes that you can tell which direction the face normals should point, and part of your question says that this may not be the case. Mesh generation algorithms (in general, not specifically for elastic surface nets) are usually designed keep the order (sometimes called "winding order") consistent. Please try the procedure I outlined, to see if things are OK without further modification. If the mesh doesn't have consistent winding, you can address that next.
> 2 votes

---
Tags: opengl, voxels, normals, shading
---


title: Effect only on one object (two cameras)

text:
# Question
Title: Effect only on one object (two cameras)
I have a problem. I want a Grayscale effect to be applied ONLY to the chair on the stage. The chair has a layer `CurrentItem`. And I have two cameras:

1. `Camera_All` renders everything except layer `CurrentItem` (I set this exception in CullingMask)
2. `Camera_CurrentItem`

Finally:

I need to apply not just one effect, but a few.

# Answer
Everything is becoming gray because post-processing always draws the whole screen, so the effect gets applied to every pixel. Since the order of the cameras is Camera\_All and then Camera\_CurrentItem, the post-processing of Camera\_CurrentItem gets applied to all the pixels that were drawn earlier by Camera\_All.

If you exchange the drawing order (by switching the Depth properties of the two cameras), and set the Clear Flags of Camera\_All to "Don't Clear", the chair will be drawn first, then the grayscale effect on just that, then all the non-chair stuff.

If this works, then great!

---

I think it will not quite work. You will probably see only a gray chair, with whatever background Camera\_CurrentItem's clear flags dictate. To fix this, you'll need to modify the grayscale effect shader.

Make a copy the shader file, and add `ZWrite Off` in the SubShader block. I don't have your particular shader, but the code near your addition will be something like

```
SubShader
{
    Tags { "RenderType"="Opaque" }
    LOD 100

    // You'll add the following line
    ZWrite Off

```

There may be other lines in there, and that's fine. Look for the `Tags` or `LOD` line and put your new `ZWrite Off` line near them.

Now you can drag the new shader into the Shader property of the Grayscale Effect component, and you should see the whole scene assembled as expected.
> 2 votes

---
Tags: unity, camera, image, effect
---


# Question
Title: Which technique should I use to create procedurally generated planets
I am working on a personal project to create a game, in which you can fly in space to various planets and land on said planets. I was originally using a script to create an IcoSphere which I stored using recursive chunks which worked as a LOD. The results looked good from space, however, after creating a player on the planet, the triangles were still very large. The IcoSphere was only subdivided 5 or 6 times due to the lengthy processing times. I was going to base the texturing of the magnitude of the point on the sphere taking into account various factors.

Is there a better method to generate planets without these processing times?

## EDIT

I am only interested in generating the planet surface, not the positioning in the galaxy/universe

I have done research online into different techniques. I've seen people using cube spheres however that looked to have caused a lot of distortion around the corners. I've also seen Octohedrons which were subdivided but I think that'd give the same problems as my icosphere technique

# Answer
> 1 votes
There is no perfect method for procedural generation of planets, but you should be why they are used, in order to be best armed for selecting a method for yourself.

Consider *why* planets are generated procedurally:

Storage issues. If you have potentially thousands of planets, with, as you desire, complex and high resolution geometry, that would make for very large file sizes.

Load times. Large files need a long time to load. Enough said about this really.

Rendering times. Larger, more complex(high poly) models require more time to render, especially when lighting them.

Physics & collision detection. More triangles = more planes of collision = more work for the physics & collision systems to do.

The "best" solution would address the highest number of these concerns.

The storage and loading issues can be largely dealt with by having planets generated from a "seed" value, which, when used as an argument in the generation algorithm, will always produce the same result. Thus, no need for large files, but at the cost of computation time.

Rendering and loading can be addressed by using the above technique, in conjunction with polygon tessellation, but this leaves issues with physics and collision, which requires accurate knowledge of the geometry at it's highest detail level.

As you can see, there is no silver bullet for this sort of thing, and, is still debated amongst space sim coders.

Bottom line, do your own research into as many techniques as you can, understand their drawbacks and benefits, and choose the one that most meets your needs, or adapt existing techniques to suit.

---
Tags: unity, c#, procedural-generation
---


# Question
Title: texture coordinates seem to have flipped or incorrect position?
I have a working cube in 3d space that has a texture wrapped to it. now when I say working it maps two of the 6 faces correctly. from what I can tell is that the texture coordinates are moved up "a block spaced (face space)". As the two textures is shows are fine but all of the other sides are white so I am thinking that it is reading the coordinates from the wrong side (aka the texture coordinates are reading 0,0 as bottom left and opengl is reading it as 0,0 is top left). I feel like that is not a thing but that is what seems to happen.

NOTE: I used blender for my creation of square with textures and and the mapping and exporting. Also note that I am using a depth buffer it that helps.

.obj file:

```
# Blender v2.78 (sub 0) OBJ File: 'cube.blend'
# www.blender.org
mtllib cube.mtl
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
vt 0.5000 0.2500
vt 0.7500 0.5000
vt 0.5000 0.5000
vt 0.0001 0.5000
vt 0.2500 0.2500
vt 0.2500 0.5000
vt 0.9999 0.0001
vt 0.7500 0.2500
vt 0.7500 0.0001
vt 0.9999 0.5000
vt 0.7500 0.7500
vt 0.9999 0.7500
vt 0.0001 0.2500
vt 0.9999 0.2500
vn 0.0000 -1.0000 0.0000
vn 0.0000 1.0000 0.0000
vn 1.0000 -0.0000 0.0000
vn 0.0000 -0.0000 1.0000
vn -1.0000 -0.0000 -0.0000
vn 0.0000 0.0000 -1.0000
usemtl cube
s off
f 2/1/1 4/2/1 1/3/1
f 8/4/2 6/5/2 5/6/2
f 5/6/3 2/1/3 1/3/3
f 6/7/4 3/8/4 2/9/4
f 3/8/5 8/10/5 4/2/5
f 1/11/6 8/10/6 5/12/6
f 2/1/1 3/8/1 4/2/1
f 8/4/2 7/13/2 6/5/2
f 5/6/3 6/5/3 2/1/3
f 6/7/4 7/14/4 3/8/4
f 3/8/5 7/14/5 8/10/5
f 1/11/6 4/2/6 8/10/6

```

cube texture:

texture loader:

```
void sky::Texture::load (const char *path) {
    if (m_loaded)
        return;
    std::cout << "load texture" << std::endl;
    int width, height, components;
    // load image to loader
    unsigned char* image_data = stbi_load(path, &width, &height, &components, 4);
    if (image_data == nullptr)
        std::cerr << "Texture loading failed: " << path << std::endl;

    // configure and bind texture to opengl
    glGenTextures(1, &m_texture);
    glBindTexture(GL_TEXTURE_2D, m_texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);

    stbi_image_free(image_data);
    m_loaded = true;
}

```

draw function

```
void sky::Mesh::draw () {
    if (configured) {
        m_texture.bind(0);
        glBindVertexArray(m_vao);
        glDrawArrays(GL_TRIANGLES, 0, m_vertices.size() * sizeof(Vertex));
        glBindVertexArray(0);
    }
}

```

vertex shader:

```
#version 330 core

layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
layout(location = 2) in vec2 textureCoord;

out vec2 textCoord;

uniform mat4 MVP;

void main() {
    textCoord = textureCoord;
    gl_Position = MVP * vec4(position, 1);
}

```

fragment shader:

```
#version 330 core

in vec2 textCoord;
uniform sampler2D diffuse;

void main() {
    gl_FragColor = texture2D(diffuse, textCoord);
}

```

data initialization:

```
void sky::Mesh::initialize () {
    //m_vertice_count = m_vertices.size() * sizeof(m_vertices[0][0]);
    //m_normal_count = normals.size() * 3;
    std::cout << "vert size: " << m_vertices.size() * sizeof(glm::vec3) << std::endl;

    // generate the buffers/arrays
    glGenVertexArrays(1, &m_vao);
    glGenBuffers(1, &m_vbo);

    glBindVertexArray(m_vao);

    // load data to vbo
    glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
    // structs memory is sequential so that we can pack all the data per vertex into one single array and
    // inform opengl of the layout
    glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex), &m_vertices[0], GL_STATIC_DRAW);
    // set the layout of the data
    // vertex position
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
    // vertex normals
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)offsetof(Vertex, normal));
    // vertex texture
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)offsetof(Vertex, texture));

    glBindVertexArray(0);

    configured = true;
}

```

# Answer
> 2 votes
As the previous answer correctly stated, the vertical dimensions for images in memory is inverted, compared to what you need for OpenGL.

I would suggest that you perform a row by row swap of the pixels in the image data in main memory before you send it to gpu ram.

Consider the following image:

If we want to access the bottom row, we go to:

```
pixels+( (sizeof(pixel) * w) * row_number)

```

And to access the final pixel of that row we use:

```
pixels+( (sizeof(pixel) * w) * row_number) + w * sizeof(pixel)

```

so, we can iterate through every row until we get halfway through the image.

we take our index and compute two start points (memory addresses)

```
upper_index_start = pixels+( (sizeof(pixel) * w) * row_number);

row_index = H - row_number;
lower_index_start = pixels+( (sizeof(pixel) * w) * row_index);

```

We now have all the information we need. Now, using `memcpy` we can do a row for row swap:

```
temp = new pixel[w];

memcpy(temp, upper_row_start, w*sizeof(pixel));

```

Then copy the lower row into the upper row:

```
memcpy(upper_row_start, lower_row_start, w*sizeof(pixel));

```

Then finally, copy the contents of temp to the lower row:

```
memcpy(lower_row_start, temp, w*sizeof(pixel));

```

Then clean up your `temp` with `delete[] temp;`

The following image will illustrate my point:

In this way, you can do this row for row swap on load, and don't have to muck about with changing UV's.

# Answer
> 2 votes
OpenGL texture are loaded **left to right, bottom to top.**

Many image loaders however will store the image in memory **left to right, top to bottom.**

First pixel from memory is bottom-left for OpenGL.

For example:

```
uint8_t image_data[] = {
    0, 0, 0, 0
    1, 1, 1, 1
    2, 2, 2, 2
    3, 3, 3, 3
};
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);

```

Will load the texture as:

```
top-left         top-right
{2, 2, 2, 2}, {3, 3, 3, 3}
{0, 0, 0, 0}, {1, 1, 1, 1}
bottom-left   bottom-right

```

Where bottom left is UV=(0,0) and top-right UV=(1, 1)

---
Tags: opengl, c++, textures, glsl
---


title: Generation of a moon terrain

text:
# Question
Title: Generation of a moon terrain
I am making a small game like Kerbal Space Program. What I do is when I am over a certain height, I render the planet or moon as a sphere. Each planet or moon will have a generation seed to generate the terrain when I am going to land. This works really well with an earth like planet.

To generate a surface map for an earthlike planet, I just use 3d rotation to see where the point on the map is in a 3d coordinate space, and take its perlin noise value as height (I also use other factors to see what the terrain looks like, but I just start with a height).

This gives me a beautiful mountain, hill kind of landscape, which works good for watery planets. However, moons and rocky planet terrains have a lot of craters & I have no idea how I am going to do with noise.

Also I am using noise so I wouldn't have to save an entire terrain by itself for a celestial body's surface, I use it so I can see where I am on the planet, and generate the height from there. If there are other solutions please tell.

# Answer
> 1 votes
Instead of using a noise, use an algorithm, that creates the terrain.

You should create every point first at a uniform height, then with a seeded random you pick a position and a radius. After you picked the point, go through every point and if the distance between this point and the center is less than or equal to the radius, then it's in the crater, if it's isn't, then just leave it alone.

For every point like this set the height of it to the minimum of the uniform height minus `(x + radius) * (x - radius) / z` where `x` is the distance from the middle point and z is just an arbitary value (A larger value of `z` mean shallower crates) and the current height of the point (in case a different crater already modified it).

The formula `(x - a) * (x - b)` is the short version of a quadratic formula, where `a` and `b` are the zero points of the quadratic curve.

This way you get some inverse bubble like craters. You could add some random noise to the heights if you want it to look less hand-made.

As @DMGregory pointed out, this is probably just a variation of the Worley noise (a noise where the distance is from the closest point is used) with a max effect radius.

---
Tags: procedural-generation, terrain, terrain-rendering, procedural, planet
---


# Question
Title: Sprites with same position rendered in different places on screen
In LibGDX I have few sprites that all have set position (0,0). So in theory they all should render in one place on top of each other but what ends up happening is that all the sprites are being rendered in different spot on screen. For all sprites objects all I do is:

```
Sprite sprite = new Sprite(new Texture("texture.png"));
sprite.setOriginCenter();
sprite.setScale(1/PPM);

```

And then when rendering it:

```
batch.begin();
sprite.draw(batch)
...
batch.end();

```

And here is what I get:

rocket sprite is in completely different place than fire sprite and some other sprites I couldn't even find. I marked "real" 0,0 point with yellow circle. So why are does sprites in different spots? I've heard that it could be because of scaling but since I am setting sprite's origin to center it shouldn't be a problem, right?

# Answer
One possible reason I can see is that your textures have different sizes, and the actual rocket and fire only take up a small portion of them (for example, 256x256 image with a 16x16 rocket in the top right corner).

Another possibility might be that you're not applying the transformation while renderering some the sprites. If you're using a `Camera` remember to call `batch.setTransformationMatrix(camera.combined);` before `batch.begin();`.

And as you yourself noted, scaling might also be the source of the issue. You could try this code instead of setting scale:

```
sprite.setSize(sprite.getWidth() / PPM, sprite.getHeight() / PPM);

```

See if any of these resolves your issue and leave a comment if they do / don't!
> 0 votes

---
Tags: libgdx, sprites
---


# Question
Title: Partial Shader Signatures HLSL D3D11 C++
I had been debugging a problem I was having in a single shader file with 2 functions in it. I'm using DirectX 11, vs\_5\_0 and ps\_5\_0. I have stripped it down to its basic components to understand what was going wrong with the shaders, because the different named components of the Pixel and Vertex shaders were swapping the data being input:

```
void QuadVertex ( inout float4 position : SV_Position,
            inout float4 color : COLOR0,
            inout float2 tex : TEXCOORD0 ) {
    // ViewProject is a 4x4 matrix,
    // just included here to show the simple passthrough of the data
    position = mul(position, ViewProjection);
}

```

And a Pixel Shader:

```
float4 QuadPixel (  float4 color : COLOR0,
            float2 tex : TEXCOORD0 ) : SV_Target0 {
    // Color is filled with position data and tex is
        // filled with color values from the Vertex Shader
    return color;
}

```

The `ID3D11InputLayout` and associated C++ code correctly compiles the shaders and sets them up with some simple primitive data:

```
        data[0].Position.x = 0.0f * 210;
        data[0].Position.y = 1.0f * 160;
        data[0].Position.z = 0.0f;
        data[1].Position.x = 0.0f * 210;
        data[1].Position.y = 0.0f * 160;
        data[1].Position.z = 0.0f;
        data[2].Position.x = 1.0f * 210;
        data[2].Position.y = 1.0f * 160;
        data[2].Position.z = 0.0f;
        data[0].Colour = Colors::Red;
        data[1].Colour = Colors::Red;
        data[2].Colour = Colors::Red;
        data[0].Texture = Vector2::Zero;
        data[1].Texture = Vector2::Zero;
        data[2].Texture = Vector2::Zero;

```

When used with the shader, the `float4 color` always ended up with the position data, and the `float2 tex` always ended up with the color data. After a moment, I figured out that the shader's input and output signatures needed to be in the correct order and the correct format and be *laid out in the exact order of the output from the Vertex Shader, regardless of the semantics*:

```
float4 QuadPixel (  float4 pos : SV_Position,
            float4 color : COLOR0,
            float2 tex : TEXCOORD0 ) : SV_Target0 {

    return color;
}

```

After finding this out, My question is: Why don't the semantics map the appropriate components when going from Vertex Shader to Pixel Shader? Is there any way that I can make it so certain semantics are always mapped to other semantics, or do I always have to follow the rigid Shader Signature (in this case, Position, Color, and Texture) ?

As a side note for why I'm asking: I know that when using XNA, my shader signatures for functions could differ in position and even drop items from Vertex Shader to Pixel Shader function parameters, having only the COLOR0 and TEXCOORD0 components being used (and it would still match up correctly). However, I also know that XNA relied on DX9 (and maybe a little DX10) implementation, and that maybe this kind of flexibility no longer exists in DX11?

# Answer
> 4 votes
Yes, this behavior changed from DX9 to DX10+, don't know much about the real story behind it, but I suspect that DX9 had to remap registers between VS and PS at runtime anyway (when linking shaders) which is inefficient.

In DX10+, when you compile a VertexShader and a PixelShader, you can see which register will be affected to a particular semantic (see output of fx.exe compiler), and these registers (which will almost map to an hardware register) should match between the output of a stage to the input of the next stage. Note that the input of a stage could have less semantics mapped, as long as the order is the same and there is no gap in the mapping.

If you are using some legacy FX file (techniques/passes) with DX10+, the compiler will check input/output signatures for you. But if you are compiling separately VS and PS, you will have to double check any signature mismatch (or you can use D3DCompiler API to verify this yourself).

There is one exception for the input of the VertexShader that is coming from the VertexBuffer and the InputLayout. The InputLayout is able to specify the byte offsets of each vertex elements and how it maps to the semantic in the VS shader, so you can have a "sparsed" mapping, the input layout can have more vertex elements/semantic bindings than the VS input, as long as all semantics from the VS are covered by the InputLayout declaration. This is handy when you have a model that has several vertex elements, and want to use the same vertex buffers for several vertex shaders that are expecting different input layouts: you can map the layout of the vertex buffer to the layout of the vertex shaders (as long as the mapping is covering all the input of the VS shader).

# Answer
> 1 votes
thanks to @xoofx 's good answer, and I found this MSDN doc:

https://msdn.microsoft.com/en-us/library/windows/desktop/bb509650(v=vs.85).aspx

---
Tags: shaders, hlsl, directx11, directx9
---


title: Browser RPG mechanic from tabletop RPG

text:
# Question
Title: Browser RPG mechanic from tabletop RPG
The GURPS "you have 100 point to buy attributes, advantages and skills, but you can get disadvantages for bonus points" mechanic can work in browser based RPG's?

# Answer
> 1 votes
*It may work.*

# What does it mean to take a disadvantage?

There are two ways to implement a disadvantage mechanic. One is a difference in scale and the other is a difference in kind.

## Difference in Scale

If taking disadvantage means to take points from zero (going negative). The question is whatever or not there is a valid range for the values.

If there is a minimum for the stats (such as -3, for example) then it is possible to transform the stats to a system where there are no negatives.

For example, if you have three stats A, B and C, and you can use 10 points to set among them, and the value of each stat can go as low as -3... it is equivalent to having three stats A, B, and C, having 19 points and the value of each stat can go as low as 0, plus you see by default A = 3, B = 3 and C = 3 (up to 9 points set by default, out of 19, leaving your original 10 points to set).

You may not have a minimum, but you have a maximum... For example, if the stats A, B and C can only go up to 10, and you have 10 points, you could put all those 10 points on A, put B to -10 points, and put those in C. You will not be able to go below B = -10 because you will not have where to put those points... therefore, -10 is your implicit minimum. Now that you have a minimum, you can change your system to be A, B and C with 40 points and set to A = 10, B = 10 and C = 10 by default (up to 30 points set by default, out of 40, leaving your original 10 points to set).

Doing that transformation makes it clear to the user that he can remove points and put them somewhere else. The user may not know that they can remove points from zero points.

Alternatively, if you have a system where there is no minimum, you may have a character with something like A = -100000, C = 0, B = 100000, or A = -1000000000, C = 500000000, B = 500000000, or worst, you get the idea. Does that break your game? Will the player be able to exploit this? - Unless you are designing for this scenario, I suggest having a valid range for your points.

Edit: there would be a theorical limit to the valid ranges anyway. Either imposed by the data types you choose or by the patience your players may have moving points around.

---

Under the assumption that there is some minimum and you did the transformation to zero based points, you end up with a system used in some computer games. For example, Fallout character creation follows this method. Moreover, I would say it works.

---

## Difference in Kind

On the other hand, taking a disadvantage could mean some other constraint that change the gameplay, something that can't be quantified.

Some examples are:

* Only being able to use single hander weapons when you normally would be able to use any.
* Causing a new type of enemy to spawn
* Making certain drops disappear completely
* Changing the starting area to a more difficult one
* Closing access to locations that allow healing or looting

Then this becomes a more powerful mechanic. It add potential to replay the game with the added constraints as an extra challenge.

Note: I would count less inventory space, more enemies to spawn and less drops as numeric disadvantages. We can invent stats for them, and they only cause differences in scale and not differences in kind.

---

# Browser Game?

Since the question about a browser game in particular, we should consider what challenge this restriction adds to the proposed system.

For a browser game, the main consideration would be how much time do you expect the player to expend during character creation and how much time will the player stay with the same character.

Being a browser game does not need to imply casual gameplay. For example, if the user can save his character in his account to use it in multiple sessions, it makes the extra time investment into creating the character worthwhile.

If we were indeed talking about a casual game, I would suggest keeping it simple, at least have a few preconfigured setups for people who do not understand or do not care and just want to jump into the game. Yet, that should not discourage you from using something like this. In particular, as mentioned before, adding this kind of configuration may add replay value for you game if you design gameplay for characters that focus on each of your stats.

---
Tags: game-design, game-mechanics, rpg, browser-based-games
---


# Question
Title: How can I trigger a buttton click event at regular intervals?
I am trying to make an idle clicker game like Adventure Capitalist. I have created the script for the buttons (say button-type: buy) that would increase the gold and the script to upgrade the gold per click (button-type :upgrade). Now I want to create a C# script for a button(button-type: auto clicker) that would enable me to automatically click those button at regular intervals?

These are my scripts:

```
public class Click : MonoBehaviour {

    public Gold gold;
    public float gpc;
    public Text goldCount;
    public float price;
    public int active = 0;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        goldCount.text = "$" + gold.gold;
    }

    public void Activate()
    {
        if(active == 0)
        {
            if(gold.gold >= price)
            {
                gold.gold -= price;
                active = 1;
            }
        }
    }

    public void Clicked()
    {
        if(active == 1)
        {
            gold.gold += gpc;
        }
    }
}

```

---

```
public class Gold : MonoBehaviour {
    public float gold;
    // Use this for initialization
    void Start () {

    }

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

    }
}

```

---

```
public class UpgradeManager : MonoBehaviour {

    public Click click;
    public Gold gold;
    public float upgradeCost;
    public int count;
    public int clickPower;
    public string itemName;
    // Use this for initialization
    void Start () {

    }

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

    }
    public void PurchasedUpgrade()
    {
        if(gold.gold >= upgradeCost)
        {
            gold.gold -= upgradeCost;
            count++;
            click.gpc = clickPower;
            upgradeCost = Mathf.Round(upgradeCost * Mathf.Pow(1.15f, count));
        }
    }
}

```

# Answer
If I have something interval related and I don't want to bother with `InvokeRepeating` \+ `CancelInvoke` combo or a coroutine, I just use a generic timer.

Sample code:

```
float timerCheck = amountYouWantToCheckAgainst;
float timer = 0;

Update(){
    timer = timer + Time.deltaTime; //add time passed since last frame to your timer
    while(timer > timerCheck){
        Invoke("MethodName", 0); //call whatever method you'd like to call
        timer = timer - timerCheck //subtract timerCheck from timer
    }
}

```

The reason we subtract `timerCheck` from timer is because there might come a point where you'd like to call this function more than once after a frame, if we just checked against the `timerCheck` then it'd only run once.

Example situation:

> Let's say 10 miliseconds has passed since last frame and you wanted a click every 3 miliseconds. If we reset the timer every time the event happened, we'd get a click after that particular frame.
>
> By subtracting `timerCheck` from `timer` and looping we get to run the function three times and we also don't lose our remaining timer amount (which is 1 milisecond in this case).
>
> When the next frame comes around and you now want a click every 2.5 miliseconds and if we assume 9 miliseconds has passed since last frame, we now have a timer that is equal to 10 miliseconds. On this frame, the loop will run four times.

This does run the risk of going through a loop too many times and stalling the gameplay but since you need an auto-upgrade kind of thing, I assume you'll never see a problem like this.

If you need to click on many upgrades and you need different counters for all of them, then `InvokeRepeating` and `CancelInvoke` will work much better than this method in terms of performance.
> 1 votes

# Answer
You could use either an IEnumerator or Unity's InvokeRepeating:

`InvokeRepeating("method name", float start_delay, float interval_time);`
> 0 votes

# Answer
I would check every Update() if it's time to activate, and increment the timer every frame regardless. Doing it with coroutines or other delayed execution would make it tricky to change the interval mid-stream, and in these sorts of games it's common to upgrade and change how long it takes while in the middle of waiting.
> 0 votes

# Answer
InvokeRepeating would work, but you are very limited and cannot change the interval once you start.

I would use a coroutine instead

```
float interval;
IEnumerator pressButton(<insert args here>){
   while(condition){
      buttonClick();
      yield return new WaitForSeconds(interval);
   }
}

```

The advantage of coroutines is that you can modify those variables whenever / wherever you want and your code will work accordingly.

This can also allow your timescale to align with detla time and other factors if you so choose.

As per the discussion with jhocking, there is a potential complication in that any changes to data / interval would not take effect until after the current cycle completes (IE, changes will not be immediate). This problems directly relates to the length of your intervals. Shorter intervals will be significantly less noticeable, while longer ones will be more so.

if this is not a concern, it's the easiest and cleanest way to solve the problem (IMO).
> 0 votes

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


# Question
Title: Rigid body falls through static mesh even though collision is detected
I'm using Jitter Physics to create a game. For testing, I have ball (a spherical rigid body) falling onto a small box-like mesh. The problem is that the ball falls straight through the floor, even though the collision seems to be detected properly.

The mesh's rigid body is created using a triangle mesh shape. In the code below, model is the floor's 3D model

```
Octree octree = PhysicsUtilities.ExtractOctree(model);
octree.BuildOctree();

Body body = new RigidBody(new TriangleMeshShape(octree));
body.IsStatic = true;

```

The `PhysicsUtilities.ExtractOctree` function extracts vertices from the 3D model in order to create the rigid body. As far as I can tell, that function is working correctly (i.e. all vertices and indices look correct). To check if the collision was detected, I added a callback function as follows.

```
CollisionSystem collisionSystem = new CollisionSystemSAP();
collisionSystem.CollisionDetected += OnCollisionDetected;

World world = new World(collisionSystem);

```

The ball-floor collision is detected and everything about the collision looks correct. I've even tried changing values in `world.ContactSettings`, but nothing worked.

Has anyone else experienced this problem? I've tried everything I can and Jitter's documentation is pretty low.

# Answer
> 1 votes
Collision detection has very little to do with *collision response*, besides triggering it.

Check your settings for both bodies, and the settings for the physics system:

1. Collision callbacks: Is there a collision behaviour for each body?
2. Body density: if density is too low, objects float through each other.
3. Mass: physics needs this to compute kinematic response and normal forces. make sure the value is set.

---
Tags: collision-detection, 3d, collision-resolution, physics-engine
---


# Question
Title: Which Type of Collision Detection should I use?
So over the past week I've been scratching my head over SAT (Separating Axis Theorem). I know how it works, but can't seem to get the C# code right. There's always one face or edge that's letting my player through an obstacle.

So I wanted to know if maybe I'm taking the hard way around, and I don't need SAT for what I want to achieve.

**My Game Involves:**
\- 3D Cubes which will sometimes be on an angle (not a multiple of 90)
\- Not too many cubes (so I don't need my Collision Detection to be too inexpensive)
\- OBB collisions

So what is the best option for me collision-wise? If SAT is my go to option, what would it look like in C#?

**EDIT**

My Sat code:

```
var n1 = (bb1.BCK_TOP_LFTCorner - bb1.BCK_BTM_LFTCorner).Normalized();
var n2 = (bb1.BCK_BTM_LFTCorner - bb1.BCK_BTM_RGTCorner).Normalized();
var n3 = (bb1.FRT_BTM_LFTCorner - bb1.BCK_BTM_LFTCorner).Normalized();
var n4 = (bb2.BCK_TOP_LFTCorner - bb2.BCK_BTM_LFTCorner).Normalized();
var n5 = (bb2.BCK_BTM_LFTCorner - bb2.BCK_BTM_RGTCorner).Normalized();
var n6 = (bb2.FRT_BTM_LFTCorner - bb2.BCK_BTM_LFTCorner).Normalized();
var norms = new List<Vector3>() {
     new Vector3(-n1.X, n1.Y,n1.Z),
     new Vector3(n2.X, -n2.Y,n2.Z),
     new Vector3(n3.X, n3.Y,-n3.Z),
     new Vector3(-n4.X, n4.Y,n4.Z),
     new Vector3(n5.X, -n5.Y,n5.Z),
     new Vector3(n6.X, n6.Y,-n6.Z),
};
norms = bb2.Normals;
float max1 = 0;
float min1 = 0;
float max2 = 0;
float min2 = 0;
for (int a = 0; a < norms.Count; ++a)
{
    //Global.Min/Global.Max are simply Math.Min/Math.Max for an array of parameters
    max1 = Global.Max(Vector3.Dot(bb1.Corners[0], norms[a]),
            Vector3.Dot(bb1.Corners[1], norms[a]),
            Vector3.Dot(bb1.Corners[2], norms[a]),
            Vector3.Dot(bb1.Corners[3], norms[a]),
            Vector3.Dot(bb1.Corners[4], norms[a]),
            Vector3.Dot(bb1.Corners[5], norms[a]));
        min1 = Global.Min(Vector3.Dot(bb1.Corners[0], norms[a]),
            Vector3.Dot(bb1.Corners[1], norms[a]),
            Vector3.Dot(bb1.Corners[2], norms[a]),
            Vector3.Dot(bb1.Corners[3], norms[a]),
            Vector3.Dot(bb1.Corners[4], norms[a]),
            Vector3.Dot(bb1.Corners[5], norms[a]));
        max2 = Global.Max(Vector3.Dot(bb2.Corners[0], norms[a]),
            Vector3.Dot(bb2.Corners[1], norms[a]),
            Vector3.Dot(bb2.Corners[2], norms[a]),
            Vector3.Dot(bb2.Corners[3], norms[a]),
            Vector3.Dot(bb2.Corners[4], norms[a]),
            Vector3.Dot(bb2.Corners[5], norms[a]));
        min2 = Global.Min(Vector3.Dot(bb2.Corners[0], norms[a]),
            Vector3.Dot(bb2.Corners[1], norms[a]),
            Vector3.Dot(bb2.Corners[2], norms[a]),
            Vector3.Dot(bb2.Corners[3], norms[a]),
            Vector3.Dot(bb2.Corners[4], norms[a]),
            Vector3.Dot(bb2.Corners[5], norms[a]));

    }
if (max1 < min2)
    return Vector3.Zero;
    // Get nearest face normal to player so that we can add it to player's velocity.
    var rl = new List<Vector3>() {bb2.Front,
        bb2.Back,
        bb2.Top,
        bb2.Bottom,
        bb2.Left,
        bb2.Right };
    var r = rl.IndexOf(rl.OrderBy(c => c.Distance(bb1.Center)).First());
    var returnval = bb2.Normals[r];
    return returnval;

```

# Answer
SAT is a good algorithm for learning narrow phase collision detection, as the code is pretty intuitive.

As to what it would look like in language X, you should simply read a tutorial on SAT and then port it to your language of choice once you understand the algorithm completely.

I would say this though: If you plan to do any sort of accurate physics, you will need additional processing on top of SAT code to compute contact points, and online tutorials are a little spotty on that subject. If you find the additional processing is hard to find/wrap your head around, take a look at:

1. Gilbert Johnson Keerthi (GJK)
2. Expanding Polytope Algorithm (EPA)
3. Minkowski Difference

All these are perhaps a little more difficult to wrap your head around, but they are pretty fast, and provide contact points "out of the box" will no additional processing.
> 1 votes

---
Tags: c#, collision-detection, 3d
---


# Question
Title: Unity multiplayer with custom server - interpolation jumping
I've built a Server / Client environment for my Unity game which is pretty simple. It is written in C# with asynchronous sockets. To keep it simple, the player sends his input data and the server broadcasts it to every connected player.

My message packets have to the following strucutre:

```
Username|Command|Scene ID|X Position|Y Position|Horizontal Axis Input|Vertical Axis Input

```

An example packet for player movement / position data would look like this:

```
PlayerA|P|0|0.12341123|1.3423424|-1|0

```

My first approach was to sent the data every frame. As you can imagine that was too often and the game was laggy with only two players moving simultaneously. Then I've read about interpolation. So I reduced sending the data. I now send only position data if a certain distance was walked or after a certain amount of milliseconds. The rest is calculated via interpolation. Unfortunately I got my interpolation code from a tutorial using the Unity multiplayer functionality.

Now the result I get is that the player kind of jumps. I have a guess why. The player sends his position when he reached it. I think that is too late. But I have no idea how I could fix that problem.

I have two objects. A player object, which is using the script PlayerMovement and a prefab which is using the CharacterMovement for in game movement. I think these two scripts are the important once to help me, so here they are:

**PlayerMovement.cs**

```
using System;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement : MonoBehaviour
{
    Rigidbody2D Body;
    Animator Animator;

    private bool sendStopWalking = false;
    public float Threshold = 0.5f;

    DateTime lastSentDateTime = DateTime.Now;

    private Vector3 lastSentPosition;

    private void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
    }

    void Start()
    {
        Body = GetComponent<Rigidbody2D>();
        Animator = GetComponent<Animator>();
    }

    void Update()
    {
        // GetAxisRaw Returns 0 / 1 / -1
        Vector2 movementVector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        if(movementVector != Vector2.zero)
        {
            Animator.SetBool("IsWalking", true);
            Animator.SetFloat("InputX", movementVector.x);
            Animator.SetFloat("InputY", movementVector.y);

            if (NetworkManagement.IsConnected)
            {
                Vector3 currentPosition = Body.transform.position;
                if(isOverThreshold(lastSentPosition, currentPosition, Threshold) || isTimeToSend(500))
                {
                    lastSentDateTime = DateTime.Now;
                    NetworkManagement.ClientSocket.Send(string.Format("P|{0}|{1}|{2}|{3}|{4}", SceneManager.GetActiveScene().buildIndex, currentPosition.x, currentPosition.y, Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")));
                    lastSentPosition = Body.transform.position;
                    sendStopWalking = true;
                }

            }
        }
        else
        {
            Animator.SetBool("IsWalking", false);

            if(sendStopWalking && NetworkManagement.IsConnected)
            {
                NetworkManagement.ClientSocket.Send(string.Format("P|{0}|{1}|{2}|{3}|{4}", SceneManager.GetActiveScene().buildIndex, Body.transform.position.x, Body.transform.position.y, Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")));
                sendStopWalking = false;
            }
        }

        Body.MovePosition(Body.position + movementVector * Time.deltaTime);
    }

    private bool isOverThreshold(Vector3 oldPosition, Vector3 currentPosition, float threshold)
    {
        return Vector3.Distance(oldPosition, currentPosition) > threshold;
    }

    private bool isTimeToSend(double milliseconds)
    {
        return ((DateTime.Now - lastSentDateTime).TotalMilliseconds > milliseconds);
    }
}

```

**CharacterMovement.cs**

```
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    Rigidbody2D Body;
    Animator Animator;
    public float AxisRawHorizontal;
    public float AxisRawVertical;

    public Vector3 ServerPosition;

    public float LerpValue = 4;

    void Start()
    {
        Body = GetComponent<Rigidbody2D>();
        Animator = GetComponent<Animator>();
    }

    void Update()
    {
        Vector2 movementVector = new Vector2(AxisRawHorizontal, AxisRawVertical);

        if (movementVector != Vector2.zero)
        {
            Animator.SetBool("IsWalking", true);
            Animator.SetFloat("InputX", movementVector.x);
            Animator.SetFloat("InputY", movementVector.y);
        }
        else
        {
            Animator.SetBool("IsWalking", false);
        }
        interpolate();

        //Body.MovePosition(Body.position + movementVector * Time.deltaTime);
    }

    private void interpolate()
    {
        Vector3 position = Vector3.Lerp(this.transform.position, ServerPosition, Time.deltaTime * LerpValue);
        this.transform.position = position;
    }
}

```

I seriously have no more idea and unfortunately I never have been good in maths and physics, so I hope someone can help me here. If there is any more information needed, please tell me. I tried to reduce the question to the most important things.

# Answer
> 1 votes
Before starting,

**Period:** The time it takes to complete one full turn of a repetitive event. So, `Period = 1/Frequency`.

---

The method you are using can work pretty robust for simple movement, but when it comes to special actions like jumping, casting spells, attacking an enemy etc; you need to consider a question:

Does the *period* of the action is greater than the communication *period*? (That is; is the time it takes for the action to complete, greater than the time between two network packets we send?)

If period of movement is lower than period of your messages, than you cannot rely on a regular broadcast, because as you mentioned in your question, the action will actually end before you can send a second packet of information.

So, you can *force* a packet send at the very beginning of the action (and maybe also at the end, depending on the type of action). This way, you can notify the server that you are "*jumping*", instead of just saying "*I am floating in the air*".

Then, when you receive the action in the client, instead of interpolating between two positions, you can actually play the "jump" action on the character. This way you can actually make the remote character jump, just like the way the local character does, instead of ascending it to mid air via interpolation. And when the remote character hits the ground, then you can simply continue to interpolate.

If you want more precision, you can interpolate the "heading" of remote character mid-air, so that it doesn't land somewhere far far away fron the actual landing point.

---

*And lastly, I suggest you to follow MSDN naming conventions for C# in your code. It will make your coding life really easier.*

---
Tags: unity, c#, multiplayer, interpolation
---


# Question
Title: How to copy the value of a variable from one script to another in Unity?
I would need some help with making two floats from two different classes, match their "data".

What I want to do here is to make it so when `Body.healthb` hits a value of 0, `Head.health` will also hit 0.

Any suggestions? I'm barely new to this.

The class from which the float comes from:

```
public class Body : MonoBehaviour
{
  public GameObject body;

  public float healthb = 50f;

  public void TakeDamageb(float amountb)
  {
    healthb -= amountb;
    if (healthb <= 0f)
    {
      Dieb ();
    }
  }

  // Update is called once per frame
  public void Dieb()
  {
    Destroy (gameObject);
  }
}

```

The class it has to reach:

```
public class Head : MonoBehaviour
{
  public static float health = 10f;
  public void TakeDamage(float amount)
  {

    health -= amount;
    if (health <= 0f)
    {
      Die ();
    }
  }

  // Update is called once per frame
  public void Die()
  {
    Destroy (gameObject);
  }
}

```

# Answer
> 1 votes
If all you need is for a part to kill its dependent parts on death (ie. head -\> body), we can do this with a single `HealthPool` component with a reference to its dependent part(s):

```
public class HealthPool: MonoBehaviour {

   public float startingHealth;

   // Make current health show in the inspector, but protect it from direct editing
   // by other scripts unless they go through TakeDamage()
   [SerializeField]
   float _currentHealth;
   public float currentHealth { get { return _currentHealth; }}

   public HealthPool killOnDeath;

   public void TakeDamage(float amount) {
        _currentHealth -= amount;

        if(_currentHealth <= 0f)
           Die();
   }

   // Kill our dependent object when we die:
   public void Die() {
       Destroy(gameObject);

       if(killOnDeath != null)
         killOnDeath.Die();

       // This will naturally cascade down to the dependent part's dependent parts,
       // eg. if you had a multi-part snake that should die backward from the head.
   }
}

```

If you need any more complicated interactions between the body parts, I'd be inclined to still use a simple `HealthPool` component on each body part, and have it report its damage up to a `HealthPoolCollection` on their shared parent/grandparent/ancestor (even if that shared ancestor is the head or body itself):

```
public class HealthPool: MonoBehaviour {

   // In case you need to make decisions based on whether it's a head/body/etc
   // This exposes a list to the Inspector to select from.
   [System.Serializable]
   public enum HealthPoolType { Other, Head, Body };

   public HealthPoolType type;

   public float startingHealth;

   [SerializeField]
   float _currentHealth;
   public float currentHealth { get { return _currentHealth; }}

   HealthPoolCollection _collection;

   void Start() {
        // Assuming these sit under the same parent/grandparent/etc.
        // If not, you can wire up this reference in the inspector.
        _collection = GetComponentInParent<HealthPoolCollection>();
        if(_collection != null)
            _collection.Register(this);
   }

   public void TakeDamage(float amount) {
        _currentHealth -= amount;
        if(_collection != null)
           _collection.ReportDamage(this, amount);

        if(_currentHealth <= 0f)
           Die();
   }

   public void Die() {
       // If you want the shared object to die,
       // consider moving this to the parent collection script instead.
       Destroy(gameObject);
   }
}

using System.Collections.Generic;

public class HealthPoolCollection : MonoBehaviour {
    List<HealthPool> _pools = new List<HealthPool>();

    public void Register(HealthPool pool) {
        _pools.Add(pool);
    }

    public void ReportDamage(HealthPool pool, float damage) {
        // Add logic here to pass the info along to other health pools / etc.
    }
}

```

Both these approaches have some similar advantages:

* Anything that deals damage only needs to know about a single Health Pool component type, not separate head & body flavours.
* You only have to write damage taking & dying logic once, and maintain it in one place, following the principle "Don't Repeat Yourself"
* Health pool relationships are hierarchical & one-way, so you don't end up with a spaghetti mess of sibling-to-sibling references to disentangle: there's a single place to look if you want to track a death to its source.

# Answer
> 1 votes
DMGregory's answer is all well and good but I think it might be over the heads of beginners, so here's a simpler solution.

What you want to do is reference these two with each other or in a separate script.

Example code:

```
public class Body : MonoBehaviour
{
  public Head head;

  public float health = 50f;

  public void TakeDamage(float amount)
  {
    health -= amount;
    if (health <= 0f)
    {
      head.BroadcastMessage("TakeDamage", head.health); //if the body dies, damage the head as much hitpoints as the head has.
      Die ();
    }
  }

  // Update is called once per frame
  public void Die()
  {
    Destroy (gameObject);
  }
}

```

Now the other part:

```
public class Head : MonoBehaviour
{
  public Body body;

  public float health = 10f;

  public void TakeDamage(float amount)
  {

    health -= amount;
    if (health <= 0f)
    {
      body.BroadcastMessage("TakeDamage", body.health); //if the head dies, damage the body as much hitpoints as the head has.
      Die ();
    }
  }

  // Update is called once per frame
  public void Die()
  {
    Destroy (gameObject);
  }
}

```

These will be your classes or, more likely, scripts on your objects. Add the scripts on the relevant objects. Drag the `Head` script to the `Body`'s script slot in the editor and also drag the `Body` script to the `Head`'s script slot in the editor.

The line where we call the method to damage the head or body could also easily be changed into `body.BroadcastMessage("Die");` but this method runs the risk of not going through the proper take damage channel you are implementing and it means it will bypass anything you implement in that method.

# Answer
> 0 votes
You should have 1 health for the whole character and different parts would have referenced to it. When head gets hit by calling `this.GetComponent<BodyPart>TakeDamage(amount);` \- it calls `this.character.TakeDamage(amount * bodyPartHitBonus);` inside.

`// bodyPartHitBonus - head could have 5 for example, so if damage from weapon was 20, then 20 * 5 = 100 damage done to character`.

Now you don't have to worry about referencing all the body parts in every script and you can get different damage depending on weapon damage and body part hit.

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


title: OpenGL 4 several glUseProgram overhead

text:
# Question
Title: OpenGL 4 several glUseProgram overhead
I'm developing a little 2D game using OpenGL 4.x and I've also coded a very simple light system which does not take care of shadows. The main concept behind this light system is the frambuffer multiplicative blending. I basically have **two framebuffers**, one for the normal scene render and the other one for ambient light and the scene light sources. Then, I blend those two framebuffers and I get my final result (which is pretty good, to be honest).

In this model I have 3 different shader programs:

* One for rendering the normal scene (with texturing and other normal features)
* One for rendering lights, which compute light halos and other light effects
* One for blending the two framebuffers together

Now, in my main application loop I have to switch between those three shader programs in order to complete a full rendering cycle. I'm also planning to add more shaders to render different light effects and particles. At the moment I'm in the design phase of my game, so I'm not able to test out the performance of this approach and I have no previous experience with it. And for the same reason I'd like to start with the best approach possibile for this situation.

So my question is: considering your experience, is switching between **several** shader programs at each frame something good or is it a *bad behaviour* in a 2D enviroment ? Is using fewer shader programs but with more `if` statement and more unused uniform variables a better solution?

# Answer
> 1 votes
In general, the fewer state changes the better. However, as state changes are unavoidable, there are some ways you can consider how to reduce the number of them.

Group/sort entities by shader/texture/mesh etc, so that you draw a bunch of stuff for each group with as few state changes as possible. To be honest though, as you are in the design phase, I wouldn't worry about this too much.

Get stuff working first, *then* optimise.

# Answer
> 0 votes
The best way to find out is to try both options and measure performance since this is not as easy to predict as it seems.

But there are a few points to keep in mind. One is that GLSL is not very good at branching. So while setting a uniform and then switch in the shader might look like a good idea because it reduces calling glUseProgram but can result in a worse performance since the graphics card is bad at branching.
Grouping shaders together and switch between these shaders might better. But in the end you should try both options and measure performance. When you decide to use less shaders and set options with uniforms I recommend to sort the vectors or whatever data structure you use by the uniform values and render them then.
But always measure performance in release builds and then decide. Also don't optimize to early. When the shaders are very simple and get more complex later the first performance runs might not be significant for the current system.

In this tutorial the same is said about branching in shader code.

---
Tags: opengl, shaders, performance, optimization
---


# Question
Title: Long loading times on large PNG file using C++, OpenGL & SOIL
I'm currently optimising a C++ OpenGL game, and I've noticed something slightly odd about texture loading.

I've got a number of PNG files I load as textures and use as spritesheets; these are generally 512px or 1024px, with one 2048px. I use SOIL (www.lonesock.net/soil.html) to load the PNGs then bind them to a custom OpenGL texture class.

I've put some primitive code in to measure how long it takes to load these PNG files as textures measured in ticks. Generally speaking the load times are:

512px PNG: 100 - 150 ticks 1024px PNG: 400 - 500 ticks 2048px PNG: 1800 - 2000 ticks

Now I recognise that not all image files are created equally, but these don't quite seem to add up with what I understand in terms of texture files. There's not much to be gained by using fewer larger textures compared to more smaller textures, and often there's no gain for that 2048px PNG compared to four 1024px.

My question is, are these (relative) load times normal? Is there something I'm missing when it comes to loading textures with SOIL?

Note that my question isn't 'how can I generically speed up image loading times' (I may at a later date convert these to more OpenGL friendly file formats like DDS), but more is there a pattern I should / shouldn't be using to optimise this?

Thanks

Nathan

# Answer
Bit of an old question but I've actually discovered what the problem here was. My instinct that basic loading of 2D textures was taking a long time was correct for the following reason:

When using the SOIL library I used the flags "SOIL\_FLAG\_MIPMAPS" and "SOIL\_FLAG\_COMPRESS\_TO\_DXT". Removing the "SOIL\_FLAG\_MIPMAPS" (no real need in a fixed camera 2D game) reduced loading time by a third, and removing "SOIL\_FLAG\_COMPRESS\_TO\_DXT" reduced this by a factor of about 50 (i.e. 1000 game ticks down to 20 game ticks), whether using PNG or DDS source file format. I'm yet to fully determine the benefits of the compress to dxt flag, there doesn't appear to be any change in memory, but I'll continue to experiment.
> 0 votes

# Answer
A 2048x2048 image is 4 times as large as a 1024x1024 image which in turn is 4 times as large as a 512x512 image. You're getting a loading time that increases linearly with image size, which is the behaviour you should expect.

PNG, however, is not the best format for storing game graphics which must be sent to an API like OpenGL. While PNG files are small and can be read off disk quickly enough, they are slow to decompress in memory, and because no graphics hardware has native support for PNGs, they must be decompressed before the graphics hardware can use them.

Despite this there are possibly areas where you can optimise further. For example, if you're using GL\_RGB/GL\_UNSIGNED\_BYTE or GL\_RGBA/GL\_UNSIGNED\_BYTE for your format/type parameters to glTexImage, you should consider switching to GL\_BGRA instead (and one some hardware use GL\_UNSIGNED\_INT\_8\_8\_8\_8\_REV instead of GL\_UNSIGNED\_BYTE): using these you'll be telling OpenGL that your data is already in the format and layout that the GPU prefers, and so your driver will probably load the data directly rather than doing it's own intermediate format conversion.

As an alternative to PNG, DDS files with DXT compression (patent expires 2nd October 2017, but is not normally a problem since GPU vendors have licensed it anyway) require between one-quarter and one-eighth the storage of an uncompressed image and are natively supported by most GPUs. Loading can be as fast as memory-mapping a file, reading some header data, then sending some pointers directly through glTexImage. No format conversions, no intermediate buffers, no heavy computation: what's on disk is the same as what's used by the GPU. DXT compression is lossy, however.

Finally, you appear to be misunderstanding the purpose of "using fewer larger textures compared to more smaller textures" - it's absolutely nothing to do with load times, but instead is to allow for better draw call batching and fewer state changes at runtime.
> 4 votes

# Answer
SOIL is a little bit buggy and some things don't load at all or will take an inordinate amount of time to load. Especially large png files. SOIL is a little old and just doesn't seem to like some of the newer formats and encodings all that much.

If I get a photo from a third party I always resave it as a lossless jpeg or similar file with no thumbnails or comments in it. Your results don't seem too terrible but doing this will probably save you some headache down the road.

Probably tiff files are the easiest for it to deal with, but I don't like them too much because windows doesn't know how to deal with them ie it won't give me a preview through windows explorer.
> 0 votes

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