# Question
Title: Spherical fragment shader shockwave regardless of screen dimensions
I've been working on a shockwave shader based on some examples I've looked at. My primary issue is that the screen/resolution dictates the shape of the shockwave. I need it to be spherical, but with default screen shapes it's an oval.

I can resolve the issue by reverse the resolution ratio calc but that winds up stretching the actual texture.

https://www.shadertoy.com/view/XlfBWj

```
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
    float offset = (iTime- floor(iTime))/iTime;
    float CurrentTime = (iTime)*(offset);

    vec3 WaveParams = vec3(10.0, 0.8, 0.1 );

    vec2 center = vec2(0.5, 0.5);

    vec2 uv = fragCoord.xy / iResolution.xy;

    //float ratio = iResolution.y/iResolution.x;
    //WaveCentre.y *= ratio;
    //texCoord.y *= ratio;

    float dist = distance(uv, center);

    vec4 Color = texture(iChannel0, uv);

    if (dist <= CurrentTime + WaveParams.z &&
        dist >= CurrentTime - WaveParams.z) {
        //The pixel offset distance based on the input parameters
        float Diff = (dist - CurrentTime);
        float ScaleDiff = (1.0 - pow(abs(Diff * WaveParams.x), WaveParams.y));
        float DiffTime = (Diff  * ScaleDiff);

        //The direction of the distortion
        vec2 dir = normalize(uv - center);

        //Perform the distortion and reduce the effect over time
        uv += ((dir * DiffTime) / (CurrentTime * dist * 40.0));
        Color = texture(iChannel0, uv);

    }

    fragColor = Color;
}

```

# Answer
The uv coordinates always go from 0 to 1 on both axes regardless of the aspect ratio if you use this method. To solves this you need to make it act based on the resolution. What I usually do is the following:

If you want to make the y axis 1 unit long:

```
vec2 uv = fragCoord.xy / iResolution.yy;

```

If you want to make the x axis 1 unit long:

```
vec2 uv = fragCoord.xy / iResolution.xx;

```

If the canvas stays wide, then use the former method, and if the canvas stays high, then use the latter one.

If however A) you aren't sure, that the canvas keeps its aspect ratio or B) you don't know which side of the canvas is longer, then you need to use a more sophisticated method:

```
float maxSize = max(iResolution.x, iResolution.y);
vec2 uv = fragCoord / maxSize;

```
> 1 votes

# Answer
in your comments you mentioned need a way to use shader in unity so i convert it to unity.

```
//Converted by ShaderMan
//https://github.com/smkplus/ShaderMan
Shader"ShaderMan/Shockwave"{
Properties{
_MainTex("_MainTex", 2D) = "white"{}
[Toggle]_Enable("Enable",Float) = 1
_Scale("Sclae",Vector) = (1,1,1,1)
}
SubShader{
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
struct appdata{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
float _Enable;
float4 _Scale;
float _Movement;

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

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

fixed4 frag(v2f i) : SV_Target{

    // Sawtooth calc of time
    fixed offset = (_Time.y - floor(_Time.y)) / _Time.y;
    fixed time = _Time.y * offset;

    // Wave design params
    fixed3 waveParams = fixed3(10.0, 0.8, 0.1 );

    // Find coordinate, flexible to different resolutions
    fixed maxSize = max(1, 1);
    fixed2 uv = i.uv;
    fixed2 shockuv = i.uv;
    shockuv *=  _Scale;
    // Find center, flexible to different resolutions
    fixed2 center = 1 / maxSize / 2.;

    // Distance to the center
    fixed dist = distance(shockuv.xy, center);

    // Original color
    fixed4 c = tex2D(_MainTex, uv);

    // Limit to waves
    if (time > 0. && dist <= time + waveParams.z && dist >= time - waveParams.z && _Enable>0.0) {
        // The pixel offset distance based on the input parameters
        fixed diff = (dist - time);
        fixed diffPow = (1.0 - pow(abs(diff * waveParams.x), waveParams.y));
        fixed diffTime = (diff  * diffPow);

        // The direction of the distortion
        fixed2 dir = normalize(uv - center);

        // Perform the distortion and reduce the effect over time
        uv += ((dir * diffTime) / (time * dist * 80.0));

        // Grab color for the new coord
        c = tex2D(_MainTex, uv);

        // Optionally: Blow out the color for brighter-energy origin
        //c += (c * diffPow) / (time * dist * 40.0);
    }

    return  c;
}ENDCG
}
}
}

```
> 0 votes

---
Tags: shaders, glsl, fragment-shader
---


# Question
Title: Balance an RTS to make a unit twice as good
I am modifying an RTS game (Rise of Nations) and want to make a unit twice as good and expensive as it's previous version so the balance is unaffected.

When I try to do it, I assumed that if I doubled the attack and health it would live twice as long and deal twice as much damage per second giving a total of four times as much damage so instead went for 1.4 times of each.

When I tested this however the modified version could defeat two of the original with little trouble.

I assumed after the first original is killed the damage would be halved. How can I calculate this correctly?

# Answer
> 6 votes
Any unit against a certain type of unit with a particular DPS will have a specific TTK, or Time To Kill. You should balance your unit around that TTK, which is calculated as `T = H / D`, where T is the defending unit's TTK, H is the defending unit's health, and D is your attacker's DPS.

If you want this new unit to die at the same time as the other two, you must keep in mind that your new unit is "fighting itself", but split in two, which means that one of the attackers will die before the twice as good defender dies (because it has more health), and the attacker's DPS will drop in half after this point. This means that, assuming they deal the same DPS, **the defender must receive two thirds of its HP in damage before one of the attacker dies**, since then the other unit will be able to leash out the remaining third in the the attacker's TTK. This means the defender's TTK must be three times as good as its opponents', or assuming equal attacks, it must have three times as much HP.

But you want this unit's attack to be better than the original unit's attack as well, so we can't assume three clear, equivalent segments. Instead, we have two segments of different sizes. In the time it takes the new unit to kill one of the originals, **the remaining attacker and the damaged defender must have the same TTK**, or `(HX - Z) / D = H / DY`, where you may consider the constraint that X == Y, and Z is how much damage he needs to receive during the first segment in which it received damage from both attackers. You now know you need to balance your TTK around this. You also know your attacker's TTK should be equal to the "TTK" (more like Time To Weaken) of the first segment of the life of your defender. The TTK is the same now, but the attacker's DPS is doubled, so `Z / 2D = H / DY`. So, for X == Y, the equation is `Z / 2D = (HX - Z) / D = H / DX`. Since there are only two unknown values, namely Z and X, this equation can be easily solved. If we consider X != Y, then we would have to solve it on lambda, which means there would be more than one possible solution to thep roblem at hand, which means you could technically make the game faster or slower by increasing the DPS and decreasing its HP or the opposite, respectively.

# Answer
> 3 votes
> I am modifying an RTS game (Rise of Nations) and want to **make a unit twice as good** and expensive as it's previous version so the balance is unaffected.

Without context, this goal is meaningless.

In RTS games, typically you do not have units fight each other one-on-one; instead they fight in groups, and group dynamics tend to dominate.

For example; suppose you have two identical units fighting each other. On average, the outcome is a draw; they either kill each other off simultaneously, or one barely survives because they happened to get the first shot off.

> A vs. B -\> draw

What if we double one side, so that it's 1 vs. 2? Do we expect that the two sides lose one unit each, leaving the side with 2 units remaining with 1 unit?

> A vs. 2B -\> B?

No! Because while the single "A" unit is attacking a "B" unit, those two "B" units are simultaneously attacking the "A" unit. The "A" unit loses health at twice the rate, and so we're left with one "B" unit at half health, and the other at full health.

> A vs. 2B -\> 1.5B

That is, **by doubling the number of units, we've made one side 4 times as powerful**.

The key here is that all the units are fighting simultaneously, which is common when you have ranged units. For melee units it's different, as you often have large groups of units waiting at the back and not engaged. The way this affects relative strengths is described in Lanchester's Laws. You could, given a ratio of engaged units, estimate how an increase in unit strength affects the group outcome, using these formulae.

But RTS games are usually much more complex than this. A lot of factors affect combat, such as range, attack speed, movement speed, area-of-effect attacks, support powers like healing, and buffs/debuffs. Instead, you should focus on **testing and simulations**.

---
Tags: game-design, modding, rts, balance
---


title: Unity unable to change android icon

text:
# Question
Title: Unity unable to change android icon
Hi I've have spent the past few days googling how to do this and I'm making no progress. I have created a png image for each of the sized icon 36x36, 48x48, 72x72,96x96, 144x144 & 192x192. But when I load my app on any device the default icon apps. This is preventing me from uploading my game to the store as I don't want users to have a game with no icon.

Can anyone help get these icons to actually appear. I have tried different devices, uninstalling the app and reinstalling but still no luck. Do the images have to be a certain format, or any setting need selecting with in unity to make them compatible?

# Answer
Update Unity to the latest stable version. The case is that probably android changed how the icon is represented in the resources and manifest and your version of unity builds the wrong things.
> 0 votes

---
Tags: unity, android
---


# Question
Title: Unity Change Rotation of Animated Object at Runtime
So I made an animation, but sometimes i nedd to rotate the animation, but for some reason it isnt working. I can change the rotation of the object and then click play and it works perfectly like in the gif, but if I attempt to change the rotation on runtime nothing happens. Why?

# Answer
It's probably because the actual rotation is encoded into the animation itself, overriding your changes. You can try to make the animated object a child of an empty one and rotate the parent instead. This way your should get the expected result.
> 2 votes

---
Tags: unity, animation, rotation
---


# Question
Title: How can SDL tell what Xbox360 controller is what player?
I init my controllers like this:

```
if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 1)
    return;
SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);

int nJoysticks = SDL_NumJoysticks();
numGamepads = 0;
for (int i = 0; i < nJoysticks; i++)
    if (SDL_IsGameController(i))
        numGamepads++;

if (numGamepads > 0)
{
    for (int i = 0; i < numGamepads; i++)
    {
        SDL_GameController* pad = SDL_GameControllerOpen(i);
        if (SDL_GameControllerGetAttached(pad) == 1)
            joysticks.push_back(pad);
        else
            cout << "SDL_GetError() = " << SDL_GetError() << endl;
    }
    SDL_GameControllerEventState(SDL_ENABLE);
}

```

and I poll events like this:

