title: How to offer directional ambient audio

text:
# Question
Title: How to offer directional ambient audio
I'm working on a game side-project that will be heavily audio-based. One feature I'd like to offer are ambient sound zones which correspond to locations of nearby areas.

Say for instance the player is standing on a beach with waves breaking to the right, and a rainforest to the left. Each of these regions has its distinct ambience. If you continue forward, the breaking waves should still be just as loud on your right. Similarly, if you head into the forest, the sound of the waves should slowly be replaced as you move away from the beach. Many games seem to treat ambient sound as either vaguely positional, or as an environmental sound that comes from everywhere at once. What I'm trying for are different areas with different distinct sounds so you can actually orient yourself to them (I.e. you should be able to return to the beach by listening for the breaking waves, they shouldn't just be omnidirectional and faint.)

I don't want to get too deep into architecture, but my system is simple 2-D tile-based. I've thought of several possible approaches and am wondering a) which is best or b) if I've missed one that is better.

* Place distinct, loud ambient sounds in specific locations. This would certainly provide directionality of a sort, but I wonder if the ocean waves might eventually sound ahead or behind and right as you walk down the beach, since all the ambience is coming from a single point. This also wouldn't allow for, say, walking out in the ocean past the breakers and hearing them behind you.
* Placing sound sources throughout the area, spaced a reasonable distance apart. So for instance the breakers might be a single row of wave sounds which you could walk along or past. Similarly, the forest would be a grid of scattered nature sounds. This seems like the best approach, but I wonder if I'd quickly hit some limit for number of sounds that can be mixed. I'm using the web audio API, not sure if that intelligently doesn't render sounds that are too soft to hear. While this seems conceptually simpler, a long beach might have hundreds of distinct sound nodes placed along it.
* Track the player's nearest intersection with a given zone, and play its ambience at those coordinates. So if you're walking along a beach with breaking waves to your right, I'd project out an invisible circle for as far as you can realistically hear, identify the closest intersection with various audio zones, and play their respective ambience. Maybe limit this to the nearest 2-3, since any more would likely be overwhelming. This seems least demanding in that it'd play fewer sounds, but would likely require more collision checks and thus might be impractical.

Thoughts?

# Answer
> 1 votes
I'm doing something not entirely dissimilar in my own game (though I don't care about the directionality as such). The approach I've taken is similar to what you say about placing sound sources throughout the area, however with the difference that I don't let each of them be its own actual sound source, but rather just let them contribute volume to an environmental sound, to put it concisely.

Basically, what I'm doing is that, each cycle, I iterate through the various sound sources in the scene and intern all the sources that are "the same sound". So for a given scene, I might find 25 sources that are wind over an open area, 37 that are forest sounds and 5 that are flowing water from the river running through the area. I check the distance of each of the sources from the player and add together their contributing sound volumes, and might then find that I'll be playing open-area wind at 33% of its maximum volume, forest sounds at 50% of its maximum volume and flowing water at 80% (since the player is right next to the river). In the end, I'm just playing 3 sounds, but adapted in volume to the contributions of several sound sources.

I figure it wouldn't be too hard to adapt this method to directional sound -- you should be able to just sum the contributing sound volumes per speaker.

# Answer
> 0 votes
This is a bit late but may help others.

Your ideas are basically sound. Place sound emitters along the ocean edge with reasonable spacing for your needs. If the player can move vertically then you need to place them as a wall rather than a straight line. Limit the number of instances of this type of sound that the player can hear at a time. Select the emitters based on volume. Calculate the volume using the distance to an emitter using whatever falloff formula you like; plain linear should be fine. You set the distance that the volume starts to fade and the distance you hear nothing. You play the n loudest. Any sound engine can do this.

However, if you're rolling your own then there's a simple formula. You have a table of speaker angles for each set of speaker setups you will support for output. If it's headphones, the angles are 90 and 270. The standards for the angles of 5.1 and 7.1 can be found on the web.

For each emitter, calculate it's angle and figure out what speakers it's between and how far. If the sound is at 75° and speakers are 30 and 120 then it's 50% of the way from speaker A to speaker B. You should have a number that is between 0.0 and 1.0. Multiply this by pi/2. This coverts it to an angle between 0 and 90° in radians. Speaker A volume is the cosine of this value and speaker B is the sine of this value. Multiply these by the attenuation volume calculated from the emitter and those are the values you send to each speaker. For the 50% case the start values for each speaker should be 0.707 or you messed up. Many sound engines implement a spill over to adjust the feel but with multiple emitters it wouldn't matter.

So, use an off the shelf sound engine or:

```
/*
Get distance to emitter.
Within falloff range?
  Get the volume V (0.0 to 1.0)
Do this for all emitters, keep the n loudest.

For each remaining emitter:
Get the angle to the emitter
Get the 2 speakers it's between (A & B)
Get the % (P) of how far your angle is from A to B (0.0 to 1.0)
Multiply P by pi/2
SpeakerA = V * cos(P)
SpeakerB = V * sin(P)
*/

```

If your platform takes something other than a value from 0 to 1 for channel volume you'll need to convert it.

---
Tags: audio
---


# Question
Title: How can I make shadows darker in unity5 without changing light intensity?
I have a problem where I want the shadow cast by an object to be a well defined and dark one. However I have to do it without changing how illuminated the object looks so only increasing the intensity of the light won't do(I have already maximized shadow strength).

Is this something i can manipulate in engine or will I have to make some sort of shader adjustments?

This one has the correct illumination on the character:

This one has the correct shadow color on the shadow cast by the character but it is to strongly illuminated:

# Answer
> 4 votes
Use a spot light with increased `Range` and `Spot Angle`. Use full shadow `Strength`.

# Answer
> 0 votes
In unity 5.6, Windows-\>Lighting-\>Settings, turn environmental lighting down to your desired setting, this globally affects ambient light, but not direct lights.

---
Tags: unity, lighting, shadows
---


title: How to use moveTo Actor?

text:
# Question
Title: How to use moveTo Actor?
How to use moveTo?

I do so:

```
actor.addAction(Actions.moveTo(500, 500, 10));

```

but he does not move

Thanks you

`UPDATE`

does not move

my code:

```
public class MyActions extends ApplicationAdapter {
    private Stage stage;
    private Actor actor;

    @Override
    public void create () {

        stage = new Stage();
        actor = new Actor(){
            {
                setSize(100, 100);
            }
            Sprite actorSprite = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")), 57, 10, (int)getWidth(), (int)getHeight());

            @Override
            public void draw(Batch batch, float parentAlpha) {
                actorSprite.draw(batch, parentAlpha);
            }
        };

        stage.addActor(actor);
        actor.addAction(Actions.moveTo(500, 500, 1));
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 1, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        actor.act(Gdx.graphics.getDeltaTime());
        //stage.act();
        stage.draw();
    }
}

```

what's wrong?

# Answer
Answer doesn't make sense after edit.

You should use Texture, not Sprite here. Your code should be like this :

```
public class MyActions extends ApplicationAdapter {
  private Stage stage;
  private Actor actor;
  private Texture texture;

  @Override
  public void create () {
      texture = new Texture(Gdx.files.internal("badlogic.jpg"));
      stage = new Stage();
      actor = new Actor(){
          {
              setSize(100, 100);
          }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            batch.draw(texture,(int)getX(), (int)getY());
        }
      };

      stage.addActor(actor);
      actor.addAction(Actions.moveTo(500, 500, 1));
  }

  @Override
  public void render () {
      Gdx.gl.glClearColor(1, 1, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      stage.act(Gdx.graphics.getDeltaTime());
      stage.draw();
  }
}

```
> 0 votes

# Answer
Your problem is that you're drawing your sprite but you're not updating your sprite's position. Your draw method should be:

```
@Override
public void draw(Batch batch, float parentAlpha) {
    actorSprite.setPosition(getX(), getY());
    actorSprite.draw(batch, parentAlpha);
}

```

This will update your sprite's position to your actor's position before you draw it.
> 0 votes

---
Tags: libgdx
---


# Question
Title: I was expecting a circle to trace a path of parabola . why isnt that the case?
Why isn't the rendered shape a parabola?

```
@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    renderer.begin(ShapeRenderer.ShapeType.Filled);
    position.x += 1;
    position.y = position.x * position.x ;
    renderer.circle(position.x,position.y,radius);
    renderer.end();
}

```

# Answer
> 1 votes
Your function acts like the `y = x^2` function:

As you can see, it acts the same for positive and negative arguments, but it's mirrored through the Y axis. To achieve a parabola, you need to give it a range like `(-5,5)` or `(-100,100)`. What you probably did is you set the `x` to `0` or `1`.

In order to achieve what you want, you should write:

```
float xOffset = 100;

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    renderer.begin(ShapeRenderer.ShapeType.Filled);
    float newX = ++position.x;
    position.x = xOffset + newX;
    position.y = newX * newX;
    renderer.circle(position.x,position.y,radius);
    renderer.end();
}

```

The `xOffset` will move your entire circle by `x` pixels right.

---
Tags: libgdx
---


# Question
Title: How can I make custom character face editor In my game In an optimal way?
In many games there Is section as customize character that you can make your own character.I always love to know how can I make something like It.

Even old game have this feature? but how ?

For Implementing It I need accurate separation for communating between values and facial parts size. So first I made multiple height-map based on facial parts for modifying by vertex shader and work correctly but this method Isn't optimal.can I Implement It just by one texture?

then I tried by using colorful mapping texture for detecting facial parts, but I have problem for getting color values from mapping texture In my shader code.

mapping texture:

My problem Is that my vertex shader Isn't match with my mapping texture.for example If I change `_NoseLength` other parts will changes.how can I tell to vertex shader which part is nose,forehead,lip,cheek,... In my colorful mapping.

Here Is my Shader Code:

```
Shader "Custom/Extrude" {
        Properties {
            _MainTex ("Base (RGB)", 2D) = "white" {}
            _ModTex ("Vertex Modify", 2D) = "white" {}
            _NoseLength ("NoseLength ", Range(-0.05,0.01)) = 1.0
            _LipSize ("LipSize ",  Range(-0.05,0.01)) = 1.0
            _CheekBones ("CheekBones ", Range(-0.05,0.01)) = 1.0
            _ForeHead ("ForeHead ", Range(-0.05,0.01)) = 1.0
            _EyeSize("EyeSize", Range(-0.05,0.01)) = 1.0

        }
        SubShader {
            Tags { "RenderType"="Opaque" "Queue" = "Transparent"}
            Cull off
            CGPROGRAM
            #pragma surface surf Lambert vertex:vert
            #pragma target 3.0

            sampler2D _MainTex;
            sampler2D _ModTex;

            uniform fixed _NoseLength;
            uniform fixed _LipSize;
            uniform fixed _CheekBones;
            uniform fixed _ForeHead;
            uniform fixed _EyeSize;

            struct Input {
                float2 uv_MainTex;
            };

            void vert(inout appdata_full v) {
                float4 lipSize = tex2Dlod(_ModTex, float4(v.texcoord.xy, 0, 0)).g;//Green
                float4 nose = tex2Dlod(_ModTex, float4(v.texcoord.xy, 0, 0)).b; //Blue
                float4 eye = tex2Dlod(_ModTex, float4(v.texcoord.xy, 0, 0)).r; // Red
                float2 cheek = tex2Dlod(_ModTex, float4(v.texcoord.xy, 0, 0)).rg; // Yellow
                float2 forehead = tex2Dlod(_ModTex, float4(v.texcoord.xy, 0, 0)).rb; // Purple
                v.vertex.y += _LipSize * lipSize;
                v.vertex.y += _NoseLength * nose;
                v.vertex.y += _EyeSize * eye;
                v.vertex.y += _CheekBones * cheek;
                v.vertex.y += _ForeHead * forehead ;

            }

            void surf (Input IN, inout SurfaceOutput o) {
                half4 c = tex2D (_MainTex, IN.uv_MainTex);
                o.Albedo = c.rgb;
                o.Alpha = c.a;
            }
            ENDCG
        }
        FallBack "Diffuse"
    }

```

# Answer
> 1 votes
let's Implement It step by step:

1.First you need a way for accessing to color values In texture by shader.

2.Then you can modify vertex shader by color values In your colorful Height map.

**Step 1** : Accessing to colors In the texture test:

```
Shader "SmkGames/ColorReplacement"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _TH("Threshold value",Range(0,1)) = 0.5

        [HideInInspector]_Red("Filter Color 1", Color) = (1.0,0,0,1.0) //Red
        [HideInInspector]_Green("Filter Color 2", Color) = (0,1.0,0,1.0) //Green
        [HideInInspector]_Blue("Filter Color 3", Color) = (0,0,1.0,1.0) //Blue
        [HideInInspector]_Yellow("Filter Color 4", Color) = (1.0,1.0,0,1.0) //Yellow
        [HideInInspector]_Purple("Filter Color 5", Color) = (1.0,0,1.0,1.0) //Purple
        [HideInInspector]_Cyan("Filter Color 6", Color) = (0,1.0,1.0,1.0) //Cyan
        [HideInInspector]_White("Filter Color 7", Color) = (1.0,1.0,1.0,1.0) //Cyan

        _ColorReplacement1("Red", Color) = (1.0,0,0,1.0) //Red
        _ColorReplacement2("Green", Color) = (0,1.0,0,1.0) //Green
        _ColorReplacement3("Blue", Color) = (0,0,1.0,1.0) //Blue
        _ColorReplacement4("Yellow", Color) = (1.0,1.0,0,1.0) //Yellow
        _ColorReplacement5("Purple", Color) = (1.0,0,1.0,1.0) //Purple
        _ColorReplacement6("Cyan", Color) = (0,1.0,1.0,1.0) //Cyan
        _ColorReplacement7("White", Color) = (1.0,1.0,1.0,1.0) //White

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

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            uniform sampler2D _MainTex;
            uniform float4 _MainTex_ST;

            uniform float _TH; //Threshold value

            //MainColors
            uniform float4 _Red;
            uniform float4 _Green;
            uniform float4 _Blue;
            uniform float4 _Yellow;
            uniform float4 _Purple;
            uniform float4 _Cyan;
            uniform float4 _White;

            //Colors Replacement
            uniform float4 _ColorReplacement1;
            uniform float4 _ColorReplacement2;
            uniform float4 _ColorReplacement3;
            uniform float4 _ColorReplacement4;
            uniform float4 _ColorReplacement5;
            uniform float4 _ColorReplacement6;
            uniform float4 _ColorReplacement7;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : Color
            {
                fixed4 color = tex2D(_MainTex, i.uv);
                if(distance(color,_Red)<=_TH){
                    return  _ColorReplacement1;
                }
                if(distance(color,_Green)<=_TH){
                    return  _ColorReplacement2;
                }
                if(distance(color,_Blue)<=_TH){
                    return _ColorReplacement3;
                }
                if(distance(color,_Yellow)<=_TH){
                    return  _ColorReplacement4;
                }
                if(distance(color,_Purple)<=_TH){
                    return _ColorReplacement5;
                }
                if(distance(color,_Cyan)<=_TH){
                    return _ColorReplacement6;
                }
                if(distance(color,_White)<=_TH){
                    return _ColorReplacement7;
                }
                return  float4(color.rgb,1);
            }
            ENDCG
        }
    }
}

```

**Step 2**: now you can easily modify vertex shader by color values In your colorful Height map:

```
    void vert(inout appdata_full v) {
    float4 FacialParts = tex2Dlod(_Mask, float4(v.texcoord.xy, 0, 0));

    if(distance(FacialParts,_FilterColor1)<=_TH){
    v.vertex.xyz += v.normal * _Width; // Extruding
    v.vertex.z +=  _Height * Intensity;
    }
}

```

---
Tags: unity, shaderlab, vertex-shader
---


# Question
Title: Android how to get opengl 3D coordinates in ontouch event
I created a cube in opengl and it rotates in ontouch event. To to this I created a CustomSurfaceView as follows

```
public class CustomSurfaceView extends GLSurfaceView {
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        float x = e.getX()
        float y = e.getY();
    }
}

```

Here x and y are screen coordinates. How can I get 3D coordinated from this? I have already looked gluProject and NeHe. But I dont know how to implement this in my project, it shows that there is no `GLdouble`,`GLfloat` class.

# Answer
> 3 votes
I'm not sure if there is an OpenGL method doing this already but here is how you should work it :

1. First from your touch position, find the corresponding X and Y angle from your camera. The center of the screen is at angle (0; 0), and the corners are at the max angle defined by your camera's field of view. Be carefull cause the max angle in Y and X are different because of your aspect ratio.
2. Using this angle, your camera's position and orientation, you can create a virtual Ray in space.
3. then you must loop on each of your object to detect if your ray collides with your object (you can use the object geometry, or a sphere or box approximation for faster computation). You can find Line/Sphere, Line/Box and Line/Triangle intersection algorithm easily on the net.
4. keep the nearest object intersecting your ray

# Answer
> 1 votes
Check out Chapter 9 in the book OpenGL ES 2.0 for Android by Kevin Brothaler. It's easy to read and explains how to use an inverse perspective matrix to make this process simple:

1. Multiply the normalized touch event `( x , y )` by the inverted MVP matrix—twice with two arbitrarily different `z` values—to create a ray. (Pages 171-172.)
2. Intersect with your plane and you have a 3d location in world space.

---
Tags: android, opengl-es
---


# Question
Title: How to adapt a webgl shader using mouse position to have symmetrical behaviour
I'm trying to create a particular kind of effect for the background of my SpriteKit game, and I've found some shaders on shadertoy that are close to what I want, but I'm struggling to adapt them to do exactly what I want..

There are a few shaders that simulate the sun with atmospheric scattering based on its xy position. here are some examples: https://www.shadertoy.com/view/MsVSWt https://www.shadertoy.com/view/MdtXD2

I want something similar to this effect but I want the glow to be symmetrical, so that when the 'sun' reaches close to bottom or top edge the glow effect is at a maximum, and when it is in the centre it is at a minimum. I've been playing with these shaders trying to get this effect but my understanding of webgl is clearly lacking as I'm struggling to achieve this.

What I've tried playing with is replacing variables such as sunPosition.y with abs(sunPosition.y) - my logic being that the y axis ranges from -1 to 1 so I should be able to get symmetry by making everything positive.. but this in fact has no effect.

If someone can nudge me in the right direction would be greatly appreciated as I'm now thoroughly confused by webgl!

# Answer
> 1 votes
Just replace all the Y-axis-dependent variables `foo` with `1 - abs(2*foo - 1)`. This includes `uv.y` and `sunVec.y`. Here's the second example shadertoy with that modification: https://www.shadertoy.com/view/lsjfzh

```
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.y;

    float sky = uv.y;
    sky = 1.0 - abs(2.0 * sky - 1.0);

    // animation
    vec2 sunVec;
    if (iMouse.x<20.0)
    {
        sunVec = vec2((0.8+0.5 * sin(iGlobalTime)),( 0.44 + 0.4 * cos( 2.0 * iGlobalTime)));
    }else{
        sunVec = iMouse.xy/iResolution.y;
    }

    float sy = sunVec.y;
    sy = 1.0 - abs(2.0 * sy - 1.0);

    //Mie mask
    float sun = max(1.0 - (1.0 + 10.0 * sy + 1.0 * sky) * length(uv - sunVec),0.0)
        + 0.3 * pow(1.0-sky,12.0) * (1.6-sy);

    //the sauce
    fragColor = vec4(mix(vec3(0.3984,0.5117,0.7305), vec3(0.7031,0.4687,0.1055), sun)
              * ((0.5 + 1.0 * pow(sy,0.4)) * (1.5-sky) + pow(sun, 5.2)
              * sy * (5.0 + 15.0 * sy)),1.0);
}

```

---
Tags: opengl, shaders, webgl, spritekit
---


# Question
Title: Fading previous frame doesn't fade all the way to black?
I'm working on a 2D OpenGL program. It'll be a fairly simple fireworks visual.

So far what I have is that I draw a circle with a gradient "glow" to it and move it around on the screen. I want it to have a tail behind it as it moves so instead of calling glClear between each frame, I'm drawing a black quad over the whole screen with transparency in hopes of darkening the previous frame before drawing the next frame. I've got a decent tail on it but I've noticed the tail doesn't completely blend to black.

Currently the red glow moves up the screen and when it goes off the top it instantly moves back down to the bottom to make another pass. You can see that there's a "shadow" of where the ball has been before and it never gets darker.

I have a feeling it has something to do with the blend function. Here's what I currently have:

```
gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

```

I'm using go-gl but it is equivalent to

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

```

Here's the shader that draws the circle and the quad:

```
#version 430 core

layout(location = 0) out vec4 color;
uniform float radius;
uniform vec2 center;
uniform float windowHeight;
uniform vec4 in_color;
uniform int gradient;

void main()
{
  if (gradient == 1) {
    vec2 correctedCenter = vec2(center.x, windowHeight - center.y);
    vec2 p = (gl_FragCoord.xy - correctedCenter) / radius;
    float r = sqrt(dot(p, p));

    if (r < 1.0) {
      color = mix(in_color, vec4(0, 0, 0, 0), r);
    } else {
      color = vec4(0, 0, 0, 0);
    }
  } else {
    color = in_color;
  }
}