```
SDL_Event sdl_Event;
while (SDL_PollEvent(&sdl_Event))
{
    switch (sdl_Event.type)
    {
    case SDL_CONTROLLERDEVICEADDED:
        cout << "DEVICEADDED cdevice.which = " << sdl_Event.cdevice.which << endl;
        break;
    case SDL_CONTROLLERBUTTONDOWN:
        cout << "BUTTONDOWN cdevice.which = "<< sdl_Event.cdevice.which << endl;
        HandleGamepadButtonsDown(sdl_Event);
        break;
    case SDL_CONTROLLERBUTTONUP:
        HandleGamepadButtonsUp(sdl_Event);
        break;
    case SDL_CONTROLLERAXISMOTION:
        HandleGamepadAxis(sdl_Event);
        break;
    case SDL_QUIT:
        _quit = true;
        break;
    default:
        break;
    }
}

```

With this I have currently two Xbox 360 controllers connected. On these pads there is a LED indicating if it is player 1, 2, 3, or 4.

When I run this my poll loop prints out this when I press a button on this controller:

When I hit a button on the controller with the player 2 LED it prints:

So that is wrong. How can I from inside the code find out what controller corresponds to the controller with the right LED light on?

Also, when I first start it then it prints:

So the controllers are 0 and 1 when I add them but 1 and 2 when I run the game.

# Answer
First of all, `cdevice` isn't safe to use on a `SDL_CONTROLLERBUTTONDOWN` event. It could contain whatever field of a `SDL_ControllerButtonEvent` happens to overlap the `which` field of the `SDL_ControllerDeviceEvent` structure in the union inside `SDL_Event`.

So the SDL docs are a little confusing on this, but here's what I could gather:

There are two different "instances" that are passed around from the game controller events. There are game controller instance IDs, which is used in the `SDL_CONTROLLERDEVICE*` events, and then there are joystick instance IDs, which are used for an example in the `SDL_CONTROLLERBUTTONDOWN` event.

Here's what the docs say about the `which` field for button events:

> Type: SDL\_JoystickID - Name: which - Description: the joystick instance id

and here's the same `which` parameter on a `SDL_ControllerDeviceEvent`:

> Type: Sint32 - Name: which - the joystick device index for the SDL\_CONTROLLERDEVICEADDED event or instance id for the SDL\_CONTROLLERDEVICEREMOVED or SDL\_CONTROLLERDEVICEREMAPPED event

The biggest (and pretty much only) giveaway here is the different types of the fields.

A game controller in SDL is a combination of multiple joystick instances or something, and this is why it all becomes quite confusing.

So here's what I do in my codebase to make sure the correct player instance receives the correct controller events (so that pressing a button on one controller doesn't make all players perform an action):

Since `SDL_CONTROLLERBUTTONDOWN` events have a joystick instance field, I compare the `which` field of the event to `SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller));`, where `controller` is a `SDL_GameController*` that's supposed to control the player.

I do keep track of the `which` value of the `SDL_CONTROLLERDEVICEADDED` event too inside my controller-wrapper class, so that I can properly handle `SDL_CONTROLLERDEVICEREMOVED` events.

So in conclusion, it's a little messy to get things going, but once you have your `bool DoesThisEventBelongToThisController(SDL_Event* event, SDL_GameController* controller);` function setup, you shouldn't have to worry about this anymore.
> 3 votes

---
Tags: c++, sdl, xbox-controller
---


# Question
Title: How can I get a reference to an actor that's already in a scene in Unreal?
I'd like to know if there is a way to get a reference to the instance of an Actor (written in c++) in the scene from a blueprint even if it's not in the scene, or at least without making a new one using that Actor as base class.

I know there's a method to get all the objects in the scene, but it wouldn't be that cool to iterate over each one of them, so i absolutely want to avoid something like this.

Basically, i have a class called ABoard, that inherits from an AActor where i got some methods to deal with the board itself. Also i have some blueprints that will show the MainMenu, and someother stuff, and what i want to do, is to call a method in the ABoard from one of these blueprints to be able to set up some stuff, like: "Play as single Player, whatever it is". But, i cannot do this because (of course) the blueprint does not have a reference to the object/instance in the scene i'm talking about.

Since i'm relatively new to Unreal Engine, i have no idea how to solve this kind of problem.

# Answer
If you cannot simply give the Blueprint that needs the actor a reference to that actor when *it* is constructed or invoked, then rather than *search* for the actor, you should simply save a reference to it (when you create it) someplace you can easily get to from the Blueprint.

You can create a property on some other well-known, accessible object to do this. Good candidates for this are a custom `UGameInstance` subclass or game state or perhaps a level Blueprint. Using a game instance, for example:

```
UCLASS(Blueprintable)
class UCustomGameInstance : UGameInstance {
...
public:
  UPROPERTY(BlueprintReadWrite)
  ABoard* MyBoard;
...
};

```

Once you create and hook up a custom game instance, you can recover it with the `GetGameInstance` node in Blueprints, cast it to your custom type, and then access the `MyBoard` property, allowing you to cache the board actor when you create it and refer to it later easily.

If you *must*, such as if the actor is hand-placed in the editor and you need to find *that* instance, Unreal does provide mechanisms to find objects at runtime, such as `TActorIterator` and various Blueprint-exposed helpers. Actors aren't indexed for efficient runtime lookup by name, however, so any such method will necessarily involve iterating linearly over at least some subset of the entire actor list until you find one with matching criteria. This is not very efficient; if you must find an object this way, you should try to perform such a lookup as infrequently as possible and cache the result in a property (as above) *anyway*. Or restructure so that you can spawn this actor at runtime for easy caching, possibly by placing a *proxy* actor instead and swapping that out with the real one during `BeginPlay` or similar.
> 4 votes

---
Tags: c++, unreal-4, blueprints
---


# Question
Title: Why when coloring a Light from green to red it's coloring only part of it in red?
I have in the Hierarchy a door with a script attached to it.

The script:

```
using UnityEngine;
using System.Collections;

public class DoorVert : MonoBehaviour {

    public float translateValue;
    public float easeTime;
    public OTween.EaseType ease;
    public float waitTime;
    public Light[] lt;
    public bool doorLocked = false;

    private Vector3 StartlocalPos;
    private Vector3 endlocalPos;

    private void Start(){
        StartlocalPos = transform.localPosition;
        gameObject.isStatic = false;

        if (doorLocked == true)
        {
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.red;
            }
        }
    }

    public void OpenDoor(){
        if (doorLocked == false)
        {
            OTween.ValueTo(gameObject, ease, 0.0f, -translateValue, easeTime, 0.0f, "StartOpen", "UpdateOpenDoor", "EndOpen");
            GetComponent<AudioSource>().Play();
        }
    }

    private void UpdateOpenDoor(float f){
        if (doorLocked == false)
        {
            Vector3 pos = transform.TransformDirection(new Vector3(0, 1, 0));
            transform.localPosition = StartlocalPos + pos * f;
        }

    }

    private void UpdateCloseDoor(float f){
        if (doorLocked == false)
        {
            Vector3 pos = transform.TransformDirection(new Vector3(0, -f, 0));
            transform.localPosition = endlocalPos - pos;
        }

    }

    private void EndOpen(){
        if (doorLocked == false)
        {
            endlocalPos = transform.localPosition;
            StartCoroutine(WaitToClose());
        }
    }

    private IEnumerator WaitToClose(){

        yield return new WaitForSeconds(waitTime);
        OTween.ValueTo( gameObject,ease,0.0f,translateValue,easeTime,0.0f,"StartClose","UpdateCloseDoor","EndClose");
        GetComponent<AudioSource>().Play();
    }
}

```

I added the doorLocked bool variable. And i want that when it's true and the door is on locked state to change the color of the two Point light 1 from green to red.

In the Start i did:

```
if (doorLocked == true)
            {
                for (int i = 0; i < lt.Length; i++)
                {
                    lt[i].color = Color.red;
                }
            }

```

When i'm running the game and doorLocked is false this is how it looks like: Both lights are green and i selected one of the Point light 1 and you can see in the inspector the Color is green:

Now this is a screenshot when the game is running and when lockedDoor is true. Now it should be red but it's only red around the Point light 1 the color seems to be still green:

Now i saw that in the Hierarchy one object above Point light 1 is called Light\_Small\_02 it's a child also of Light\_Small\_02:

I marked it here with a black circle.

And i think that i need also to change this Light\_Small\_02 color from green to red. Not sure since i can't find any green color with it in the inspector but when i disable the Light\_Small\_02 the green color is gone.

Anyway the main goal is to change the color of the two lights according to the door state: doorLocked true/false

This is a screenshot of Light\_Small\_02 inspector showing the mesh renderer part:

# Answer
> 2 votes
Two problems here:

1. A "Light" in a game scene is only an illumination, not a bright object itself. You'll see it via its effects on surrounding geometry, but it doesn't have a "bulb" or hot spot that you can see directly. The light seems to come from an invisible source.

So, when we want to represent real light sources in our games, there are two parts:

* The light component, to illuminate the surroundings.
    * A rendered visual to represent the source of the light. This could be a particle system representing the flames from a torch, or a flare component that draws a glare spot when we look toward the light's origin, or in this case, a bright spot on a mesh.

In your case, it looks like the two green squares are part of the same mesh & material that's rendering the rest of your hallway. This won't give you the flexibility to change the colour of just this pair of glowing panels, without affecting other parts of your scene.

You might want to replace these glowing squares with your own objects - say for example cubes or quads using an unlit shader and tinted to the green or red colour you want. Then you'll be able to address these elements individually, without wrestling with the rest of your corridor's rendering.

You may get good enough results by placing the new objects to cover the original glowing spots, or you might have to cut those spots out of the corridor texture / mesh to prevent interference.
2. Your lights are currently configured as "Baked," which means you're asking Unity to pre-compute their effect on the scene at edit time, using a high-quality light bouncing model, and use that pre-computed result at runtime. That won't work if you're changing the colour, intensity, or position of the lights during gameplay, so these should be marked "Realtime" instead.

You've currently disabled baking, which is masking the issue, hence the warning text under the "Baked" Mode setting. I recommend still marking these lights as Realtime, just in case you later decide to experiment with baked lighting on the rest of your scene, to ensure these lights don't cause unsightly bugs if you forget to change them at that time.

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


title: Blender Animations glitchy in Unity

text:
# Question
Title: Blender Animations glitchy in Unity
I have created a gorilla and its animations in Blender, exported the file as an FBX file and then imported it in Unity. The animations works fine in Blender, the loop is perfect for the walking animation. When I play the animations in Unity (in the animation preview and in game) it glitches at the moment where it loops, the arms make a really strange quick move. Is there anything special to do to export Blender animations ? Tell me if you need more informations.

Here is the link to my blender file, if you want to try exporting it and import it in Unity.

# Answer
***IMPORTING 3D MODELS WITH ANIMATIONS FROM BLENDER***

\[First of all, you import the 3d model, by dragging it into your project\]

1) Select the gorilla

2) go under the ***rig*** tab and set ***animation type*** from ***legacy*** to ***humanoid***