```

For the circle I use `gradient = 1` but for the quad I use `0`.

# Answer
Well sure, if you think about it, multiplying the previous value by a value \> 0 will always leave some left over. So if you are multiplying the previous frame by, say, 0.5, it won't ever reach 0 (though practically speaking, once you pass the precision of the machine you'll effectively hit 0). Your options are to make the amount of the previous frame you're mixing in much less so it reaches 0 (by surpassing the precision of the GPU) faster, or keeping the past few positions and blending them with some set values. Like blend in the last 3 position at 25%, 50%, and 75% with the current frame. Or something along those lines.
> 1 votes

---
Tags: fragment-shader
---


title: Stretched textures in Blender

text:
# Question
Title: Stretched textures in Blender
First of all: I'm relatively new to Blender.

I discovered a weird bug in Blender 2.78c. On my object some textures are stretched although they are UV mapped. Since I have no clue why this is happening I took some screenshots which hopefully explain the problem.

I tried various things, but found no way to solve this. Things I tried:

* Unwrap again
* Apply Rotation and scale
* Manually adjusting verts in UV map
* Looking for "dead" verts somewhere in the model

Does anyone know this strange behavior?

Edit: I uploaded my .blend file -\> http://pasteall.org/blend/index.php?id=47124 | merged screenshots due to low reputation :P

# Answer
The issue is bad UV unwrapping from the ngons in your mesh. What you have are vertices in the middle of the corner edge that have unwrapped to be close to the outer corner vertex in the uvmap. This leads to the small section of the image stretching to fill the face between the two vertices.

The simplest fix would be to remove the extra vertices. In vertex select mode select them and press `X`*-\>Dissolve Vertices*

If you needed to keep the ngons, you can get a flat view of the wall in the 3d view (using left/front views would be the easiest) and use `U`*-\>Project from View*
> 3 votes

---
Tags: blender
---


# Question
Title: How to make a palette swap shader that works withn non-pixel art sprites?
I´m trying to build a tool inside Unity that allows our artists to create different color palettes for our characters.

The big problem is that since every single sprite is hand-drawn and hand-painted with different brushes there are no "traditional" color palettes defined for our base sprites. We use around 10-15 base colors for our characters but each character has tons of different shades and saturation variants to their base color on every frame (again, the art is brush-painted like).

Since color indexing is not really an option (unless I want to create a really big color index texture with a gazillion colors) I was wondering if there was a way to create a shader that, given a set of "base colors" and an equivalent color palette, swaps every "similar color" of the character with the color from the new palette (i.e. swap every single reddish color within a tolerance range with a newly defined color).

The goal here is to do this on a shader in real time. I could just write a script that does this and generates a new spritesheet with the swapped colors, but managing one spritesheet per character variation (we aim to have 10 variations per character) is really problematic for our workflow.

I really hope you can help me. I've been trying to find an answer for this for a week.

# Answer
> 4 votes
Chroma key effect used for removing colors but you can change colors Instead of removing them.

> Chroma key compositing, or chroma keying, is a visual effects / post-production technique for compositing (layering) two images or video streams together based on color hues (chroma range). The technique has been used heavily in many fields to remove a background from the subject of a photo or video – particularly the newscasting, motion picture and videogame industries. https://en.wikipedia.org/wiki/Chroma\_key

Here Is the Chroma Key Shader for **non-pixel art sprites** :

```
Shader "SmkGames/ColorReplacement"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}

        [HideInInspector] _color("Color", Color) = (1.0,1.0,1.0,1.0)

        [HideInInspector]_Red("Filter Color 1", Color) = (1.0,0,0,1.0) //Red
        [HideInInspector]_Green("Filter Color 2", Color) = (0,1.0,0,1.0) //Green
        [HideInInspector]_Blue("Filter Color 3", Color) = (0,0,1.0,1.0) //Blue
        [HideInInspector]_Yellow("Filter Color 4", Color) = (1.0,1.0,0,1.0) //Yellow
        [HideInInspector]_Purple("Filter Color 5", Color) = (1.0,0,1.0,1.0) //Purple
        [HideInInspector]_Cyan("Filter Color 6", Color) = (0,1.0,1.0,1.0) //Cyan
        [HideInInspector]_White("Filter Color 7", Color) = (1.0,1.0,1.0,1.0) //Cyan

        _ColorReplacement1("Red", Color) = (1.0,0,0,1.0) //Red
        _LerpValue1("_LerpValue1",Range(0,1)) = 0
        _ColorReplacement2("Green", Color) = (0,1.0,0,1.0) //Green
        _LerpValue2("_LerpValue2",Range(0,1)) = 0
        _ColorReplacement3("Blue", Color) = (0,0,1.0,1.0) //Blue
        _LerpValue3("_LerpValue3",Range(0,1)) = 0
        _ColorReplacement4("Yellow", Color) = (1.0,1.0,0,1.0) //Yellow
        _LerpValue4("_LerpValue4",Range(0,1)) = 0
        _ColorReplacement5("Purple", Color) = (1.0,0,1.0,1.0) //Purple
        _LerpValue5("_LerpValue5",Range(0,1)) = 0
        _ColorReplacement6("Cyan", Color) = (0,1.0,1.0,1.0) //Cyan
        _LerpValue6("_LerpValue5",Range(0,1)) = 0
        _ColorReplacement7("White", Color) = (1.0,1.0,1.0,1.0) //White
        _LerpValue7("_LerpValue6",Range(0,1)) = 0
    }

    SubShader
    {
Tags {"Queue" = "Transparent"} ZWrite Off  Blend SrcAlpha OneMinusSrcAlpha
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            uniform sampler2D _MainTex;
            uniform float4 _MainTex_ST;
            fixed4 _color;

            //MainColors
            uniform float4 _Red;
            uniform float4 _Green;
            uniform float4 _Blue;
            uniform float4 _Yellow;
            uniform float4 _Purple;
            uniform float4 _Cyan;
            uniform float4 _White;

            //Colors Replacement
            uniform float4 _ColorReplacement1;
            uniform float4 _ColorReplacement2;
            uniform float4 _ColorReplacement3;
            uniform float4 _ColorReplacement4;
            uniform float4 _ColorReplacement5;
            uniform float4 _ColorReplacement6;
            uniform float4 _ColorReplacement7;

            uniform float _LerpValue1;
            uniform float _LerpValue2;
            uniform float _LerpValue3;
            uniform float _LerpValue4;
            uniform float _LerpValue5;
            uniform float _LerpValue6;
            uniform float _LerpValue7;

            float _LerpValue;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            half dis(float4 c){
            half result = (pow(_color.r - c.r,2.0)+pow(_color.g - c.g,2.0)+pow(_color.b - c.b,2.0));
            return result;
            }

            fixed4 frag (v2f i) : Color
            {
                 _color = tex2D(_MainTex, i.uv);

                 if(_color.a<=0.15){
                    return half4(0,0,0,0);
                }

                 float4 transparent = float4(0,0,0,0);
                   float4 Red = lerp(_ColorReplacement1,transparent,smoothstep(0,_LerpValue1,dis(_Red)));
                   float4 Green = lerp(_ColorReplacement2,transparent,smoothstep(0,_LerpValue2,dis(_Green)));
                   float4 Blue = lerp(_ColorReplacement3,transparent,smoothstep(0,_LerpValue3,dis(_Blue)));
                   float4 Yellow = lerp(_ColorReplacement4,transparent,smoothstep(0,_LerpValue4,dis(_Yellow)));
                   float4 Purple = lerp(_ColorReplacement5,transparent,smoothstep(0,_LerpValue5,dis(_Purple)));
                   float4 Cyan = lerp(_ColorReplacement6,transparent,smoothstep(0,_LerpValue6,dis(_Cyan)));
                   float4 White = lerp(_ColorReplacement7,transparent,smoothstep(0,_LerpValue7,dis(_White)));

                   return _color + (Green + Red + Blue + Yellow + Purple + Cyan + White);
            }
            ENDCG
        }
    }
}

```

useful links: Chroma Key Shader 2 , Chroma Key Shader 1

# Answer
> 4 votes
It seems like you want a variation mask for each sprite.

This would entail creating a new greyscale image for each spritesheet, with the darkest values being on the parts of the sprite you want to change (here, Mario's clothing) and the lightest values on those you don't (here, his skin and eyes). In game, you can additively color the variation mask with a color of your choosing and then overlay it onto the actual sprite.

There are two caveats. One, you still need an extra spritesheet per character. Two, all of the spots on the regular spritesheet that you want to change should ideally be in greyscale, to prevent the mask colors and spritesheet colors from mixing into a new color entirely.

If you want multiple, independent colors per character (ie, Mario's hat and overalls are separate), then just create multiple masks, being careful not to overlap dark areas between them unless you want colors to mix. You could fit 4 into the RGBA channels of one image if you are concerned about memory.

---
Tags: unity, shaders, textures, palette
---


# Question
Title: How to create random seeds, randomly in gamemaker studio?
So, I'm working on a match-3 game similar to Ironcast (in concept, it's just seeing if I can). I've finally got the board to generate properly, and to place down random gems. Problem is, it's always generating the same placement, as though it were seeded (which it isn't, as far as I know).

Here's the code that directly generates the randomness (scr\_generate\_gem).

```
var insert = irandom_range(1, 4);//randomizing the gem inserted
var gem_insert;

        switch (insert)
        {
        case 1: gem_insert = obj_Food;
        break;
        case 2: gem_insert = obj_Fuel;
        break;
        case 3: gem_insert = obj_Parts;
        break;
        case 4: gem_insert = obj_Meds;
        break;
        default: gem_insert = obj_Parent;
        break;
        }

return gem_insert;

```

And here is where it's used.

```
//hardcoded height and width of the board. could change later
Large_Width = 6;
Large_Height = 6;

var i = Large_Width-1; //5, at the moment
var jreset = Large_Height-1; //5. Used to keep a reference to when j
//needs to be reset to maximum, so the board fills out.
var j = jreset;

repeat(Large_Width) //repeat 6 times; i goes from 5 to 0 through repeats
   {
    repeat(Large_Height) //repeat 6 times; j goes from 5 to 0 through repeats
    //ends up repeating this repeat 6 times, because of the above Repeat, making 36 in total
        {
        //initialize the board by generating the objects
        BoardGems[i, j]  = instance_create((i-1)*36, (j-1)*36, scr_generate_gem()); //creates an object, and places it here
        j -= 1;//decrement j so we aren't overwriting the last object created.
        }
    j = jreset;//resets j
    i -= 1;//decrements i to make a new column
   }