3) Unity by default doesn't know by default how you created your model, it can only make assumptions on how your gorilla's skeleton is configured. Beacuse of this we need to click on ***avatar definition*** and ***create from this model***

4)Once you configured your model's skeleton(it's pretty intuitive, you just have to click on a spot on the skeleton image and assign the corresponding bone transform to it), you should also check in the ***Animations*** tab if there are all the animation cycles you created for the gorilla. Sometimes you also have to specify the keyframes an animation starts and ends, but most of the times it should be all fine by default.

5)If you have done everything correctly, you should have the gorilla, with it's own configured avatar and animations ;)
> 1 votes

---
Tags: unity, animation, blender, fbx
---


# Question
Title: How to run Shader after Build without problems?
I always have problems with shaders, while my partners avoid using custom shaders because it always causes problems.

1. When I write shaders I have to test it in many devices and optimize every time. In addition to testing, each shader should be tested alone. We do not have enough time to test this way.
2. The result that can be seen in the engine is different from the built version.
3. In most cases it reduces speed; android phones are very weak and speed is important parameter for us.

We decide to drop custom shaders, but I don't like this decision because efforts are wasted.

So we have to use animated sprites instead of a custom shader but it isn't dynamic. I need way to bake the shaders before building the game.

One solution is pre-rendering my shaders; this means after finishing setting the shader details, generate a sprite sheet or store pixels from the shader. How can I do this?

But it's a ridiculous idea: why use sprites instead of shaders?

So how can I prevent this headache with shaders and have same result in game engine and output?

For example these shaders work on PC but doesn't work on mobile:

# Example 1:

https://www.shadertoy.com/view/4dSfDK

```
//Converted by ShaderMan
//https://github.com/smkplus/ShaderMan
Shader"ShaderMan/Space"{
Properties{
_iMouse("iMouse",Vector) = (1,1,1,1)
}
SubShader{
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata{
fixed4 vertex : POSITION;
fixed2 uv : TEXCOORD0;
};
fixed4 _iMouse;
sampler2D _MainTex;

struct v2f
{
fixed2 uv : TEXCOORD0;
fixed4 vertex : SV_POSITION;
fixed4 screenCoord : TEXCOORD1;
};

v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.screenCoord.xy = ComputeScreenPos(o.vertex);
return o;
}
#define M_PI 3.14
#define M_TWO_PI (2.0 * M_PI)

fixed rand(fixed2 n) {
return frac(sin(dot(n, fixed2(12.9898,12.1414))) * 83758.5453);
}

fixed noise(fixed2 n) {
const fixed2 d = fixed2(0.0, 1.0);
fixed2 b = floor(n);
fixed2 f = smoothstep(fixed2(0.0,0.0), fixed2(1.0,1.0), frac(n));
return lerp(lerp(rand(b), rand(b + d.yx), f.x), lerp(rand(b + d.xy), rand(b + d.yy), f.x), f.y);
}

fixed3 ramp(fixed t) {
return t <= .5 ? fixed3( 1. - t * 1.4, .2, 1.05 ) / t : fixed3( .3 * (1. - t) * 2., .2, 1.05 ) / t;
}
fixed2 polarMap(fixed2 uv, fixed shift, fixed inner) {
uv = fixed2(0.5,0.5) - uv;
fixed px = 1.0 - frac(atan2( uv.x,uv.y) / 6.28 + 0.25) + shift;
fixed py = (sqrt(uv.x * uv.x + uv.y * uv.y) * (1.0 + inner * 2.0) - inner) * 2.0;

return fixed2(px, py);
}
fixed fire(fixed2 n) {
return noise(n) + noise(n * 2.1) * .6 + noise(n * 5.4) * .42;
}

fixed shade(fixed2 uv, fixed t) {
uv.x += uv.y < .5 ? 23.0 + t * .035 : -11.0 + t * .03;
uv.y = abs(uv.y - .5);
uv.x *= 35.0;

fixed q = fire(uv - t * .013) / 2.0;
fixed2 r = fixed2(fire(uv + q / 2.0 + t - uv.x - uv.y), fire(uv + q - t));

return pow((r.y + r.y) * max(.0, uv.y) + .1, 4.0);
}

fixed3 color(fixed grad) {

grad =sqrt( grad);
fixed3 color = fixed3(1.0 / (pow(fixed3(0.5, 0.0, .1) + 2.61, fixed3(2.0,2.0,2.0))));
fixed3 color2 = color;
color = ramp(grad);
color /= (0.1+ max(fixed3(0,0,0)+_iMouse.x, color));
return color;

}

fixed4 frag(v2f i) : SV_Target{
fixed t = _Time.y;
fixed2 uv = i.uv;
fixed ff = 1.0 - uv.y;
fixed2 uv2 = uv;
uv2.y = 1.0 - uv2.y;
uv = polarMap(uv, 1.3, _iMouse.y);
uv2 = polarMap(uv2, 1.9, _iMouse.y);

fixed3 c1 = color(shade(uv, t)) * ff;
fixed3 c2 = color(shade(uv2, t)) * (1.0 - ff);
fixed3 col = c1+c2;
return  fixed4(col,1)*_iMouse.z;
}
ENDCG
}
}
Fallback "Sprites/Default"
}

```

# Example 2:

https://www.shadertoy.com/view/4ttGWM

```
//Converted by ShaderMan
//https://github.com/smkplus/ShaderMan
Shader"ShaderMan/Fire"{
SubShader{
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
struct appdata{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;

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

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

fixed rand(fixed2 n) {
    return frac(sin(cos(dot(n, fixed2(12.9898,12.1414)))) * 83758.5453);
}

fixed noise(fixed2 n) {
    const fixed2 d = fixed2(0.0, 1.0);
    fixed2 b = floor(n), f = smoothstep(fixed2(0.0,0.0), fixed2(1.0,1.0), frac(n));
    return lerp(lerp(rand(b), rand(b + d.yx), f.x), lerp(rand(b + d.xy), rand(b + d.yy), f.x), f.y);
}

fixed fbm(fixed2 n) {
    fixed total = 0.0, amplitude = 1.0;
    for (int i = 0; i <5; i++) {
        total += noise(n) * amplitude;
        n += n*1.7;
        amplitude *= 0.47;
    }
    return total;
}

fixed4 frag(v2f i) : SV_Target{

    const fixed3 c1 = fixed3(0.5, 0.0, 0.1);
    const fixed3 c2 = fixed3(0.9, 0.1, 0.0);
    const fixed3 c3 = fixed3(0.2, 0.1, 0.7);
    const fixed3 c4 = fixed3(1.0, 0.9, 0.1);
    const fixed3 c5 = fixed3(0.1,0.1,0.1);
    const fixed3 c6 = fixed3(0.9,0.9,0.9);

    fixed2 speed = fixed2(0.1, 0.9);
    fixed shift = 1.327+sin(_Time.y*2.0)/2.4;
    fixed alpha = 1.0;

    fixed dist = 3.5-sin(_Time.y*0.4)/1.89;

    fixed2 uv = i.uv;
    fixed2 p = uv.xy * dist / 1;
    p += sin(p.yx*4.0+fixed2(.2,-.3)*_Time.y)*0.04;
    p += sin(p.yx*8.0+fixed2(.6,+.1)*_Time.y)*0.01;

    p.x -= _Time.y/1.1;
    fixed q = fbm(p - _Time.y * 0.3+1.0*sin(_Time.y+0.5)/2.0);
    fixed qb = fbm(p - _Time.y * 0.4+0.1*cos(_Time.y)/2.0);
    fixed q2 = fbm(p - _Time.y * 0.44 - 5.0*cos(_Time.y)/2.0) - 6.0;
    fixed q3 = fbm(p - _Time.y * 0.9 - 10.0*cos(_Time.y)/15.0)-4.0;
    fixed q4 = fbm(p - _Time.y * 1.4 - 20.0*sin(_Time.y)/14.0)+2.0;
    q = (q + qb - .4 * q2 -2.0*q3  + .6*q4)/3.8;
    fixed2 r = fixed2(fbm(p + q /2.0 + _Time.y * speed.x - p.x - p.y), fbm(p + q - _Time.y * speed.y));
    fixed3 c = lerp(c1, c2, fbm(p + r)) + lerp(c3, c4, r.x) - lerp(c5, c6, r.y);
    fixed3 color = fixed3(1.0/(pow(c+1.61,fixed3(4.0,4.0,4.0))) * cos(shift * uv.y / 1));

    color=fixed3(1.0,.2,.05)/(pow((r.y+r.y)* max(.0,p.y)+0.1, 4.0));;
    color = color/(1.0+max(fixed3(0,0,0),color));
    return  fixed4(color.x, color.y, color.z, alpha);
}ENDCG
}
}
}

```

# Answer
As user1118321 says in their answer, we can often replace noise or complex functions with texture lookups and still get good results.

Here's an effect I built to try to mimic the first example in the question. It uses two samples into a noise texture, scrolling at different rates, to create chaotic patterns over time.

(The jump is just due to the short gif loop - the actual effect has a very long seamless looping period)

Texture samples aren't free either - particularly when they're based on a calculated coordinate which makes it harder to hide fetch latency - but if you can exchange heavy math loops for one or two texture samples it can be a net win. Profile it on your target hardware and see.

```
Shader "Unlit/GlowingRing"
{
    Properties
    {
        // Use an FBM noise texture here.
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

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

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

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

            sampler2D _MainTex;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                // Transform uvs so (0, 0) is in the center,
                // and we go out to 2.0 at the edges.
                // 1.0 will be the radius of the ring.
                o.uv = (v.uv - 0.5f) * 4.0f;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Convert to polar coordinates.
                float2 ringUV = float2(
                                  atan2(i.uv.y, i.uv.x)/(2.0f * 3.141592653589f),
                                  length(i.uv));

                // Compute our own sampling gradients, and correct
                // the wrap-around from -180 to 180.
                float4 grad = float4(ddx(ringUV), ddy(ringUV));
                grad.xz = frac(grad.xz + 0.5f) - 0.5f;

                // Compute signed distance from the ring at radius 1.
                // > 0 = outside, < 0 = inside.
                float signedDistance = ringUV.y - 1.0f;

                // Our base gradient will fall off away from this ring.
                float level = 1.01f - 1.5f * abs(signedDistance);

                // Flip the texture scrolling direction on the inside.
                float scroll = sign(signedDistance) * _Time.y;

                // Sample the two textures at dfferent scales,
                // moving at two different rates,
                // so they interfere in complex patterns.
                float2 ring1Scale = float2(7.0f, 0.7f);
                float2 ring2Scale = float2(5.0f, 0.7f);

                float2 ring1= ringUV * ring1Scale;
                ring1 -=  scroll * float2(0.11f, 0.31f);
                float2 ring2= ringUV * ring2Scale;
                ring2 -=  scroll * float2(-0.07f, 0.3f);

                float sample1 = tex2Dgrad(_MainTex, ring1, grad.xy * ring1Scale, grad.zw * ring1Scale).r;
                float sample2 = tex2Dgrad(_MainTex, ring2, grad.xy * ring2Scale, grad.zw * ring2Scale).r;

                // Interfere the two texture samples. (I couldn't decide if I liked
                // a sum or ridge noise better, so I used a blend of the two. ;)  )
                float delta = lerp(sample1 + sample2, 1.0f - abs(sample1 - sample2), 0.6f);

                // Squaring this offset enhances contrast between peaks & valleys.
                delta *= delta;

                // Offset our gradient by the texture interference value.
                level += lerp(0.5f, 0.05f, level) * delta;

                // Again multiplying to boost contrast, without flipping negatives.
                level = max(level, 0) * level;
                float level2 = level * level;
                return fixed4(level2 * level2 * level2, 0.85f * level2, level, 1);
            }
            ENDCG
        }
    }
}

```

It's also worth noting that ShaderToy isn't really meant to be an Asset Store gallery of shaders that you can just drop into your game. A lot of the work there has more in common with tech demos / demoscene creations, meant to push the limits of what we can do in WebGL when rendering one effect alone. It's great to browse for inspirations and to discover new techniques, but for incorporating effects into your game it's generally not safe to just cut & paste and expect it to work correctly/with good performance on all platforms. Instead, take the time to understand the important parts of the effect, and craft your own version that plays nicely with the rest of the rendering going on in your game. ;)
> 1 votes

# Answer
One thing that immediately stands out to me is the numerous expensive math functions that your shaders are using. Functions like `pow`, `sin`, `sqrt`, etc. are computationally expensive. You should avoid them when you can, and I see some opportunities to do so. For example, this line:

```
pow(fixed3(0.5, 0.0, .1) + 2.61, fixed3(2.0,2.0,2.0)

```

You're just squaring a value. You shouldn't call `pow` to do that. Just multiply it by itself. Multiplication is a single instruction whereas `pow` is many. You could do this:

```
fixed3 temp = fixed3(0.5, 0.0, 0.1) + 2.61;
result = temp * temp;

```

Likewise, this line:

```
return pow((r.y + r.y) * max(.0, uv.y) + .1, 4.0);

```

can be written as:

```
fixed temp = (r.y + r.y) * max(0.0, uv.y) + 0.1;
fixed tempSquared = temp * temp;
return tempSquared * tempSquared;

```

Functions like `sin` are periodic. You might be able to get away with a look-up table (texture). (Just be careful that indirect texture look-ups are also slow, so it might not be a win.)

Another thing that might help is passing in a texture of random noise rather than trying to calculate it on the GPU. You can use a smaller texture than the whole image, but index into it cleverly. For example, I've done this where there are a few tiles of random noise. The tiles are uploaded in a different order each frame and the orientation is switched by playing with the texture coordinates. This pushes most of the work to the build system so it can be faster at run time.

Your `ramp` function uses a conditional. On some architectures (particularly on mobile), conditionals are *really* slow. You could calculate both sections and use a step function with a `lerp` to choose between them.
> 1 votes

---
Tags: unity, 2d, android, shaders, fragment-shader
---


# Question
Title: Manipulating an animation towards a target object (ie. The hand and arm lean towards the target)
I am trying to make a boxing game just for fun (I dont expect the end product to be anything decent lol) . I have my boxers in the ring and they are animated quite well so far, with Idle, and punch Left and Right. They also rotate so they are always looking at each other.

What I want to do is give the punch some aim towards the head. I will give the punch a set amount which it can move from the standard animation and move the hand bone in the direction of the targets head object. But I don't know how to do this :S

So far i have used dragged the 3 animation files into Mecanim and coded it to do the animations when a button is pressed.

Is there a way to manipulate the animation in this way? (ie. actually make the arm reach towards the target object )

# Answer
As the comments suggest. The two parts of Unity made for this that I could find are Target Matching https://docs.unity3d.com/560/Documentation/Manual/TargetMatching.html / and Inverse Kinematics https://docs.unity3d.com/560/Documentation/Manual/InverseKinematics.html /// https://www.youtube.com/watch?time\_continue=117&v=GYfeALySSq8.

I also found a very basic "fake IK" solution that just uses the spine and was very easy to implement. But this only really works to get a character to point towards the target (eg. Aiming, or just watching it) , i dont think it would be too good for my punch the head target, which im trying now to make by using the other two things. But here is a very easy gun aiming solution for beginners: https://www.youtube.com/watch?v=6UgB7TMk3Bg
> 1 votes

---
Tags: unity, animation, mecanim
---


title: Drawing a 1 pixel thick line in Unity

text:
# Question
Title: Drawing a 1 pixel thick line in Unity
I'm trying to get a cross at the center of the screen (Two lines will do as well).

I have a 2048x2048 Texture which I have thrown into a canvas. Filtering is set to point. The image is set to be in the middle of the screen no matter the resolution. The image is set to 2048x2048 no matter the screen resolution which works as well.

However when I change the Screen Resolution I get results like the following, no matter what I do, the line refuses to stay at the same thickness. When I enable Bilinear filtering the lines constantly fade and thicken.

This is what I get when I use a 16x16 image:

EDIT: i tried using a black square and setting its width to 1 and height to 2048, and another one with width to 2048 and height to 1. The result i got is not what i expected:

Can someone help me to fix this please?

# Answer
Textures mapped onto the surfaces of 3D geometry were developed to represent, well, surface texture. This type of detail usually doesn't align precisely with the grid of screen pixels, due to varying object sizes, distances, orientations, and camera perspectives, so it doesn't include any built-in features to snap the sampled texels to screen pixels. In fact, we more frequently want the opposite, smooth blending that hides the effect of the screen grid (which can show up as aliasing).

But Unity gives us the tools to be pixel-perfect when we want to be. Here's two ways we can approach it:

1. Create a new UI Canvas. Leave it in the default Screen Space - Overlay mode
2. Check the Pixel Perfect checkbox and set the Canvas Scaler mode to "Constant Pixel Size"
3. Create two Panels as children of the canvas. Remove their sprite so they're just a flat colour of your choosing.
4. Set one to centered horizontally / stretched vertically with width 1, and the other to the opposite with height 1.

Or, if you prefer to render this on other geometry, you can use a shader that clips out everything but the center cross:

```
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0
#include "UnityCG.cginc"

void vert (
      float4 vertex : POSITION, // vertex position input
      out float4 outpos : SV_POSITION // clip space position output
    )
{
    outpos = UnityObjectToClipPos(vertex);
}

fixed4 frag (UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
{
    // Compute the pixel center of the screen.
    float2 center = _ScreenParams.xy/2.0f;

    // Keep only the first pixel on/beside the center in the positive direction.
    float2 onLine = (screenPos >= center) * (screenPos < (center + 1.0f));

    // Discard all other pixels.
    clip(max(onLine.x, onLine.y) - 0.5f);

    // Draw black. (Or the colour of your choice)
    return 0;
}
ENDCG

```

With both of these solutions, though I could verify that Unity was writing a crisp single-pixel-wide line into the buffer, I ended up seeing a fuzzy line in screenshots. It turned out to be Windows applying its scaling logic for high-resolution displays - it was forcing Unity to render at a lower-than-native scale and then upscale. Disabling that Windows feature let the lines come out crisp, as expected.
> 5 votes

# Answer
There are many ways to create cross-hairs and cross-hair-like effects in Unity. Here are just a few of them:

---

# 9-sliced image:

You don't need a 2kx2k pixel texture just for a cross-hair. In fact, that would be (very) bad practice. Instead, you can have Unity scale and tile a simple, very small texture, based on it's parts.

In the case of a single-pixel cross-hair, a 3x3 image is enough, through the process of **9-slicing**; there the image will be sliced in up to 9 different parts, and where each edge slice will be tiled or stretched to fit/fill a certain area.

---

# Normal image(s):

You don't need a 2kx2k texture. A 1-pixel image stretched across the screen will look like a 1-pixel line. Make two of them cross at the middle, and you have a 1-pixel cross-hair.

When dealing with UI, transformations, variations and combinations of small images are pretty much always better than monolithic textures.

---

# Vector-Graphics:

In engines that support this, or with the help of plugins, **vector-graphics** is often the best choice for screen-space UI, as it provides clean, crisp, graphics, which are easy to transform, maintain, extend, and can greatly simplify the process of making dynamic effects.

Unfortunately, very few game-engines support this out-of-the-box, and Unity is not one of them. Further unfortunately still, almost all plugins that provide this functionality do so through work-arounds, like transforming the vector-graphics into normal images, which, despite allowing the engine to "support vector-graphics", doesn't really maintain most of the advantages of vector-graphics.

---

# Scripted *Graphics-Library* rendering:

Most game engines allow (direct or indirect) access to their underlying *low-level Graphics-Library* (IE OpenGL, DirectX, Vulkan, etc), and it is trivial to draw simple cross-hairs through these libraries.

In Unity, this access is provided through the **GL class**.

Note: This is usually ***not*** recommended, because it's overkill and much harder to change/maintain than an image-based approach, specially since there is no difference if you do the image-based approach correctly.

---

# And many more...

These are just the main/most common few of many, many other methods... You're strongly advised to do some research on this, as many of the methods for creating cross-hairs also provide interesting starting-points and/or clues for more advanced graphics and effects.

---

# NOTE:

To get a pixel-perfect effect, you need a pixel-aligned approach, obviously. In Unity, for screen-space UI, that's as easy as marking the "pixel-perfect" checkbox in the canvas' inspector.
> 3 votes

---
Tags: unity, pixel
---


# Question
Title: Using a dissolve shader as well as the Standard shader
I'm applying a "burning" dissolve shader to an object which uses the Standard shader already. Because I need the Standard shader for better lighting, etc, I looked into how to use them "both" or how to extend the standard shader.

According to the Unity docs I can define which lighting mode I want to use in the `pragma` so I used `Standard`. That must not work the way I thought, because I see none of the lighting I do when using the standard shader directly.

I'm using the burning dissolve shader from Harry Alisavakis