```

# Answer
Please read the documentation https://docs.yoyogames.com/source/dadiospice/002\_reference/maths/real%20valued%20functions/randomize.html

Game maker is really well documented. So you would do yourself a favor by starting to use it. You do not even need internett, it is already in GM. The hot key for it is f1.

When you use the randomize function game maker will start to make random seeds. The default is set to not generate random seeds to make it easier for bugtesting during development. I would recommend having the randomize function in a object all by itself that deletes itself after having run. This way it will not take up any space and will only run once.
> 1 votes

---
Tags: game-maker
---


# Question
Title: Learning OpenGL 3.3 on OpenGL 2.1 machine?
I am going to learn OpenGL 3.3 instead of OpenGL 2.1 because many model of OpenGL 2.1 is deprecated (base on this information). It's pity that my "old friend" only support OpenGL 2.1.

Base on this article at learnopengl.com I found that from OpenGL 2.1 to OpenGL 3.3 is a huge jump of Khronos Group and I will receive error if I run OpenGL 3.3 function on OpenGL 2.1 machine.

1) Is it possible to learn OpenGL 3.3 on OpenGL 2.1 machine?

2) Relate to this question 7 years ago, is learning OpenGL 2.1 useless today?

Thank you!

# Answer
**You absolutely can write code in modern OpenGL style while at the same time restricting yourself to OpenGL 2.1 (or lower) calls**.

All that you need to do is avoid using calls or features that are marked deprecated, which typically (for OpenGL 2.1) means using shaders and vertex buffers for all drawing.

That's OK because **shaders and vertex buffers are not modern OpenGL features**. They're actually very *old* features, with shaders being made core in OpenGL 2.0 (and available as extensions before then) and vertex buffers being even *older*, being made core in OpenGL 1.5 and likewise being available as extensions before then.

Other deprecated features you'll need to avoid include using the built-in matrix stack and built-in GLSL input uniforms and attributes, but that's also OK because even OpenGL 2.0 has always supported alternatives to them: use your own matrix library and provide your own uniforms and attributes.

So for example, the following is perfectly valid OpenGL 2.1 code:

```
glBindBuffer (...);
glEnableVertexAttribArray (...);
glVertexAttribPointer (...);
glUseProgram (...);
glUniformMatrix4fv (...);
glDrawArrays (...);

```

Some GL 3.0+ features you will (probably; they may be available as extensions) not be able to use include:

* Geometry shaders.
* Instancing.
* Uniform buffer objects.
* Sampler objects.
* Floating-point texture formats.
* Framebuffer objects.

This is also OK, because there's nothing about OpenGL 3.3 that *requires* you to use these.

---

As an alternative, software implementations do exist, but I would personally consider them unsuitable (on grounds of poor performance) for GameDev work.
> 2 votes

---
Tags: opengl
---


# Question
Title: How to enable CrossPlatformInput in Unity?
I'm new to Unity but not a complete programming novice.

I'm trying to use the `CrossPlatformInput` component from the "Car" prefab from Standard Assets.

I can't see it appear and when reading the notes file it says this:

> Importing the CrossPlatformInput package adds a menu item to Unity, "CrossPlatformInput", which allows you to enable or disable the CrossPlatformInput in the editor. You must enable the CrossPlatformInput in order to see the control rigs in the editor, and to start using Unity Remote to control your game.

So,

1. What is "a menu item" and where do I find it in the Unity UI?
2. How do I enable `CrossPlatformInput`? I have dragged the prefab called `DualTouchControls` into my scene but I can't see anything and I'm not sure how to link it to the actual car object.

# Answer
> What is "a menu item" and where do I find it in the Unity UI?

You know what the File and Edit menus are and where to find those, yes? The package contains an Editor script which adds a new menu item, like File or Edit, named "Mobile Input" to the menu bar. Use it like you would any other menu.

> How do I enable CrossPlatformInput?

I haven't used the package, but I imagine that the thing you need to do is...

> enable the CrossPlatformInput \[via the Mobile Input menu\] in order to see the control rigs in the editor, and to start using Unity Remote
> 1 votes

---
Tags: unity, input, touch
---


# Question
Title: A game that can balance itself over time?
So after reading some history and learning about how some countries were allowed to survive by stronger countries, just so that a power gap wouldn't exist. That being said, we can assume that if this power gap did exist, eventually the world will rebalance itself one way or another.

Would that be applicable in games? Can a game (for example, Overwatch or any MMORPG) balance itself over time whether the imbalances are a result of how the classes are built or even the population of people in every faction?

I thought about it a lot and I tried finding dissimilarities between my real world example and games.

* In games, you are allowed to have many identities. You can essentially have a character in every faction. In a game like OW you can pick any hero. You don't have a fixed identity that defines you like IRL so cloning the idea of a "Country/Nation" in real life to a game is nearly impossible as developers don't have power over how many characters/factions the player can have.
* Nations have finite resources. All MMOs I played have infinite resources which simply doesn't make sense compared to the real world. Finite resources is what makes nations great whether by smart utilization of said resources or conquering/invading other nations.

That being said, I still have a feeling that it's possible, one day, to have a game that can balance itself over time. But to achieve that, I believe we need to put many constraints on the gameplay to mimic real life constraints that "define" a nation.

What do you guys think? What would those constraints be?

# Answer
> 1 votes
I think the main issue here is the finite resources that you touched on. Currently basically all online games are based around infinite resources as you have said. However you asked if it was possible, to which I say, of course it is. It's just that no current game has done it.

Some Ideas and examples:

* As altskop alluded to in his answer, EVE online has something along these lines. It doesn't have finite resources, but it has built an economy of scarcity by adding risk and overhead to the collection of some resources. Basically in order to produce more of the better resources you need to risk a great deal (relative to an average single player, for the alliances it barely factors). This causes the finite resource to be *the right to gather* not the resource itself.
* You could design a game with true limited resources. There are some definite challenges present here, such as hoarding of resources and eventually exhausting the amount of players a world can support. It could be interesting to have that be the arc of the game. As players devour the worlds resources it becomes more inhospitable to newer and weaker players. Maybe some sort of "server start time" where you can only create characters on a "new server" with significant server turnover. That way everyone starts on even terms and the game itself becomes a rat race for resources. Such a game would balance itself via market forces until the planet collapses.

Either way someone decides to approach it, I'm confident in saying such a thing doesn't exist yet.

# Answer
> 0 votes
A game is not at all the same as a natural equilibrium of people's economic actions in an organized society, the difference in complexity between a game and real life isn't even comparable, and the decisions made for game characters and their environment are completely arbitrary.

Balancing really just comes down to testing, and more testing, and then even more testing, along with good intuition; the statistics and the variables you consider. We don't currently have any artificial intelligence which is capable of substituting the anticipation of new variables with the dexterity to properly execute balancing already known variables, and we won't have it for a long time to come either, at least not for 30-40 years with current technological projections.

Perhaps if the game is simple enough, but not for a large RPG.

# Answer
> -1 votes
I would take a good look at EVE Online. Out of all existing MMOs I think this is the only one that is really close to bring the concept to reality.

---
Tags: game-design
---


# Question
Title: What game mechanics work best on mobile phones?
I teach Swift 3 and Android Studio. My students are always asking why I'm not in the mobile market yet; frankly, I'm migrating my 88 games from flash into native mobile apps ... it takes time. My question is: What game mechanics are most successful in the mobile apps for a profitable endeavor? Puzzle sliders? PacMan-ish chases?

I know there are 7 different methods of input, but which provide fun entertaining games? I could use some advice.

# Answer
I do not have any actual data on this issue, but in my opinion, the most important factors are

* Very limited methods of input. There are a lot of popular games which only use sliding and tapping. Some games use only one (e.g. infinite runner games where the only action is jump on tap).
* Much shorter game sessions. Most people play mobile games to kill a few minutes (e.g. in public transport). This requires the game design to account for short playtime. Games also benefit from the ability to be paused and continued later.
* Small screens. Much less elements can be visible at the same time (this makes designing gameplay and UI more difficult (or at least different from PC) for e.g. strategy games, although there are some popular ones).

If you need some particular statistics on the popularity of genres or mechanics, you will probably need to do your own research (unless somebody here has this data to share). But more importantly, you need to account for the abovementioned limitations while designing the gameplay and UI. In your case, you should probably choose the games that already satisfy these constraints (or can be easily made to do so).
> 1 votes

---
Tags: game-mechanics, input, mobile
---


title: OpenGL float[][] not working?

text:
# Question
Title: OpenGL float[][] not working?
I have a float\[\]\[\] array in my terrainFragmentShader to load render the biomes, however the code simply does not work. No errors are being cast and when I remove the code `biomeMap[int(pass_textureCoordinates.x)][int(pass_textureCoordinates.y)]` by either deleting that section or manually setting it, it loads the appropriate texture.

```
vec4 textureColour = texture(backgroundTexture, pass_textureCoordinates);

float c = biomeMap[int(pass_textureCoordinates.x)][int(pass_textureCoordinates.y)];

if(c < 0)
    textureColour = texture(sandTexture, pass_textureCoordinates);
else if(c < 32)
    textureColour = texture(stoneTexture, pass_textureCoordinates);

```

All three textures load just fine and are rendered when not using this method and the biomes are being properly loaded and initialized.

Loading:

```
public void loadBiomes(float[][] biomeMap) {
    for(int x = 0; x < Terrain.VERTEX_COUNT; x++) {
        for(int y = 0; y < Terrain.VERTEX_COUNT; y++) {
            super.loadFloat(location_biomeMap[x][y], biomeMap[x][y]);
        }
    }
}

```

Initializing:

```
    location_biomeMap = new int[Terrain.VERTEX_COUNT][Terrain.VERTEX_COUNT];
    for(int x = 0; x < Terrain.VERTEX_COUNT; x++) {
        for(int y = 0; y < Terrain.VERTEX_COUNT; y++) {
            location_biomeMap[x][y] = super.getUniformLocation("biomeMap[" + x + "][" + y + "]");
        }
    }

```

And finally here is the entire terrainFragmentShader:

```
#version 400 core

in vec2 pass_textureCoordinates;
in vec3 surfaceNormal;
in vec3 toLightVector;
in vec3 toCameraVector;
in int biomeSize;

out vec4 out_Color;

uniform sampler2D backgroundTexture;
uniform sampler2D sandTexture;
uniform sampler2D stoneTexture;

uniform vec3 lightColour;
uniform float shineDamper;
uniform float reflectivity;

uniform float biomeMap[128][128];

uniform float offsetX;
uniform float offsetZ;

const int levels = 32;

void main(void){

    vec4 textureColour = texture(backgroundTexture, pass_textureCoordinates);

    float c = biomeMap[int(pass_textureCoordinates.x)][int(pass_textureCoordinates.y)];

    if(c < 0)
        textureColour = texture(sandTexture, pass_textureCoordinates);
    else if(c < 32)
        textureColour = texture(stoneTexture, pass_textureCoordinates);

    vec3 unitNormal = normalize(surfaceNormal);
    vec3 unitLightVector = normalize(toLightVector);

    float nDotl = dot(unitNormal,unitLightVector);
    float brightness = max(nDotl, 0.25);

    vec3 unitVectorToCamera = normalize(toCameraVector);
    vec3 lightDirection = -unitLightVector;
    vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);

    vec3 totalDiffuse = brightness * lightColour;

    out_Color = vec4(totalDiffuse,1.0) * textureColour;

}