```
Shader "Custom/BurnDissolve" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _SliceGuide("Slice Guide (RGB)", 2D) = "white" {}
        _SliceAmount("Slice Amount", Range(0.0, 1.0)) = 0

        _BurnSize("Burn Size", Range(0.0, 1.0)) = 0.15
        _BurnRamp("Burn Ramp (RGB)", 2D) = "white" {}
        _BurnColor("Burn Color", Color) = (1,1,1,1)

        _EmissionAmount("Emission amount", float) = 2.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200
        Cull Off
        CGPROGRAM
        #pragma surface surf Standard

        fixed4 _Color;
        sampler2D _MainTex;
        sampler2D _SliceGuide;
        sampler2D _BumpMap;
        sampler2D _BurnRamp;
        fixed4 _BurnColor;
        float _BurnSize;
        float _SliceAmount;
        float _EmissionAmount;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
            half test = tex2D(_SliceGuide, IN.uv_MainTex).rgb - _SliceAmount;
            clip(test);

            if (test < _BurnSize && _SliceAmount > 0) {
                o.Emission = tex2D(_BurnRamp, float2(test * (1 / _BurnSize), 0)) * _BurnColor * _EmissionAmount;
            }

            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Standard"
}

```

I also tried adding this as another subshader to a copy of the Standard shader source, but I wasn't able to get it working there. If I put it before the others, it works as if it was alone, if I put it after, the standard shader works like if it was alone.

I'm still new to shaders so I'm sure I'm misunderstanding this. How can I get the dissolve shader to apply as well the standard shader, without hopefully having to manually rewrite stuff.

# Answer
> 2 votes
Here's a version of your shader where I've added normal mapping and pulled the smoothness map from the albedo texture's alpha.

You can see it gives consistent lighting behaviour on my test model below. The Ethan in the middle is using the Standard shader, and the ones on either side are using the Dissolve shader below.

If there are other particular lighting features you need, reply and we can figure out how to add them.

```
Shader "Custom/Dissolve" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _BumpMap ("Normal Map", 2D) = "white" {}

        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0

        _SliceGuide ("Slice Guide", 2D) = "white" {}
        _SliceAmount ("Slice Amount", Range(0, 1)) = 0.0
        _BurnRamp ("Burn Ramp", 2D) = "white" {}
        _BurnSize ("Burn Size", Range(0, 1)) = 0.15
        _EmissionAmount ("Emission Amount", float) = 2.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard addshadow
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _BumpMap;
        sampler2D _SliceGuide;
        sampler2D _BurnRamp;

        struct Input {
            float2 uv_MainTex;
            float2 uv_BumpMap;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        half _SliceAmount;
        half _BurnSize;
        half _EmissionAmount;

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);

            half test = tex2D(_SliceGuide, IN.uv_MainTex).rgb - _SliceAmount;
            clip(test);

            // I skipped the _BurnColor here 'cause I was getting enough
            // colour from the BurnRamp texture already.
            if (test < _BurnSize && _SliceAmount > 0) {
                o.Emission = tex2D(_BurnRamp, float2(test * (1 / _BurnSize), 0)) * _EmissionAmount;
            }

            o.Albedo = c.rgb * _Color.rgb;
            // Apply normal mapping.
            o.Normal = UnpackNormal (tex2D (_BumpMap, IN.uv_BumpMap));

            o.Metallic = _Metallic;

            // My Albedo map has smoothness in its Alpha channel.
            o.Smoothness = _Glossiness * c.a;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

---
Tags: unity, shaders
---


title: Programming Action RPG Battle system

text:
# Question
Title: Programming Action RPG Battle system
My best goal atm is just make one 1vs1 battle with no animations more than something which makes me realize the attack is done.

I'm learning C and Xlib, and now I know how to put an image in a window in Xlib.

Yes, it's nothing, but it was my first goal, show images in a window, and then start to do things.

So now I'm starting to think how I will make the game.

Since I'm thinking how make a low quality battle 1vs1 with no more than the two sprites and a black background in a window, I'm focusing in the battle "system" to make a little base and see how things will go.

I think the way is this (Maybe you know a better one, but it's just what i was testing one day and it works):

The map has coords like X and Y, so the sprites or enemies or whatever is in the game, are occuping some X and Y.

Then to use an attack I will take the X and Y of the attacker, and move one of them depending on the direction the attacker is looking.

For example, I want attack with a melee skill. I'm looking at right, so I take my X coord and move the X one step (maybe copying it in a variable first). This will be done with something like X=X+1; or X+=1; So my Y coord still unchanged, but my X is one step to right, then it's like I moved to right, but I'm still in my position because are the coords who are moving, not me really.

Then I make a condition like if X and Y are equal to Xenemy and Yenemy then, do attack.

So the base is move my coords or someone coords and do the attack moving X and Y and testing if they are the same of the enemy.

The ranged attacks will be the same, but repeating the process depending on range until it's done or the range is out.

```
X++;
if (X and Y are equal to Xtarget Ytarget) then do attack;
else  X++ and try again until the range is out or attack is done;

```

But, my questions are:

How I should do to attack more than 1 enemy? I need test all the coords of all sprites while I do this, or there is a better way like a selectable target or something?

I should use the Window coords, and the pixmap coords (the images or sprites) and copy them to attack, or I should make a new map with different X and Y?

What I must have in mind for the future? I mean, how I should make all coordinates and be sure the method I'm using is not lacking something which I should realize?

I'm having a wrong start? I guess I'm wrong when I'm focusing on only one target.

I guess the ranged skills should have X and Y, move on the map, and affect whatever is in the X and Y. But I have no more idea than test all the possible targets every time the skill cords move.

There is a way to create a global target to test only one location and know if there is an attackable target?

BTW: I will appreciate some corrections on my english. I will remember it, so I will learn with your edits. I guess formatting is not needed and will be useless since there is no real code, but maybe you can do or add something to explain better what I'm trying to say.

I must say sorry for my bad english, I'm spanish and the english level here is shit. I've learned more playing wow on pirate servers than at the school and now reading programming docs.

If you know some books, info or questions I can look, please share it if they will be useful for me.

# Answer
Honestly, it seems to me like you have a lot to learn about programming in general. Its seems like you have mainly come up with solutions for the problems you are having, but they are very simple and naive solutions. Fortunately, it seems like you are on the right path, and working on games is (IMO) probably the best way to improve your programming skill. Additionally, it seems like the project you are starting with is just about the perfect project for you to be taking on, its not too ambitious, but its enough for you to gain valuable experience.

As for your questions:

> How I should do to attack more than 1 enemy? I need test all the coords of all sprites while I do this, or there is a better way like a selectable target or something?

Mainly this depends on what you want. Testing all enemy instances should be no problem. There are many ways to solve this problem though, you are basically talking about collision detection, which is a big topic with many solutions. Fortunately, in your case you have very simple requirements, so the simplest solution should be adequate for you. Keep your enemy structures in an array, then use a for loop to iterate through all instances and compare against the player's position + direction. You could store the player's direction as dir\_x and dir\_y, where facing upward could be dir\_x=0; dir\_y=-1; and then when you need to attack, you can compare:

if (enemy\[i\].x == player.x+player.dir\_x && enemy\[i\].y == player.y+player.dir\_y)

> I should use the Window coords, and the pixmap coords (the images or sprites) and copy them to attack, or I should make a new map with different X and Y?

I think it would be beneficial to you to separate the concept of an enemy position from that of its sprite. This was a mistake I commonly made when I was learning. You are working with a grid, so you can store that position and then to display your sprite, it could be something as simple as:

player.x*grid\_x, player.y*grid\_y

This can simplify your collision detection and anything else that depends on a position in your grid.

> What I must have in mind for the future? I mean, how I should make all coordinates and be sure the method I'm using is not lacking something which I should realize?

This all depends on your requirements. Having clear requirements from the beginning is very important, and don't underestimate the potential issues, don't make the mistake of thinking you don't need to worry about something because it will be easy to solve. For instance, menu navigation seems like something easy to handle, but if you start out building your game around a state machine, where each menu is a state and your gameplay is another state, then a lot of things become a lot easier. Also, think about how you are storing and allocating memory for all your game objects, make sure you don't paint yourself into a corner. Keep in mind what you will need later in the development process, will everything be constrained to a grid? if not then you will need to rethink how you represent your coordinates internally, and this could be difficult to change when you have a lot of code written already.

> I'm having a wrong start? I guess I'm wrong when I'm focusing on only one target.

I think you should be considering how it will work with multiple targets, but I don't think you have a wrong start. I think you are on the right track, but the language you are working with has features that will make things a lot easier for you (struct, arrays, for loops).

> I guess the ranged skills should have X and Y, move on the map, and affect whatever is in the X and Y. But I have no more idea than test all the possible targets every time the skill cords move.

You should think about how you want to represent "range" internally, and how you want it to work. For instance, can a ranged attack work at short range also? If so then you can have a player.range, and then loop through all positions between the player and the player's position + (player.dir\_x, player.dir\_y) * player.range

As for testing all targets each time something moves, that should be fine. It seems like you won't have that many targets to actually test, and this kind of test takes no time at all, its about the simplest form of collision detection.

> There is a way to create a global target to test only one location and know if there is an attackable target?

Basically, like I said just keep targets in an array and loop through them, in your case, this is a perfectly correct solution. However, if you are really concerned about performance, think more in terms or eliminating possible targets. If you can quickly decide "no, its impossible for this enemy to be attacked by the player, no need to check further", then you can skip checking. However, based on the kind of checking you will be doing, it will likely be faster to just actually do the check. But in the future, if your needs become more complicated, look into quad-trees.
> 2 votes

---
Tags: rpg, c
---


# Question
Title: Unity post-processing effect conflicts with UI Image blur shader
I'm unable to use a UI image blur effect when I'm also using a grayscale post-processing effect on my camera.

I activate the grayscale post-processing effect when the game is paused, which is also when I show my pause menu, which is a UI panel with a blur shader.

When the grayscale effect is enabled, the UI panel is invisible. It's there, because all my text/buttons show fine. It's just the portion the blur shader applies to, has become fully transparent.

When the grayscale effect is disabled, my panel shows fine, with the blur working as expected.

Here is the grayscale post-processing effect I'm using by Alan Zucconi. I have this on my Main Camera, and it is enabled when my game is paused.

Here is the blur shader I'm using by vinipc, modified from cician, whose blur shader is commonly used by Unity users.

I'm not sure why these would conflict. My guess is that somehow the blur effect is seeing empty/fully transparent colors and therefore is also transparent?

# Answer
Add `ZTest always` to your UI Blur shader this make it Always Top!!

> How should depth testing be performed. Default is LEqual (draw objects in from or at the distance as existing objects; hide objects behind them).

or

Add `ZWrite Off` to your ImageEffect shader

> Controls whether pixels from this object are written to the depth buffer (default is On). If you’re drawng solid objects, leave this on. If you’re drawing semitransparent effects, switch to ZWrite Off. For more details read below.

https://docs.unity3d.com/Manual/SL-CullAndDepth.html

---

One solution is using two cameras

1.Make secondary camera

2.On second camera, in Clear Flags set it to **Don't clear**

> From what I observe, many Unity users do not grasp the concept of using multiple Unity cameras on a single scene. “If I want to look from only one perspective, why do I need more than one camera?”. Saying that it makes perfect sense when more than one camera captures the scene from the same perspective makes it even more confusing. So why even bother? The reason is somewhat complex, but it’s really worth learning. It will help you create great visual effects, that are hard to accomplish with the use of only one camera, in an easy way. http://blog.theknightsofunity.com/using-multiple-unity-cameras-why-this-may-be-important/
>
> ---

One interesting thing :)

if you want filter Image Effect to specific objects you can do this:

1.Make secondary camera

2.On second camera, in Clear Flags set it to **Depth only**

3.Create new Layer and set it to some objects, then select camera and change culling mask.

I solve this problem and place in my Github you can download it from Here
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: How can I use allocators for different systems?
I am going over the memory architecture for my game and even though I know my memory budgets may not be final, I am at the point where I can start using them in a general sense. I know that I will need several allocators (for systems such as audio, rendering, etc) but I am unsure of how they will be accessed. I do not use singletons, so I can't just have something such as `AudioManager::GetInstance().get_allocator()`. Instead, I need to find a different method of usage but I am not sure of how.

How can I store and call my allocators needed for several different systems over engine in an efficient manner?

# Answer
> 2 votes
There are two ends of the spectrum here:

1. You can do the simple thing, and make the allocators globally-accessible things (free functions, global objects). In this case you rely on the discipline of the consumer to use the correct allocator for the subsystem in question, by calling the appropriate function or passing the appropriate allocation bucket enumeration, or whatever.
2. You can make the allocators instance objects, disabling the usual memory allocation functions (`malloc`, `new` et cetera), and require all allocations to route through one of these allocator instances. You then pass these instances around to anything that is permitted to allocate memory.

The first option is straightforward, and probably the most common. It does require some minor discipline to avoid, say, using the rendering allocator in the physics subsystem, but this is rarely going to be a challenge. It plays well with code where you can't change the interfaces that much, because you don't have to introduce new parameters to shuttle allocators around. It's easier to bind up with macros to automatically pass `__FILE__` and `__LINE__` for diagnostics. But these are global points-of-entry into the allocation subsystem, in the end, which can hurt you. Particularly where multithreading is concerned.

The second option is interesting in that it lets you *really strictly* control who can allocate, and when. It's arguably slightly easier to build stack allocation (allocations in a stack, not allocations on the C++ stack) paradigms around. There are "no globals," which regardless of how you feel about them can be an improvement in the ability to write safe concurrent code. But it can also be cumbersome. The Stingray engine took this approach to the extreme of mandating allocator instances be passed even to basic containers (equivalents of `std::vector`), which has knock-on implications for the default-constructibility of a lot of stuff and can be tedious to work with in practice, leading to some "temporary allocator" kludges that require more discipline to use correctly, without circumventing the rules about where and when you can allocate.

Practically speaking, you'll likely want to be closer to #1 than #2; even though the latter is interesting I think it's a little too rigid, at least when taking to the extreme where *literally everything* must have an allocator reference to construct.

---
Tags: c++, architecture, design-patterns, memory-efficiency
---


# Question
Title: Unity: How can I get realtime image capturing at ~60fps?
I am writing an application in Unity which will be required to capture an image from a camera every frame (at ~60fps), and send the resultant data to another service running locally.

The issue is, I am aware that capturing the rendered data from the camera can cause massive frame rate drops (as explained in this article) when using the `GetPixels()` method. The article explains that "GetPixels() blocks for ReadPixels() to complete" and "ReadPixels() blocks while flushing the GPU" which is why the GPU and CPU have to sync up, resulting in a lag.

I have produced a sample project with a script attached which simply outputs frames to a file as a PNG to replicate the functionality of the program I wish to create. I have done my best to implement what is described in the article, namely allowing the GPU to render a frame, then wait a few frames before calling `GetPixels()` so as not to cause the GPU and CPU to forcefully sync up. However, I really haven't made any progress with it. The project still plays at about 10-15fps.

How can I achieve a realtime capture of 60 frames per second in Unity?

```
using System;
using System.Collections;
using System.IO;
using UnityEngine;

namespace Assets
{
    public class MyClass: MonoBehaviour
    {
        private const float reportInterval = 0.5f;
        private int screenshotCount = 0;
        private const float maxElapsedSecond = 20;
        private string screenshotsDirectory = "UnityHeadlessRenderingScreenshots";
        public Camera camOV;
        public RenderTexture currentRT;
        private int frameCount = 0;
        private Texture2D resultantImage;

        public void Start()
        {
            camOV.forceIntoRenderTexture = true;
            if (Directory.Exists(screenshotsDirectory))
            {
                Directory.Delete(screenshotsDirectory, true);
            }
            if (!Application.isEditor)
            {
                Directory.CreateDirectory(screenshotsDirectory);
                camOV.targetTexture = currentRT;
            }
        }

        // Update is called once per frame
        public void Update()
        {
            //Taking Screenshots
            frameCount += 1;
            if (frameCount == 1)
            {
                TakeScreenShot();
            }
            else if (frameCount == 3)
            {
                ReadPixelsOut("SS_"+screenshotCount+".png");
            }

            if (frameCount >= 3)
            {
                frameCount = 0;
            }
        }

        public void TakeScreenShot()
        {
            screenshotCount += 1;
            RenderTexture.active = camOV.targetTexture;
            camOV.Render();
            resultantImage = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
            resultantImage.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);
            resultantImage.Apply();
        }

        private void ReadPixelsOut(string filename)
        {
            if (resultantImage != null)
            {
                resultantImage.GetPixels();
                RenderTexture.active = currentRT;

                byte[] bytes = resultantImage.EncodeToPNG();
                // save on disk
                var path = screenshotsDirectory + "/" + filename;
                File.WriteAllBytes(path, bytes);

                Destroy(resultantImage);
            }
        }
    }
}

```

The article implies that it is possible, but I haven't managed to get it to work.

Many thanks in advance for your help.

# Answer
> 1 votes
I've done something similar to this using compute shaders to convert a renderTarget to an array of Vector4s (or any other datatype).

I've never had any problems with performance. All the compute shader does is convert the texture into a buffer than can easily be read back.

```
#pragma kernel CSMain
Texture2D<float4> t;
RWStructuredBuffer<float4> pixels;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    float4 temp = t[id.xy];
    pixels[twoToOne(id.xy)] = temp;
}

```

twoToOne is just a simple 2D to 1D conversion. So yea. If you plugin your renderTarget to t, and pull pixels using getData, you get an array of usable pixel data cpu side.

# Answer
> 1 votes
I've seen something like this done with asynchronous PBO read backs. Since it's asynchronous, you don't have to worry about blocking:

> Conventional glReadPixels() blocks the pipeline and waits until all pixel data are transferred. Then, it returns control to the application. On the contrary, glReadPixels() with PBO can schedule asynchronous DMA transfer and returns immediately without stall. Therefore, the application (CPU) can execute other process right away, while transferring data with DMA by OpenGL (GPU).

---
Tags: unity, rendering, image, realtime
---


# Question
Title: unity webgl scale page on different sizes of internet browsers on pc or phone
unity only has a fixed resolution for building webgl. how can I make it changebale on users browser size change.

there are some tutorials on the internet that doesn't match. there is only

> > index.html unityloader.js gamename.json gamename.data.unityweb gamename.asm.memory.unityweb gamename.framework.unityweb gamename.asm.code.unityweb

how can I make multi res webgl output happen for unity?

# Answer
> 2 votes
change the HTML as documented here. You can choose either one of the defaults or create your own template.

According to those docs you create folder in `Assets` called `WebGLTemplates` and inside that create a new folder for your template like `BetterTemplate`. Inside that put an `index.html` file and any other images, css, JavaScript files you want included with your game.

The index.html could look something like this

```
<!DOCTYPE html>
<html lang="en-us">

  <head>
    <meta charset="utf-8">
    <title>%UNITY_WEB_NAME%</title>
    <style>
      body { margin: 0; }
      #gameContainer { width: 100vw; height: 100vh; }
      canvas { width: 100%; height: 100%; }
    </style>
    <script src="Build/UnityLoader.js"></script>
    <script>
    var gameInstance = UnityLoader.instantiate("gameContainer", "Build/dist.json");
    </script>
  </head>

  <body>
    <div id="gameContainer"></div>
  </body>

</html>

```

Then you pick Edit-\>Project Settings-\>Player from the menus and under the WebGL tab choose your template

Here's an example.

---
Tags: unity, html5, webgl
---


# Question
Title: Can I build cross platform executables with Unity?
If I create a C# console application in Monodevelop and build it I can run it by typing:

> ./executableName.exe

or using Wine. (I am using Ubuntu Linux)

I assume that this means that C# .exe files are cross-platform.

If so can I build a cross-platform Unity executable?

**UPDATE:**

Here is this program:

```
using System;

namespace MyConsoleApp
{
class MainClass
{
    public static void Main (string[] args)
    {
        Console.WriteLine ("This will run on Linux and Windows (I
think).");
    }
}
}