```

Why isn't the biome not loading? Is it an issue in me not getting the appropriate `[x][y]` from the `pass_textureCoordinates`?

# Answer
> 3 votes
For multidimensional arrays in GLSL you need either one of two requirements:

* Support the extension GL\_ARB\_arrays\_of\_arrays or
* Use GLSL version 430 (in which the mentioned extension became core)

---
Tags: opengl
---


# Question
Title: How to make local keyboard input move only the local player, not everyone in networked multiplayer?
I am working on Unity Networking and following this Tanks Networking tutorial:

https://www.youtube.com/watch?v=V6wEvT6G92M

Problem is that the keyboard inputs move all the tanks in the scene. It is not detecting the local tank. And when I run the game all tanks shows the same movement but it is not giving any error. I have followed all steps in the tutorial and searched all solutions on the google. This step in Tutorial is at 11:48.

Implemented Code is:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.Networking;

public class TankController : NetworkBehaviour {

// Use this for initialization

[Header("Movement Variables")]
[SerializeField] float movementSpeed = 5.0f;
[SerializeField] float turnSpeed = 45.0f;

[Header("Camera Position Variables")]
[SerializeField] float cameraDistance = 16f;
[SerializeField] float cameraHeight = 16f;

Rigidbody localRigidBody;
Transform mainCamera;
Vector3 cameraOffset;

void Start () {
    if (!isLocalPlayer)
    {
        Destroy(this);
        return;
    }
        localRigidBody = GetComponent<Rigidbody>();
        cameraOffset = new Vector3(0f, cameraHeight, -cameraDistance);
        mainCamera = Camera.main.transform;
        MoveCamera();

}

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

        float turnAmount = CrossPlatformInputManager.GetAxis("HorizontalUI");
        float moveAmount = CrossPlatformInputManager.GetAxis("VerticalUI");

        Vector3 deltaTranslation = transform.position + transform.forward * movementSpeed * moveAmount * Time.deltaTime;
        localRigidBody.MovePosition(deltaTranslation);

        Quaternion deltaRotation = Quaternion.Euler(turnSpeed * new Vector3(0, turnAmount, 0) * Time.deltaTime);
        localRigidBody.MoveRotation(localRigidBody.rotation * deltaRotation);

        MoveCamera();

}

void MoveCamera() {
        mainCamera.position = transform.position;
        mainCamera.rotation = transform.rotation;
        mainCamera.Translate(cameraOffset);
        mainCamera.LookAt(transform);

}
}

```

I have also checked the auto create player in the spawn info as suggested in some solutions.

# Answer
Use the isLocalPlayer property, as you did in `Start()`. Use it wherever you want to keep things 'local':

```
void FixedUpdate () {

    if(this.isLocalPlayer)

        float turnAmount = CrossPlatformInputManager.GetAxis("HorizontalUI");
        float moveAmount = CrossPlatformInputManager.GetAxis("VerticalUI");

        Vector3 deltaTranslation = transform.position + transform.forward * movementSpeed * moveAmount * Time.deltaTime;
        localRigidBody.MovePosition(deltaTranslation);

        Quaternion deltaRotation = Quaternion.Euler(turnSpeed * new Vector3(0, turnAmount, 0) * Time.deltaTime);
        localRigidBody.MoveRotation(localRigidBody.rotation * deltaRotation);

        MoveCamera();

    }
}

```
> 1 votes

---
Tags: unity, unity-networking
---


# Question
Title: Sprite masking with multiple, non-equally dimensioned textures in XNA
I know this question's been asked many times before, but I can't seem to get sprite masking to work in XNA/Monogame no matter if I try the stencil method, or the shader method.

Considering I'm having partial luck with the shader method, I feel I'll have the most luck with this route. Though it's not consistently sampling the same region of the texture, nor is it sampling the sprite I want to, nor is it sampling 100% correctly since the rest of the sprites are being rendered with partial transparency; it's still further than I've gotten with stenciling.

However, even with regards to all the examples I've seen online, my problem is slightly different. Basically, my sprites are all unpacked from a file that contains a list of indexed sprites into into 2048x2048 square textures. The mask sprite also goes into this same list, so it could be part of the same texture as one of the character sprites at any arbitrary region. What this means is that the mask sprite does *not* have its own texture. This complicates things. Additionally, I want to be able to place the mask spot at any region of the main sprite, whether it's outside or inside the region, and get the cut I expect. Furthermore, the mask sprite need not be the same dimensions as the main sprite.

Thus I could have this, a 66x121px image file:

Being masked with this, a 45x45 image file:

And the result would be something like: the black triangle defines what gets masked out; anything white or outside of the mask region gets kept.

Once again, these sprites are within the region of (separate) 2048x2048 texture.

This is my relevant HLSL code:

```
sampler TexSampler : register(s0) = sampler_state { MinFilter = Point; MagFilter = Point; };
sampler PalSampler : register(s1) = sampler_state { MinFilter = Point; MagFilter = Point; };
sampler MaskSampler : register(s2) = sampler_state { addressU = Clamp; addressV = Clamp; };

uniform int PalTextureSize : register(c0);

uniform float2 palCoords;

uniform float3 add;
uniform float3 mult;
uniform bool invertAll;
uniform float colorbal;
uniform float src_alphamul;

float2 drawSpritePos;
float2 drawSpriteSize;
float2 maskSpritePos;
float2 maskSpriteSize;

// ... pallete application code...

//
// Applies a mask to an image. The parameter is the main texture coordinate.
//
void Mask(float2 texCoord, inout float4 color)
{
    // Where does the sprite get drawn?
    //float2 spriteStart = drawSpritePos + drawSpriteSize*texCoord;
    //float2 mappedCoord = (maskCoord * maskSpriteSize) + maskSpritePos;

    // Get the necessary values from each sampler
    //float alphaValue = tex2D(MaskSampler, texCoord * maskCoord).r; // this does something, not sure what though
    //color.a = alphaValue;
    float alphaValue = 0.0;
    if (any(tex2D(MaskSampler, texCoord).rgb)) // A MASK THAT LOOKS LIKE WHAT I WANT OMG
        alphaValue = 1.0;

    color *= alphaValue;
}

//
// Shader converting 8-bit indexed color to RGBA
//
float4 Main(float2 texCoord : TEXCOORD0, float2 maskCoord : TEXCOORD2) : COLOR0
{
    float4 color = NearestNeighbor(texCoord);
    PalFX(color);
    Mask(maskCoord * texCoord, color);
    return color;
}

technique ApplyPal
{
    pass Pass0
    {
        PixelShader = compile ps_3_0 Main();
    }
}

```

And this is my Draw() method in my Entity class:

```
    public virtual void Draw(SpriteBatch spriteBatch, Effect spriteEffect, Texture2D[] plTextures, GameTime gameTime)
    {
        Sprite plSprite = null;
        bool beginCalled = false;
        Collision clsn = currCollision;
        // Just TRY to draw in case someone tries to draw an invalid sprite or something
        try
        {
            plSprite = Sprites.Select((s) => s).Where(s => s.ID == Anim.CurrElem.SpriteID).First();
            var maskSprite = Sprites.Select((s) => s).Where(s => s.ID == new ID(54321, 0)).First();
            Texture2D p1Tex = plTextures[plSprite.TextureIndex];
            //spriteEffect.Parameters["src_alphamul"].SetValue(1.0F);
            spriteEffect.Parameters["colorbal"].SetValue(1.0F);
            spriteEffect.Parameters["mult"].SetValue(new Vector3(1.0F, 1.0F, 1.0F));
            textureRegion = plSprite.TextureRegion;

            int palIndex = plSprite.PaletteIndex;
            if (paletteRemappings.ContainsKey(palIndex))
                palIndex = paletteRemappings[palIndex];

            spriteEffect.Parameters["MaskSampler"].SetValue(plTextures[maskSprite.TextureIndex]);
            Vector2 maskPos = maskSprite.TextureRegion.Location.ToVector2() / maskSprite.TextureRegion.Size.ToVector2();

            if (palIndex > -1)
            {
                spriteBatch.Begin(effect: spriteEffect, samplerState: SamplerState.PointClamp, rasterizerState: RasterizerState.CullNone);
                beginCalled = true;
                foreach (var pass in spriteEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    spriteEffect.Parameters["palCoords"].SetValue(new Vector2((palIndex / 4) % 1024, (palIndex / 4) / 1024));
                    spriteBatch.Draw(p1Tex, Pos + new Vector2(0,StageHeight), textureRegion, Color.White, Anim.CurrElem.Rotation, plSprite.Axis, Scale * Anim.CurrElem.Scale * new Vector2(facing, 1), SpriteEffects.None, LayerDepth);
                    //spriteBatch.Draw(plTextures[maskSprite.TextureIndex], Pos + new Vector2(0,StageHeight), maskSprite.TextureRegion, Color.White, 0, maskSprite.Axis, Scale * new Vector2(facing, 1), SpriteEffects.None, LayerDepth);

                }
            }
            else
            {
                spriteBatch.Begin(samplerState: SamplerState.PointClamp, blendState: BlendState.NonPremultiplied, rasterizerState: RasterizerState.CullNone);
                beginCalled = true;
                spriteBatch.Draw(p1Tex, StagePos, plSprite.TextureRegion, Color.White, Anim.CurrElem.Rotation, plSprite.Axis, Scale * Anim.CurrElem.Scale * new Vector2(facing, 1), SpriteEffects.None, LayerDepth);
            }

            if (beginCalled)
            {
                spriteBatch.End();
                beginCalled = false;
            }
        }
        catch (Exception)
        {
            if (beginCalled)
                spriteBatch.End();
        }
    }

```

It'd hard for me to debug, though, since this is HLSL being translated into GLSL internally since this is an OpenGL MonoGame project in VS2017. I'm using NVidia's Nsight debugger which is awesome, but it doesn't help me much in the way of debugging since I have no idea what I'm doing.

I've been stuck on this problem for 36 straight hours, so any help would be greatly appreciated!

# Answer
> 0 votes
After much trial and error, I did it! Didn't have to use stencils, either (which didn't seem to work anyway).

Basically, using a non-indexed mask sprite, I have to pass in these parameters:

```
spriteEffect.Parameters["MaskSampler"].SetValue(plTextures[maskSprite.TextureIndex]);
spriteEffect.Parameters["drawSpritePos"].SetValue(plSprite.TextureRegion.Location.ToVector2());
spriteEffect.Parameters["maskSpritePos"].SetValue(maskSprite.TextureRegion.Location.ToVector2());
spriteEffect.Parameters["maskSpriteSize"].SetValue(maskSprite.TextureRegion.Size.ToVector2());

```

`drawspritePos` is the location in the player texture to start drawing from. `maskSpritePos` and `maskSpriteSize` are similar in that regards, but for the mask sprite texture.

The trickiest part was the shader, where the final mixing is done:

```
float4 Main(float2 texCoord : TEXCOORD0) : COLOR0
{
    // Return of the mask
    float2 texIndex = texCoord * 2048.0;
    float2 maskIndex = texIndex - drawSpritePos;
    float2 maskPixel = (maskSpritePos + maskIndex) / 2048.0;
    float4 mask = tex2D(MaskSampler, maskPixel);

    // Convert indexed to RGBA
    float4 color = NearestNeighbor(TexSampler, texCoord, normPalCoords);
    PalFX(color);

    // Within the mask texture region?
    if ((maskPixel*2048.0 - maskSpritePos).x < maskSpriteSize.x && (maskPixel*2048.0 - maskSpritePos).y < maskSpriteSize.y)
        color *= mask.a;

    return color;
}

```

The "2048" I need to make a constant, but where it comes from is the texture size I use for sprites since the sprites themselves are always contained in a region within a 2048x2048 textures.

The drawing is pretty simple. No need to draw the mask, only the sprite to be masked.

```
if (palIndex > -1)
{
    spriteBatch.Begin(effect: spriteEffect, samplerState: SamplerState.PointClamp, rasterizerState: RasterizerState.CullNone, depthStencilState: s2);
    beginCalled = true;
    spriteEffect.CurrentTechnique.Passes[0].Apply();
    palIndex = plSprite.PaletteIndex;
    if (paletteRemappings.ContainsKey(palIndex))
        palTexIndex = paletteRemappings[palIndex];
    else
        palTexIndex = Palettes[palIndex].StartIndex;

    // Divide by 4 because of RGBA
    spriteEffect.Parameters["normPalCoords"].SetValue(new Vector2((palTexIndex / 4) % 1024, ((palTexIndex) / 4.0F) / 1024.0F));
    spriteBatch.Draw(p1Tex, Pos + new Vector2(0,StageHeight), textureRegion, Color.White, Anim.CurrElem.Rotation, plSprite.Axis, Scale * Anim.CurrElem.Scale * new Vector2(facing, 1), SpriteEffects.None, LayerDepth);
}
// 24 or 32 bit sprite
else
{
    spriteBatch.Begin(samplerState: SamplerState.PointClamp, blendState: BlendState.NonPremultiplied, rasterizerState: RasterizerState.CullNone);
    beginCalled = true;
    spriteBatch.Draw(p1Tex, StagePos, plSprite.TextureRegion, Color.White, Anim.CurrElem.Rotation, plSprite.Axis, Scale * Anim.CurrElem.Scale * new Vector2(facing, 1), SpriteEffects.None, LayerDepth);
}

```

---
Tags: xna, shaders, hlsl, fragment-shader, masking
---


title: Pixelated shadows in Unity

text:
# Question
Title: Pixelated shadows in Unity
I have tried everything I can think of and all the solutions I could find on forums, but I haven't been able to fix this problem. I have a point light that is shining on several spheres which are casting shadows. The shadows work fine, but they are quite obviously pixelated. How do I get them to be smoother?

These are the settings that I took this screenshot with. I've tried tweaking most of the them, but it's possible I wasn't using the right combination to get the smoother shadows.

# Answer
> 3 votes
You're reaching the upper limits of the built in lights. The alternative is to create your own (rather complicated, it's a combination of shaders, materials and scripting) or find a replacement on the asset store (pretty simple, may be money involved). There are also post processing effects that can help a little at the cost of performance (take a look at Unity's Post Processing Stack as a starting point).

Unity lights are made for the general cases and they cover a vast majority of use cases, while still having great performance, supporting a large number of lights and producing fairly quality light effects and shadows. But they're not for every use case, if you have a higher standard of quality, you'll probably have to go beyond the built in lights/shadows.

---
Tags: unity, lighting, shadows
---


title: Keyboard input conflict in wall jump

text:
# Question
Title: Keyboard input conflict in wall jump
I'm trying to make a Megaman-style wall jump in my 2D platform game with JavaScript.

The character can do A,B,C motions when it sticks the wall:

My problem is that when I trying to jump off the wall(motion C), it goes to motion A or B first, C was not happened. I think the keyboard input was conflict but I have no idea how to handle it.

Here is my current code:

```
if(key['right'] && key['jump']) {//it doesn't work
    //jump off the wall
} else if(key['right']) {
    //leave the wall
} else if(key['left']) {
    //stick the wall
} else {//release all keys
    //falling down
}

```

Please, Any help would be appreciated.

# Answer
> 3 votes
Your actual way of handling this is a *frame perfect*, this mean that to actually go to the C state you have to press both right and jump at the same frame (which very hard). A solution could be to implement a **timer** and an additionnal **boolean**. You have one boolean isOnTheWall and when you press the key\['right'\], you start the timer. If after X time the key\['jump'\] has not been pressed you go to state B. If the jump button is pressed then you go to state C. Here is the pseudo code :

```
if(isOnTheWall && key['right']){
    time++;
    if(time > maxTime){
        time = 0;
        isOnTheWall = false;
        //leave the wall;
    }
    else if(key['jump']){
        time = 0;
        isOnTheWall = false;
        //jump off the wall
    }
    ...
}

```

Note that **time** could be replaced by **frames** depending on what you are trying to achieve.

**EDIT :** Here are two other examples of how it could have been achieved :

* You could check for the key\['jump'\] before the right key so that you don't have to have any timer at all. If your character is on the wall and you press jump (without pressing any direction), your character would automatically jump to the opposite side of the wall and then you could press any direction to adjust the jump. This is a common solution but the feeling is less intuitive and precise to my mind.
* You could check for the **distance** between the wall and your character instead of a timer. If the distance is lower than X, you can make still jump to the other direction. Using this method you won't have to wait for your character to leave the wall.

Anyways, I would still chose the first option which feels better when playing.

---
Tags: javascript, input, platformer
---


# Question
Title: Lightmaps from RTCW BSP file not being rendered correctly
I'm trying to recreate a Return To Castle Wolfenstein renderer using Direct3D 11, but I can't seem to be able to render the lightmaps as they should be. I have not found much information on the internet on how Quake3/RTCW lightmaps are actually created from the BSP files. Basically, the result is as below:

And this is how the result should be:

With the info taken from Q3 BSP file format, I extracted the lightmap x and y origin inside the lightmap data taken from the lightmap index lmindex, in the BSP file from lm\_start\[0\] and lm\_start and the width and height from lm\_size\[0\] and lm\_size. The problem seems to be in finding the lightmap texture coordinates, which I assumed were the same as the face textures. After each lightmap extracted, I assigned the lightmap index to the face index. A negative index indicates that no lightmap is associated to the face.

Here is the code I used to create lightmaps from the file:

```
bool XWorldMap::CreateLightmaps(ID3D11Device* pd3d, ID3D11DeviceContext*
pd3dDeviceContext)
{
    m_lightMaps.reserve(m_numFaces);

    for (int i = 0; i < m_numFaces; ++i)
    {
        ID3D11ShaderResourceView* pTexture = nullptr;
        int x = m_q3Faces[i].lmstart[0];
        int y = m_q3Faces[i].lmstart[1];
        int lightMapWidth = m_q3Faces[i].lmsize[0];
        int lightMapHeight = m_q3Faces[i].lmsize[1];
        int lightMapIndex = m_q3Faces[i].lmindex;
        m_q3Faces[i].lmindex = (lightMapIndex < 0) ? -1 : i;

        if (lightMapIndex < 0 || lightMapWidth == 0 || lightMapHeight == 0)
        {
            m_lightMaps.push_back(nullptr);
            continue;
        }

        std::vector<char> lightMapData;
        lightMapData.reserve(4*lightMapHeight*lightMapWidth);

        for (int j = y; j < y + lightMapHeight; ++j)
        {
            for (int k = x; k < x + lightMapWidth; ++k)
            {
                lightMapData.push_back(m_q3LightMaps[lightMapIndex].map[j][k][0]);
                lightMapData.push_back(m_q3LightMaps[lightMapIndex].map[j][k][1]);
                lightMapData.push_back(m_q3LightMaps[lightMapIndex].map[j][k][2]);
                lightMapData.push_back(255);
            }
        }

        if (!CreateTexture(pd3d, pd3dDeviceContext, lightMapData, lightMapHeight, lightMapWidth, &pTexture))
            return false;

        m_lightMaps.push_back(pTexture);
    }

    return true;
}

```

This is the code to create the lightmap textures:

```
bool CreateTexture(ID3D11Device* pd3d, ID3D11DeviceContext*
pd3dDeviceContext, std::vector<char> imgData, unsigned int height, unsigned
int width, ID3D11ShaderResourceView ** pTexture)
{
    HRESULT hr;
    ID3D11Texture2D *pTex2D = nullptr;
    D3D11_TEXTURE2D_DESC texDesc;
    memset(&texDesc, 0, sizeof(D3D11_TEXTURE2D_DESC));
    texDesc.Width = width;
    texDesc.Height = height;
    texDesc.MipLevels = texDesc.ArraySize = 1;
    texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.Usage = D3D11_USAGE_DYNAMIC;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    texDesc.MiscFlags = 0;

    hr = pd3d->CreateTexture2D(&texDesc, nullptr, &pTex2D);

    if (FAILED(hr))
       return false;

    D3D11_MAPPED_SUBRESOURCE  mappedTex;
    pd3dDeviceContext->Map(pTex2D, 0, D3D11_MAP_WRITE_DISCARD, 0,
    &mappedTex);

    UCHAR* pTexels = (UCHAR*)mappedTex.pData;
    int j = 0;
    for (UINT row = 0; row < texDesc.Height; row++)
    {
        UINT rowStart = row * mappedTex.RowPitch;
        for (UINT col = 0; col < texDesc.Width; col++)
        {
            UINT colStart = col * 4;
            pTexels[rowStart + colStart + 0] = imgData[j++];
            pTexels[rowStart + colStart + 1] = imgData[j++];
            pTexels[rowStart + colStart + 2] = imgData[j++];
            pTexels[rowStart + colStart + 3] = imgData[j++];
        }
    }

    pd3dDeviceContext->Unmap(pTex2D, D3D11CalcSubresource(0,0,1));

    D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
    memset(&srvDesc, 0, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC));
    srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MipLevels = 1;
    hr = pd3d->CreateShaderResourceView(pTex2D, &srvDesc, pTexture);

    if (FAILED(hr))
       return false;

    return true;
}

```

# Answer
> The problem seems to be in finding the lightmap texture coordinates, which I assumed were the same as the face textures.

They're not.

If we examine the RTCW source code, paying particular attention to the ParseTriSurf function, we see the code for loading lightmap texture coordinates is as follows:

```
    for ( j = 0 ; j < 2 ; j++ ) {
        tri->verts[i].st[j] = LittleFloat( verts[i].st[j] );
        tri->verts[i].lightmap[j] = LittleFloat( verts[i].lightmap[j] );
    }

```

And the drawVert\_t structure is:

```
typedef struct {
    vec3_t xyz;
    float st[2];
    float lightmap[2];
    vec3_t normal;
    byte color[4];
} drawVert_t;

```

Here, "st" is the standard OpenGL convention for diffuse texture coordinates (Direct3D typically uses "uv") so we can see that lightmap texture coordinates follow them in the struct.
> 2 votes

---
Tags: c++, lightmap, quake3, binary-space-partitioning
---


# Question
Title: Relational Databases vs XML vs public static finals: Pros and Cons
I'm working on a game (single player, metroidvania type, Java) and I'm torn as to how data should be stored. For example, monster stats, dialogues, flavor text for weapons, gear stats... there is all kinds of fixed data that needs to be loaded.

I've tried 3 ways of handling this:

1. Apache derby database
2. XML (or JSON or CSV) files
3. Java classes with a long list of "public static final" Strings/floats

Hands down I love #1 the most, but I wonder if it will affect performance. I hate #2 because it requires a lot more work to organize everything, plus I have to do encryption and remove said encryption when debugging. #3 works fine but feels... unprofessional or sloppy.

I want to hear from someone with experience, since I'm new at this, what are the pros/cons of each, and is there a "best way", for simple single player games?

# Answer
> 1 votes
1. This is definitely overkill. I'm going to liken this to drinking a glass of water out of 5 gallon bucket. Because I think unlike TomTom's answer, although apt, I'd like to get the point across that this is technically a valid and at times even the best solution, in the circumstance that you need to drink the entire 5 gallons. Lets suppose that based on you saying, you're making a "simple single player game" that that's something more like 3-5 oz of water, and a 5 gallon bucket although it will never spill or fail you, is hugely overkill.
2. **This is indeed the optimal solution** and you're approaching it wrong if you believe you need to encrypt this data (there's other ways to prevent theft) or are under fault of a misconception if you believe your data would be protected in this way (Because your actual application itself would need to store the encryption key, which most any hacker who could break into your compressed and ciphered binary configs and make changes should also be able to locate that encryption key)

If you're only trying to discourage cheating, then simply cipher the data and compress it with zlib or some other library that can help you with this. This would give you the non plaintext data that you're looking for, while still being secure enough that your basic, I'm here to play not hack player won't cheat. If you're concerned about your assets and resources being stolen, then write a good copyright and make sure it verbally covers all of the assets and implies no right to use your assets outside of the game.

As far as file format goes, I cannot recommend XML for this task. I always recommend to start with the simplest format possible, and proceed to move to different libraries in order of lowest complexity and forward, as there becomes a requirement for that feature. For example when I first start out I tend to save everything in CSVs. If I realize that I'm going to need to express some kind of relationship or inheritance or something, I switch to JSON or write my own parser for the task.

3. In this case I would not recommend that you do this. Basically you have the data (the files that you need to import variables from) and you have the model (the place where that data is actually maintained to be used by the entities). What you're suggesting essentially can be paraphrased to "Forget the data driven approach altogether, and configure each entity model in code". There's a few issues with this approach, although I would never say it's wrong to do in every case.

For example lets say that almost all of your entities behave really similarly and the constructor of your object only needs to take maybe 5-6 parameters to create a new type of enemy. In this situation the approach of not loading the data from an external source would be fine. Even if all of those functions that set up these entities, were in there own class called EntityFactory or something, this should be fine.

One issue with this approach however is usability. Now you not only have to change the configuration class every time you want to change anything about any entity, but you also have to recompile your game when you do so.

Another issue is scalability and maintainability. You make 100 entities in your game, well that's 100-200 configuration lines, not pleasant but you've been making your game for enough time by now to not mind the extra work in actually locating the line you want to change. But now you add a few levels and start making really minor changes to those entities. Well... Making multiple changes is going to be difficult. It's different when you have a 100 lines and know which one you need to find, but when actually balancing something you need to change 4-5 values in entirely different lines this becomes a pain, fast. Now just think about releasing an expansion. Now you have 2 configuration classes (3, 4?).

# Answer
> 2 votes
1: TOTAL overhead. Like driving a 40 ton truck to your weekly shopping for you and your spouse. Adds a lot of memory eating high end functionality into what is essentially a configuration file. If you consider that the best fit to store some small amount of data - you really need a reality check. Or have thousands of weapons.

3: you start hating it the moment you want to allow modding and / or go multi language.

2: isolate the encryption and add it in the final build step on the build server and you do NOT Have to deal with encryption during debugging. Slim, easy to extend. Easy to handle translations. I would likely call it standard as this is the way I have seen this handled for great many smaller games (i.e. non MMORPG style games).

---
Tags: java, data-structure, databases, xml, json
---


title: How is ball_pos calculated

text:
# Question
Title: How is ball_pos calculated
I'm new to game development and I'm trying to build my first Pong game on the Godot engine. the tutorial I'm following is given below.

Simple Pong Game

What I don't understand is the line:

```
ball_pos += direction * ball_speed * delta

```

**How is the new ball position being calculated?**

As far as I know, `delta` is the time elapsed in seconds (float) since the `last _process()` call.

**Also, why is the direction vector set to `(1.0, 0.0)`?**

I'm looking for a clear explanation since the tutorial doesn't explain much. Thank you.

# Answer
> 1 votes
The `+=` operator adds the right hand operand to the left hand operand. So the line is equivalent to

```
ball_pos = ball_pos + direction*ball_speed*delta

```

So `direction*ball_speed*delta` is the offset of the new position compared to the old position. It's the distance the ball travelled during this frame. `direction*ball_speed` is the speed of the ball combined with its direction, so it's a vector. Direction is a so called unit vector, so its length is one. This represents the velocity of the ball in `(some distance-unit)/second`. If you multiply this by the time that passed since the last update you have the change in position in this frame.

To learn more about this I recommend researching the basics of linear algebra.

# Answer
> 0 votes
Mostly assumptions based off what I've seen for similar variables and formulas, but `ball_pos` is probably a vector (so it has a `direction`, hence multiplying by `direction` to get it's direction). `ball_speed` is likely velocity, so you need to know how far it travels/elapsed time, and `delta` is likely the elapsed time between calculations.

That with the `+=` basically says where was I, what direction did I go in and how fast did I go over the previous time frame, now where did that get me to.

Direction is set to `(#, 0)` because presumably it's not an x, y, z direction but just x, basically is it facing left or right (or up and down depending on what movement you're looking for).

---
Tags: 2d, godot, pong
---


title: Why is alpha channel ignored in Texture

text:
# Question
Title: Why is alpha channel ignored in Texture
I am binding a texture to draw over some geometry (using the ImmediateModeRenderer20) but the alpha channel of the texture turns into colour black when drawn. Why is that happening?

My draw call loop looks sort of like this:

```
immediateModeRenderer20.begin(renderer.getUiCamera().combined, GL20.GL_TRIANGLE_STRIP);
immediateModeRenderer20.color(new Color(1, 1, 1, 1));
immediateModeRenderer20.texCoord(distance, tc.y);
immediateModeRenderer20.vertex(point.x, point.y, 0f);
immediateModeRenderer20.end();

```

# Answer
Make sure blending is enabled. Otherwise OpenGL will not blend between overlapping fragments.

```
glEnable(GL_BLEND);

```

Also you need to specify which factors are used for the blending calculation. This would be additive blending:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

After your `end()` function you should disable blending again, as it may not be wanted for other calls.

```
glDisable(GL_BLEND);

```
> 2 votes

---
Tags: libgdx
---


# Question
Title: Synchronizing object states over .NET sockets
What I want to achieve is synchronize the state of a list of objects between two applications using sockets. All my attempts, but failed.

One of my methods was to send each object each update to the client, which is clearly a bandwidth problem and I'm very limited to the amount of objects I can send since I send all the objects in one UDP packet.

It's clear to me that I need to send all the game objects to the client and then only update the fields as they change on the server side. The reason why I didn't try this approach from the beginning is because I identified a few barriers. My objects gets serialized and would like to synchronize every property.

1. How do I detect the change of a property without implementing a change event externally and for all the objects that inherited my main entity class.
2. Alot of the object's properties gets changed every frame so when I apply the changes to the clients representative object it requires alot of processing since I need to find each property which I need to change from the object and assign it the new value.
3. Each object has components which also needs synchronization. These components are within a list contained in each game object. So I must not only simple synchronize the object's properties, but the properties of each component as well.
4. A property can change multiple times each frame and I only want to synchronize the last value the property was set to at the end of the frame.

I currently I have no clue on how I can implement this method. My first method works, but it's not the optimal approach according to my understanding. Please any small hint or opinion can contribute to the formulation of the answer.

Thanks in advance.

# Answer
For what i can understand, i think you might could consider making a singelton factory that keeps your frame updates and the sends them over networking.

so in theory what you do is that you have a gameobject, lets call it GMOBJ. so when you change your property somewhere in the code, you register this to the frameUpdater.

frameUpdater.RegisterChange( GMOBJ, "scaling", value );

the string would be the identifier for the property, if you put this into a dictionary you could easily do that call several times and it would only store the lasted edited value. The string could also be a hashcode.

on every end of frame then you would do something like.

frameUpdater.SendChangedData();

and that function would then build a byte array of the data changed and send it to the other application.

that application would recive it and then deserialize it back to values and change the corresponding gameobject with propertys.

Something like this is what i think you want.
> 1 votes

# Answer
You almost certainly **do not** want to update **everything** **every single** frame.

Usually you would split data into Atomic events and Continuous events.

So things like a position change would be a Continuous event and do not need to be handled immediately. For example you could send the new position every X milliseconds and the client could interpolate between the old value and this new one in between.

Other events things will be atomic for example player death as this needs to happen immediately but these events will usually be more sparse and also hopefully lightweight than the continuous ones like movement animation etc.

You basically want the client to guess everything until it gets a server response, at which point it will 'fix' itself to the real values if it got the guessing wrong - this is the cause of 'glitching' and jumping about in multiplayer games, the client guessed and was wrong so the player is 'teleported' to match the real server value. If the latency is low and your prediction is good, you hope this doesn't happen (or little enough it is not noticable). But you usually don't need everything to be completely in sync at all times between client and server, just marry them up every so often and you save the majority of your bandwidth/performance.
> 1 votes

# Answer
I wrote an answer to a previous question about networking a multiplayer game here: How can I minimise data sent through a network in a modern FPS?.

To summarize - we started with a system that read every single replicated field on every object and sent it to the client. This was slow, but once we had that working we knew we had a solid baseline for optimizations.

Our next step was to keep track of every object that *appeared* to change - we essentially put a notification in each field's setter that marks the entire game object as dirty, and puts it in the head of a list of 'dirty objects this frame'. Only those objects would then have their replicated fields sent. This was a significant improvement.

Next we actually stored, on the server, a 'shadow copy' of the object's replicated fields. Every time the object was seen as dirty, we would compare each field with the previous shadowed value. If it differed, we would send it and copy the new value into the shadow copy. If it didn't differ we would skip it.

Finally, we compressed some of the data down so that we wouldn't send the fields as a UInt32, say, if the value could only ever be between 0 and 7.