```

When I build it I get this:

I can either run this file (MyConsoleApp.exe) by double clicking it which will open it in Wine:

Or by typing ***./MyConsoleApp.exe*** :

This is why I think that C# programs are cross platform and wonder if I can build cross platform executables with Unity.

# Answer
First of all you seem very confused. There is no way to create an executable file that can run on different platforms. If you read about Wine on their website, you'll find this:

"Wine (originally an acronym for "Wine Is Not an Emulator") is a compatibility layer capable of running Windows applications on several POSIX-compliant operating systems, such as Linux, macOS, & BSD. Instead of simulating internal Windows logic like a virtual machine or emulator, Wine TRANSLATES Windows API calls into POSIX calls on-the-fly"

So what wine does is translating the Windows API into Posix calls.

"I assume the C# .exe files are cross platform" No, they aren't. That's why different operating systems have different types of executable:

* .exe Windows
* .dmg MacOs
* .deb .gz .tar LinuxOs

"If so can i build cross platform executables?" If you mean building a project in Unity and export it to different platforms then yes, you can. But you can't run natively an .exe file on an Os that is not Windows.
> 2 votes

# Answer
I think the actual answer you are looking for is "sort of ... in a way". The way that C# works is less like normal (native) executables that you would run on your Linux or windows machine, and more like Java. With normal executables, your compiler compiles the code and produces a native executable, and then your OS loads that executable and runs it. However, in C#, you compile to CLI (common language infrastructure) code, then your Common Language Runtime (mono on linux, .net on windows) loads that code, and compiles the parts that it needs while it is running (JIT compilation).

So the platform dependent parts are taken care of by either mono or .net when you run the executable. The reason you can run the executable in linux using ./myprog.exe instead of mono myprog.exe is because the linux kernel has a feature called misc-executables, which basically sees that you are running a c# program and instead of trying to load non-native code, it loads an interpreter program (mono or wine depending on you your system is configured).

So I say that it is "sort of" cross platform because the native code is still platform dependent. But a c# application is not native code, so it actually can't run directly on any system (it will not run on my computer because I have neither wine nor mono installed). However, as long as a good enough CLR (common language runtime) implementation exists on the system, it should work. So it is cross platform in the sense that it can run on any CLR platform (because the CLR what does the loading and executing, NOT the OS).

Additionally, don't be confused by the program's extension (.exe), this does not denote the type of the file. People often see .exe and assume that means its a windows executable (PE executable), but in this case that is not true, its a CLI executable. Under linux, the extension is basically meaningless, linux (almost) completely ignores it. Linux determines if a program is an executable or not based on the executable flag in the file attributes. Most Linux native executables (ELF executables) do not have any extension. I believe though that (depending on how your system is configured), linux's misc-executable system might use the extension to determine that wine or mono is needed to execute your C# application.
> 2 votes

---
Tags: unity, c#, windows, linux
---


# Question
Title: Is there a way to do local multiplayer on a combination of Windows/Ubuntu computers?
So far I've tried Bluetooth but it doesn't appear to work on either windows or Ubuntu (for this use-case; it can connect to printers fine). I've also looked up USB-bridge-cables, but from what I’ve read so far, they can't be used for this, either.

Since the game is a hobby-project, the solution can neither be expensive, nor require months of work. It's a turn-based game. Otherwise I wouldn't be asking but finding a different project after finding out neither Unity nor Unreal Engine can do this; currently, I'm using neither.

Is there a way to do local multiplayer on a combination of Windows/Ubuntu computers?

# Answer
> 1 votes
What language are you using? You said you are not using Unity or Unreal, are you using any engine or are you doing everything yourself? These details will be more important than the operating systems in question.

Also, please note that what you describe is not really local, since there is more than one machine involved. It might seem physically local, but from a programming point of view its the same as any network communication.

I have never worked with bluetooth, but I know on linux is difficult to work with (from a user perspective). You will probably make things a lot easier for yourself by just using sockets and TCP. Since you are on the same network, it should be quite fast, and for something turn based its even easier. Basically you need one player to host (start a server on some port) and the second player to connect to it. There isn't really anything game-specific about this, and the code will look very similar in windows and in linux, so OS choice isn't really a big factor. I would advise you to avoid developing a separate server, and just have one player as the host. In other cases this might make sense, but it seems an unnecessary complication in your case.

Search for simple TCP client/server examples in whatever your chosen language is. You will need to implement BOTH (client and server) into your game, server for host and client for second player. The code should be fairly simple and easy to follow.

# Answer
> -1 votes
you can use socket io and NodeJS server but for that you must have back end knowledge because you have to develop back end in nodeJS and it hardly take 10-15 days to create back end so it's a good Alternative and it's free to do.

---
Tags: multiplayer, windows, linux
---


# Question
Title: Make object follow another object while keeping the same distance from it
I want an object to follow another object just like the way it follows it when it's parented to it, but smoothly and only in the x and z axis.

Here's my code so far:

```
distanceX = player.position.x - transform.position.x;
distanceZ = player.position.z - transform.position.z;
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, transform.position.z), new Vector3(transform.position.x + distanceX, transform.position.y, transform.position.z + distanceZ), Time.deltaTime);

```

Now the problem is that it goes way too close to the player and ignores the current distance.

If you got any questions please don't hesitate to ask.

Thank you for your time!

Edit:

I'm not looking to make the object go to the target's position, just to follow it and keep the distance, just like it does when it's parented to that object, but smoother movements.

Edit 2:

Looks like I have made a mistake when I said that I wanted to keep the same distance between the two objects. What I actually meant was that I want the ***offset*** to be the same. I apologize to anyone who I confused or wasted their time! P.S. I'm still looking forward to finding a fix for my issue.

# Answer
> 3 votes
This can be done with a very small modification to the script in the question Philipp linked:

```
public class BlendFollower : MonoBehaviour
{
    public Transform leader;
    public float followSharpness = 0.1f;

    Vector3 _followOffset;

    void Start()
    {
        // Cache the initial offset at time of load/spawn:
        _followOffset = transform.position - leader.position;
    }

    void LateUpdate ()
    {
        // Apply that offset to get a target position.
        Vector3 targetPosition = leader.position + _followOffset;

        // Keep our y position unchanged.
        targetPosition.y = transform.position.y;

        // Smooth follow.
        transform.position += (targetPosition - transform.position) * followSharpness;
    }
}

```

Note that the rate of follow here is framerate-dependent, and using `Time.deltaTime` the way you have in your question won't correct for that (that particular use pattern only works for linear rates of motion, which is not what we have here)

If you have a very uneven framerate and want to improve consistency, the most robust solution is to move this to `FixedUpdate` and interpolate, but for purely visual effects this correction formula will suffice:

```
const float REFERENCE_FRAMERATE = 30f;

// Then, in LateUpdate()...
float timeRatio = Time.deltaTime * REFERENCE_FRAMERATE;
float adjustedSharpness = 1f - Mathf.Pow(1f - followSharpness, timeRatio);

transform.position += (targetPosition - transform.position) * adjustedSharpness;

```

# Answer
> 2 votes
Find the normal between the two then scale that normal by the distance wanted.

```
float distanceWanted = 3.0f;

Vector3 diff = transform.position - player.position;
diff.y = 0.0f; // ignore Y (as requested in question)
transform.position = player.position + diff.normalized * distanceWanted;

```

This will also keep the `y` of your following object to be exactly the same as `player.position`, you may want to add a vertical offset relative to the player:

```
transform.position = new Vector3(0.0f, verticalOffset, 0.0f) + player.position + diff.normalized * distanceWanted;

```

# Answer
> 0 votes
Try this:

```
calculate the angle between the player and the object on the X and Z axis
find the offset on the X and Z axis by using cosine and sine of the previous extabilished angle and multiplying them by the distance you want to keep
move the object to that offset

```

# Answer
> 0 votes
Set your object to the position of its parent, then translate it by the distance you desire by multiplying the orientation of the forward unit vector by the distance.

```
    transform.position + transform.forward * distance.

```

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


# Question
Title: Convert gl_FragCoord range to fragment range
I'm working with shaders so far, but I'm not sure how I can make my shader gl\_FragCoord relative to the window. To be more clear, this is what I have:

and this is what I'm looking to achieve no matter where I place the fragment on the screen:

As you can see, the shader take the whole window as the refference canvas insted of the fragment. I'm playing with ranges and division based on resolution and fragment size/position, but couldn't figure it out.

The second image was compiled based on hardcoded data, need to find a general solution..

EDIT: This is my vert & frag glsl code:

```
#version 330 core
layout(location = 0) in vec2 position;

void main() {
    vec2 fp = vec2(position.x, position.y);
    gl_Position = vec4(position.x, position.y, 0.0, 1.0 );
};

```

$

```
#version 330 core
layout(location = 0) out vec4 color;

void main() {
    vec2 pos = gl_FragCoord.xy/vec2(800., 600.);

    float r = 0.4 / 2.0;
    float c = smoothstep(r, r - 0.01, distance(pos, vec2(0.5)));

    color = vec4(vec3(c) * vec3(0.0, 0.5,1.0), 1.0);

};

```

# Answer
> 0 votes
Your resolution is undoubtedly not actually 800 by 600, as the following shadertoy program gives the output you desire, with the only change being the proper resolution is used to divide. You also don't need to pass in coordinates at all, look at this explanation of gl\_FragCoord

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

    float r = 0.4 / 2.0;
    float c = smoothstep(r, r - 0.01, distance(pos, vec2(0.5)));

    fragColor = vec4(vec3(c) * vec3(0.0, 0.5,1.0), 1.0);
}

```

Test it out here

EDIT:

You appear to be hinting that you are actually using 400 x 300 resolution, if that is the case, my answer is 100% correct, to fix your problem *divide by 400 and 300 instead of 800 and 600!*

so instead of

```
vec2 pos = gl_FragCoord.xy/vec2(800., 600.);

```

do this

```
vec2 pos = gl_FragCoord.xy/vec2(400., 300.);

```

Or if your resolution is different do this where resolution\_x and resolution\_y are the values for your *actual resolution*...

```
vec2 pos = gl_FragCoord.xy/vec2([resolution_x]., [resolution_y].);

```

If you want this to work with all resolutions *you will still need to pass the resolution to the shader*.

I recommend changing your shader to this and passing a resolution uniform in.

```
#version 330 core
layout(location = 0) out vec4 color;
uniform vec2 screenResolution

void main() {
    vec2 pos = gl_FragCoord.xy/screenResolution.xy;

    float r = 0.4 / 2.0;
    float c = smoothstep(r, r - 0.01, distance(pos, vec2(0.5)));

    color = vec4(vec3(c) * vec3(0.0, 0.5,1.0), 1.0);

};

```

# Answer
> 0 votes
We use the built-in `gl_FragCoord` value, which gives us the `(x, y)` coordinates (in pixels) of the current fragment in the frame buffer. We divide this by the resolution width and height (e.g. 800, 600) to get values between 0.0 and 1.0.

```
gl_FragCoord.xy / resolution.xy

```

Note that gl\_FragCoord value uses a lower left origin, so (32, 10) would mean 32 pixels to the right, 10 pixels up from the bottom. However, since our circle is symmetrical and located at center, we do not need to worry about this difference in our specific demo.

We subtract `(0.5, 0.5)` so that we can determine the length from center, rather than lower-left (the origin).

```
//determine center
vec2 position = (gl_FragCoord.xy / resolution.xy) - vec2(0.5);

```

We will use GLSL's built-in length() method to determine the length from the center point. Fragments at the center will have a length of zero (i.e. black), and it will increase as we move outward (i.e. into white/gray). We can test the shader so far:

```
//our screen resolution, set from Java whenever the display is resized
uniform vec2 resolution;

//"in" attributes from our vertex shader
varying vec4 vColor;

    void main() {

        //determine origin
        vec2 position = (gl_FragCoord.xy / resolution.xy) - vec2(0.5);

        //determine the vector length of the center position and using step function for drawing circle
        float circle = step(length(position),0.5);

        //show our length for debugging
        gl_FragColor = vec4( vec3(length), 1.0 );
    }

```

https://github.com/mattdesl/lwjgl-basics/wiki/ShaderLesson3

https://thebookofshaders.com/07/

---
Tags: mathematics, glsl
---


title: Developing for Unity without Editor

text:
# Question
Title: Developing for Unity without Editor
I want to write a Unity app that doesn't use the Editor. That's the goal. Please don't ask why or tell me the Editor "is really great, you should try it", I know all that, I love the Editor, I'd personally love to WORK on the Editor (at Unity). That's not how this particular project goes, however.

The goal is a 3D prototyping app. In the app, you make design changes to a set of 3D models, and the changes you make show up "live" in a Unity app. When you're done, you "bake" the changes into an actual Unity app, complete w/ the Unity project source code, so you can open it and further refine it. Sounds goofy, I know, I was assigned this project from somebody else.

I know that for the live changes shown in Unity, I could of course make a nearly blank Unity project, and add GameObjects at runtime, and set their attributes. That much is obvious.

What's not obvious is how to add C# script behaviors at runtime. If the Unity "live" app is running all the time, and I'm adding GameObjects at runtime, how then do I add *compiled* C# dlls at runtime, so the dynamically created GameObjects use the newly compiled C# code?

I'm thinking the GameObjects would call out to a C# dll by some kind of name-binding, each time the C# code is updated, the dll is written out with a GUID/hash, and in the GameObject code, it dynamically looks for that Dll and loads it, then steps into it. seems tricky and complicated, right?

Has anybody done this and had some insight into it? Before anybody references "Futile", keep in mind I don't care much about looking into a 2D only answer for this, and don't want to dig though that 2D code even if it has the answer in it. I'd like to discuss the answer here, on this forum, about thoughts about how to approach this, in the hopes it may help other people too.

Goals: 1. I provide 3rd party users a prototyping app that throws together an "editor" or a "prototyper" which shows on one winodw, with live in-Unity results in another window. Let's say the "prototyper" object in question is a GIANT terrain, populated with houses, trees, humans, etc. You can move around, see what the generated stuff looks like. Then, when you're happy with the look, you press "bake" and out pops a Unity project that you can go edit and flesh out. 2. I need the live Unity view to accept c# code (over some kind of communication mechanism) that will get compiled and run by the live view. Examples for why might be trees in the scene waving in the wind, running waterfalls, etc.

Thoughts?

# Answer
> 0 votes
To compile C# code, you may want to look into `Microsoft.CSharp.CSharpCodeProvider` but Unity doesn't normally reference the assembly that class is in, and it won't work on non-Windows systems. An alternative is `Mono.CSharp.Evaluator` but that doesn't allow creating new classes.

---
Tags: unity
---


title: Monogame drawing lines above map cells

text:
# Question
Title: Monogame drawing lines above map cells
I'm trying to draw 4 lines above map cells as cells access level using this code

```
VertexPositionColor[] collection = new VertexPositionColor[]
{
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[0].X, loc.Y + _cellPoints[0].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[0].X, loc.Y + _cellPoints[0].Y, 0f), color),

    new VertexPositionColor(new Vector3(loc.X + _cellPoints[1].X, loc.Y + _cellPoints[1].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[1].X, loc.Y + _cellPoints[1].Y, 0f), color),

    new VertexPositionColor(new Vector3(loc.X + _cellPoints[2].X, loc.Y + _cellPoints[2].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[2].X, loc.Y + _cellPoints[2].Y, 0f), color),

    new VertexPositionColor(new Vector3(loc.X + _cellPoints[3].X, loc.Y + _cellPoints[3].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[3].X, loc.Y + _cellPoints[3].Y, 0f), color),

};

_vertexBuffer = new VertexBuffer(_device, VertexPositionColor.VertexDeclaration, 8, BufferUsage.WriteOnly);
_vertexBuffer.SetData(collection);

Device.SetVertexBuffer(_vertexBuffer);
Device.DrawPrimitives(PrimitiveType.LineList, 0, 4);

```

but it gives on this error

> An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV\_Position0, COLOR0.

in

```
Device.DrawPrimitives(PrimitiveType.LineList, 0, 4);

```

# Answer
> 1 votes
As the error says, the vertex declaration for the stream is missing some attributes required by the current vertex shader that's bound. Your code, and the error, indicate that you're filling a vertex buffer with "position" and "color" elements. But the shader you're using -- which you don't document here -- wants more.

Find where you are setting the active shader and change it so that the two agree: either swap the shader with one that only needs position and color, modify the existing shader so it only needs position and color, or determine what the extra data is and supply it in the vertex data.

---
Tags: c#, monogame
---


title: DrawImage problem adjacent sprite?

text:
# Question
Title: DrawImage problem adjacent sprite?
**Context**

I'm building a 2D game from scratch in JS. I'm drawing the map by using rpgmxp tilesets for the moment just to have some resources :

Each tile is 32\*32 pixels. I'm using canvas API with `ctx.drawImage` method to display it :

```
ctx.drawImage(tile.tilesetImg, tile.sX, tile.sY, this.tile.w, this.tile.h, canvasX, canvasY, Engine.Camera.tile.w, Engine.Camera.tile.h);

```

I use different parameters for the image source size (`this.tile.w` & `this.tile.h`) and the image destination size (`Engine.Camera.tile.w`, `Engine.Camera.tile.h`).

This has the effect of scaling the game, like that each user have the same map exactly displayed (32 tiles * 24 tiles). The current tile aspect ratio distortion doesn't matter to me for the moment.

The result displayed to the player with a 4:3 ratio :

**Problem**

When I change window size if I don't keep the ratio 4:3 (because i display always 32 tiles * 24 tiles for the player) one of my tile types causes strange visual artifacts. This happens in chrome and firefox and probably all browsers.

It's strange because all the other tiles are drawn from the same method, but do not exhibit this behavior. This behavior only seems to occur when the ratio is very different from 4:3.

Here is an example of what I'm talking about.

There is some transparent lines which display the background at the right of each "bad" tile. Note this tile happens to be the first tile from the tileset (first image above).

The same thing happens if height alone is changed, except the line will appear on the bottom instead.

The thing which is again more strange is that if i change the tileset to draw a red line at the right of the first tile :

The transparent line is replaced by the red line when drawing the map :

From debugging (console.log), there doesn't apear to be any reason that tile source size would be 33px instead of 32px, but the artifacting effect makes it seem like this is the case.

**Question**

I appear to be using `drawImage` correctly by all accounts, so googled to see if this was a known problem. I was reading the w3 documentation when I found that : (especially the last note of part 12)

> Thus, scaling an image in parts or in whole will have the same effect. This does mean that when sprites coming from a single sprite sheet are to be scaled, adjacent images in the sprite sheet can interfere. This can be avoided by ensuring each sprite in the sheet is surrounded by a border of transparent black, or by copying sprites to be scaled into temporary canvas elements and drawing the scaled sprites from there.

Does this explain the problem ? Does any one know what the problem is more in detail ?

Thank you in advance, best regards.

# Answer
This is an unavoidable artifact of anti-aliasing. You have two options, both require a compromise. As seen in the example, the unfortunate reality is that some browsers don't handle disabled anti-aliasing as well as others.

# 1. Disable Anti-Aliasing

Disable anti-aliasing altogether. The compromise here is that the "smooth" look you get with anti-aliasing will change the perceived art style of your game.

This can be achieved in modern browsers with added CSS & JavaScript.

**CSS**

```
/* add this class to your canvas */
.disable-anti-aliasing {
  image-rendering: optimizeSpeed;
  image-rendering: -moz-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: -o-crisp-edges;
  image-rendering: optimize-contrast;
  -ms-interpolation-mode: nearest-neighbor;
}

```

**JavaScript**

```
// pass in the canvas' context to this function
function disableAntiAliasing(context) {
  // note: you must factor this into any other context.translate calls in the future
  context.translate(0.5, 0.5);
  context.webkitImageSmoothingEnabled = false;
  context.mozImageSmoothingEnabled = false;
  context.imageSmoothingEnabled = false;
}

```

# 2. Modify your assets

These artifacts occur when the canvas renderer samples neighbor pixels in the tileset. Since the tiles in your tileset have no padding around them, there will always be bleeding from these neighbors (with any sort of scale/rotation). If you add roughly 2 pixels in padding to your tilesets, you won't get such harsh bleeding.

As an added measure, you can offset the canvas by `0.5` pixels like in the JavaScript section of the first option. This throws off the anti-aliasing algorithm. As to why this is? Probably some sort of magic that only the graphics gods can explain.

The compromise here is that you are now spending more time editing all of your assets, but luckily some tileset editors can export with padding baked in.

```
function disableAntiAliasing(context) {
  // note: you must factor this into any other context.translate calls in the future
  context.translate(0.5, 0.5);
  context.webkitImageSmoothingEnabled = false;
  context.mozImageSmoothingEnabled = false;
  context.imageSmoothingEnabled = false;
}

function renderTile(ctx, tile, canvasX, canvasY, scale) {
  ctx.drawImage(
    tile.tilesetImg,
    tile.sX, tile.sY,
    tile.w, tile.h,
    canvasX * scale, canvasY * scale,
    tile.w * scale, tile.h * scale
  );
}

function render(time) {
  for (var i = 0; i < contexts.length; ++i) {
    var ctx = contexts[i];

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  }

  var offsetX = Math.cos(time / 6400) * 120;
  var offsetY = Math.sin(time / 6400) * 120;
  var scale = 0.5 + (Math.cos(time / 5000) + 1) * 0.5;

  for (var x = 0; x < 25; ++x) {
    for (var y = 0; y < 25; ++y) {
      var tile = tiles[(x + y * 16) % (12 * 16)];

      var canvasX = x * tile.w - offsetX;
      var canvasY = y * tile.h - offsetY;

      for (var i = 0; i < contexts.length; ++i) {
        renderTile(contexts[i], tile, canvasX, canvasY, scale);
      }
    }
  }

  requestAnimationFrame(render);
}

const contexts = [].slice.call(document.querySelectorAll('canvas'))
  .map(function(canvas) {
    return canvas.getContext('2d');
  });

disableAntiAliasing(contexts[1]);

var tiles = [];

for (var x = 0; x < 12; ++x) {
  for (var y = 0; y < 16; ++y) {
    tiles.push({
      tilesetImg: document.getElementById('tileset'),
      sX: x * 32,
      sY: y * 32,
      w: 32,
      h: 32
    });
  }
}

requestAnimationFrame(render);
```

```
img {
  display: none;
}

canvas {
  display: block;
  border: 1px solid black;
}

.disable-anti-aliasing {
  image-rendering: optimizeSpeed;
  image-rendering: -moz-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: -o-crisp-edges;
  image-rendering: optimize-contrast;
  -ms-interpolation-mode: nearest-neighbor;
}
```

```
<img id="tileset" src="https://i.stack.imgur.com/p8MLp.png">

<div>
  <strong> Regular </strong>
  <canvas width="600" height="600"></canvas>
</div>

<div>
  <strong> Anti Aliasing Disabled </strong>
  <canvas class="disable-anti-aliasing" width="600" height="600"></canvas>
</div>
```
> 1 votes

---
Tags: 2d, javascript, sprites, html5, html-canvas
---