I hope that gives you some ideas.
> 1 votes

---
Tags: c#, .net, socket
---


# Question
Title: What is a faster alternative to a GetComponent from a RaycastHit?
I have a basic AI car script which needs to interact with other cars around it. I would like to access variables from the other cars to help one car identify what the other cars are doing so they can avoid jams and crashes better.

One way to do this would be a raycasthit (ignore any errors there, you know what I mean):

```
if(Physics.Raycast(...))
{
    hitCar = hit.transform.gameObject.GetComponent<Car>();
}

```

However, I know that GetComponent can be very performance taxing especially if it's done every time there's an intersection with the raycast.

Another way would be to save all of the cars in an array or list before hand, and then test the name of it against all the names in the array or list.

```
if(Physics.Raycast(...))
{
    for(int i = 0; i < listOfCars.length; i++)
    {
        if(carName == listOfCars[i].name)
        {
            hitCar = listOfCars[i];
        }
    }
}

```

However, I've heard that string comparisons (again, especially if there's a lot of intersections with the raycast) can also be taxing on performance.

What's the best way to do this?

# Answer
> 6 votes
You could use a Dictionary. Store all Transforms as a key with reference to each Car.

In this example, we have a god Game class that holds references to all Cars. (just make sure your Script Execution Order has Game execute before Car does)

Each Car class adds itself to the Game's Car Dictionary upon Awake.

Then in your Raycast, you get the Car directly by using `hit.transform` as the key for the dictionary.

```
public class Game : MonoBehaviour
{
    public static Game Global;
    public Dictionary<Transform, Car> dict_transforms_cars = new Dictionary<Transform, Car>();

    void Awake ()
    {
        Game.Global = this;
    }
}

public class Car : MonoBehaviour
{
    void Awake ()
    {
        Game.Global.dict_transforms_cars.Add(transform, this);
    }
}

```

...

```
if(Physics.Raycast(...))
{
    hitCar = Game.Global.dict_transforms_cars[hit.transform];
}

```

But is this faster than using GetComponent? You would need test the timing.

---
Tags: unity, c#, performance, component-based, raycasting
---


title: Find third point in right triangle

text:
# Question
Title: Find third point in right triangle
I need to get position marked as green X. I have the helicopter's world position and the player's world position. I want X to always have an angle of 90 degrees. Player heading is ignored. How can I obtain the position X.

# Answer
> 0 votes
First we need to calculate rotation of vector from P to H. *(Here, V.y means y component of vector V, similarly for V.x)*

Next, we need to increment the angle found by 90 degrees. *(You can decrement by 90 degrees too, that will give you another point which is also correct.)*

Now we have the polar coordinates for the point T relative to P: (theta, r).

All we need to do is to convert this to Cartesian coordinates. *(Here, dot is multiplication)*

Now, we can calculate the cartesian position of the point T, and add over the position of P to make it relative to the origin (0,0).

---

**Footnote:** You may want to use `Atan2` in your code instead of `Atan` for finding arctangent.

# Answer
> 0 votes
If you're dealing with 2D positions, this is relatively straight forward, all you need to do is get the vector from the player to the helicopter (heliPos - playerPos) and then rotate it 90 degrees (Almost all libraries able to handle vectors should have rotation built in, but if you don't have access to one this can also be done via swapping the X and Y and negating either one, each negation option will give you one of the two 90 degree rotations).

Once you've done that, add the rotated vector to the player's position to get the third point of your triangle. If you need the third point to be a specific distance from the player, such as putting it on a circle around the player, you simply need to normalize the rotated vector and then multiply it by your desired length before adding it to the player position to get your world coordinate.

---
Tags: mathematics
---


# Question
Title: OpenGL 2D orthographic projection problem
I'm trying to use an orthographic projection to allow me to specify the dimensions and position of rendered objects using exact pixel coordinates (like in this tutorial: https://learnopengl.com/#!In-Practice/2D-Game/Rendering-Sprites)

So I have this vertex data, and I setup the ortho projection matrix like this:

```
glm::vec2 vertices[] = {
    // X, Y
    glm::vec2(0.0f, 1.0f),
    glm::vec2(1.0f, 0.0f),
    glm::vec2(0.0f, 0.0f),

    glm::vec2(0.0f, 1.0f),
    glm::vec2(1.0f, 1.0f),
    glm::vec2(1.0f, 0.0f),
};

glm::mat4 projection = glm::ortho(0.0f, 1024.0f, 768.0f, 0.0f, -1.0f, 1.0f);

```

and I set my shader's projection uniform to that value.

The problem is that I can't see any rendered objects if I use the projection matrix. I know that the rest of my program works, because I can see the rendered square if I remove the projection matrix from my shader:

```
gl_Position = model * view * vec4(position.xy, 0.0, 1.0);

```

Then the triangles are rendered as you would expect. But in the tutorial, they use integers to specify the exact size and position (in screen pixels) to render the object, which doesn't work without the orthographic projection matrix.

My full code is here: https://github.com/Oddity/basic-2D-opengl (sorry about the hand-made Python 2 build script)

# Answer
I believe you're multiplying in GLSL in the wrong order:

```
gl_Position = projection * LookAt * model * vec4(position.xy, 0.0, 1.0);

```

Remember that matrix multiplication is ***not*** a commutative operation.

I feel I should emphasize that the Projection matrix must be the **last** in the order of multiplication(**the order should be read in the reverse order**; i.e.: First comes the **model * vertex** multiplication, then the result is multiplied by the LookAt matrix, and the last one is the Projection matrix;).
> 3 votes

---
Tags: opengl, 2d
---


# Question
Title: Is there any way to get PVRTexTool's version from the command line?
I am to make an automated task which involves requiring the version of the PVRTexTool that comes with the Unity installed in a machine.

Is it possible to get the version of PVRTexTool on the command shell?

# Answer
> -1 votes
PVRTexTool as part of PowerVR Tool at Imagination website has command-line tools for Windows 32/64, Linux 32/64 and OSX 32.

https://community.imgtec.com/developers/powervr/tools/pvrtextool/

---
Tags: unity
---


# Question
Title: How can I make the background of my game move following my player?
I'm starting with Libgdx and I would like to make my ParallaxBackground move following my player. I am using a TiledMap along with Scene2d, and have the camera follow the sprite of my player. I'm basing my ParallaxBackground on the example of the following link:

Link here

Best regards

# Answer
Answering because you've not had any response yet. I don't have experience of doing parallax background but in the example you linked the speed of the background is hard coded, would you not just set the speed based on user input?

In your GameScreen you'd do something like

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    parallaxBackground.setSpeed(0); // reset to 0 to stop the background when no keys are pressed.
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
          // Set player speed x -1
          parallaxBackground.setSpeed(-1);
    }
    if( Gdx.input.isKeyPressed(Input.Keys.RIGHT) ) {
          // Set player speed x 1
          parallaxBackground.setSpeed(1);
    }
    stage.act();
    stage.draw();
}

```

Then in the constructor around this bit:

```
    parallaxBackground.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    parallaxBackground.setSpeed(1);
    stage.addActor(parallaxBackground);

```

Comment out that middle line and it should work.

You'll also need to move the

```
ParallaxBackground parallaxBackground

```

definition from the constructor and make it a field like so:

```
ParallaxBackground parallaxBackground;

public GameScreen(Game aGame) {
    game = aGame;
    // Other code removed for ease of reading
    parallaxBackground = new ParallaxBackground(textures);
}

```

I've tested this without a sprite and it seems to work. The only thing you might find if you're also moving the sprite is the player might feel too fast, in which case you might just reduce the sprite and parallax movement speed.

Hope that helps.
> 0 votes

# Answer
LibGDX provides a parallax test which shows you all you need to create a parallax background.

The core items are a Parallax camera:

```
class ParallaxCamera extends OrthographicCamera {
    Matrix4 parallaxView = new Matrix4();
    Matrix4 parallaxCombined = new Matrix4();
    Vector3 tmp = new Vector3();
    Vector3 tmp2 = new Vector3();

    public ParallaxCamera (float viewportWidth, float viewportHeight) {
        super(viewportWidth, viewportHeight);
    }

    public Matrix4 calculateParallaxMatrix (float parallaxX, float parallaxY) {
        update();
        tmp.set(position);
        tmp.x *= parallaxX;
        tmp.y *= parallaxY;

        parallaxView.setToLookAt(tmp, tmp2.set(tmp).add(direction), up);
        parallaxCombined.set(projection);
        Matrix4.mul(parallaxCombined.val, parallaxView.val);
        return parallaxCombined;
    }
}

```

and the drawing process:

```
    // background layer, no parallax, centered around origin
    batch.setProjectionMatrix(camera.calculateParallaxMatrix(0, 0));
    batch.disableBlending();
    batch.begin();
    batch.draw(layers[0], -(int)(layers[0].getRegionWidth() / 2), -(int)(layers[0].getRegionHeight() / 2));
    batch.end();
    batch.enableBlending();

    // midground layer, 0.5 parallax (move at half speed on x, full speed on y)
    // layer is 1024x320
    batch.setProjectionMatrix(camera.calculateParallaxMatrix(0.5f, 1));
    batch.begin();
    batch.draw(layers[1], -512, -160);
    batch.end();

    // foreground layer, 1.0 parallax (move at full speed)
    // layer is 2048x320
    batch.setProjectionMatrix(camera.calculateParallaxMatrix(1f, 1));
    batch.begin();
    for (int i = 0; i < 9; i++) {
        batch.draw(layers[2], i * layers[2].getRegionWidth() - 1024, -160);
    }
    batch.end();

```

This should be all you need to implement a parallax background
> 0 votes

---
Tags: libgdx, graphics, android-studio, parallax-scrolling
---


title: How to move Stage in LibGDX?

text:
# Question
Title: How to move Stage in LibGDX?
How to move Stage?

I am looking for an example:

```
stage.draw(x,y); // ???

```

Thanks you

# Answer
> 5 votes
You should not move the stage, you should move the viewport for the stage.

You need to make sure when you call this

```
stage.getViewport().update(width, height, false);

```

that the last parameter is false, so that the viewport is not always centered. You can then set

```
stage.getViewport().getCamera().position.x

```

or call

```
stage.getViewport().getCamera().translate()

```

before calling

```
stage.getViewport().getCamera().update()

```

# Answer
> 1 votes
if you really want to move all sprites on Stage, use root

My example (I use stages as windows and make transitions for window changes)

```
 private void startShowTransition(Stage stage) {
    stage.getRoot().setX(WINDOW_START_X);
    stage.getRoot().setY(WINDOW_START_Y);

    stage.addAction(Actions.moveTo(WINDOW_FINAL_X,
            WINDOW_FINAL_Y,
            WINDOW_TRANSITION_DURATION));
}

```

And note - you can use Actions for smooth stage changes effects!

---
Tags: libgdx
---