title: Dual touch controls turning on one axis

text:
# Question
Title: Dual touch controls turning on one axis
I wanted a swift look around functionality to be put in the middle of a room and just look around.
So obviously I imported the standard assets and put the FPS controller in the middle and then dragged in the Dual touch controls and build it to android.
The problem is that it only rotates horizontally and not vertically. I tried playing around with the values a bit but nothing seems to be working.

# Answer
I don't know what exactly is the problem with the FPS character and why it works in windows and not in android but I tested the Rigid body FPS character and it worked in android.
> -1 votes

---
Tags: unity, assets
---


title: Shake a tree on chop

text:
# Question
Title: Shake a tree on chop
I have a top down RTS type of game where the player (God mode style) can click a tree to chop it. I'd like to shake the tree where the base of the tree (where the position marker is) moves the least and the top the most to simulate like it's being hit by an axe so it shows visual feedback. Any ideas on how to accomplish this? Not really sure where to start.

This would be in 3D.

# Answer
I don't know Shaderlab, however concept doesn't change.

* Use vertex painting to color the parts you want to move. You can do this in your modeling tool. In Blender.
* In your vertex shader use the color channels ( RGB ) of each vertex as how much to displace over time. Channel values should range from 0 to 1. You can just use the red channel (green and blue are cool too) or all channels to do some funky stuff. For example black ( value 0 ) means absolutely rigid. You probably want to apply that to your base. This part doesn't move. And the higher you go the more red it gets ( value 0 to 1.0 ) the shakier it is. Really depends on how you use these values to displace/animate your vertices.

Manual for vertex data in shader Scroll down for the color example

Alternatively you could use animations with bones or have the leafs separate and shake that in script. Not sure how performance heavy that is when you have plenty of trees. I don't know how your trees are setup and I'm not entirely sure how my solution scales to instancing either. If someone else can comment on that, that would be great.
> 1 votes

---
Tags: unity
---


# Question
Title: Does the size/distance of a single object affect performance?
I have a moon that I would like to place in the sky, which will likely be anywhere from 1000-5000 triangles.

Will I experience any performance degradation if I choose to place this sphere several million units away from the player, and increase its size several thousand times? Would this giant (but distant) moon have the same performance impact as the same sphere shrunken into a ball that can fit in the player's hand?

My question is intended to be platform-agnostic, but I am working within Unity.

# Answer
The smaller it is on screen, the faster it will draw as there is less to draw and (if used) mip-maps will reduce the texture bandwidth.

However, depending on the GPU the size of triangles can bog down the fill rate: some GPUs can only draw one triangle at a time per tile. It will draw multiple tiles at the same time but only one triangle per tile.

This means that in the worst case where triangles are 1 pixel in size the fill rate will be divided by the tile size (8x8 tile = slowed down to 1/64th of the GPU's potential fill rate)

While a desktop GPU can most likely handle it without slow downs it can easily become an issue on mobile GPUs where the cost of binning all those triangles into tiles is greater.

---

Since the moon is a plain sphere there's an easy trick to it: **Subdivide only the outline** and rotate a cube textures using the texture UVs instead of the geometry. **Leaving the geometry always facing the camera.**

You apply the rotation (or it's inverse) to the texture matrix instead of model matrix.

You can get the same visual quality with 1/10th the triangles.

Alternatively, even drawing a single quad and calculating the spherical UVs in the pixel shader can be more efficient than sorting out 5000 triangles despite the penalty incurred from the dependent texture reads.

* Create a high definition sphere (I started at 3842 triangles)
* Remove the back side
* Select most of the front and use your 3D software's triangle reduction tool.
* Remove some loop subdivisions we can't see (Selected in the image below).

We're now down to 356 triangles and kept the circumference well defined.
> 4 votes

# Answer
Not from a draw call perspective. Triangles are very efficient and lightweight, and 5000 is barely enough to notice by today's standards.

At those distances you'll have more problems with precision loss than triangle count. If you don't care about the back side, consider animating a 2d sprite to imitate rotation (called a billboard).
> 1 votes

# Answer
> If I choose to place this sphere several million units away from the player \[...\] same performance impact as the same sphere shrunken into a ball that can fit in the player's hand?

That makes no difference, it is the screenspace size that matters, if anything. The in-game size is inconsequential (well, not really, floating point math with both very near and very far things in the same scene can be a major problem, but that's irrelevant for the question).

Note that although a few thousand triangles are "nothing" in general, you will still want to use LOD to reduce the number of triangles if an object is small (which "size of player's hand" suggests, unless the hand fills the whole screen, which it usually doesn't). Vertex processing is massively parallel (assembly and rasterization has to be serial, but vertices are independent, there's no hindrance to running parallel), and no challenge to a modern GPU, but that's not the issue.

Drawing small objects with too high tesselation will cause fragment shader invocations to explode, and will put a lot of pressure on ROP. Now since ROP has been mentioned, it is exactly that one thing in GPUs that *doesn't* grow faster than Moore's Law. Which means that if there is a bottleneck in your drawing, it is almost certainly not ALU -- it is almost certainly ROP.

Is it a real problem insofar as it will cripple your game? I cannot tell, nobody can tell but you (you'd have to try). It is, however, in any case a very real problem from an architectural point of view.

There exist different approaches to hardware rendering, one of them rasterizing all triangles into fragments and then processing these massively in parallel, and the other common one using a tile-based approach where information is first collected and spatially organized in an attempt to minimize ROP and memory bandwidth (operations can happen in a tiny tile-sized piece of local memory which is then only copied to global memory once). The tile based approach may introduce additional constraints, but the most stringent one follows in the next paragraph.

Fragments are rendered in small (usually 2x2) groups, which is necessary because GPUs support gradients, and that's how they're generated. For every fragment that a triangle touches, the corresponding 2x2 group has to be processed, even if only one of the 4 samples (or none of them!) is finally saved. The smaller your triangles get, the higher the likelihood of rendering and discarding useless fragments becomes. As triangles approach (or pass below) the size of fragments, it gets worse and worse.
Again, that doesn't *necessarily* mean that your game's performance will suck. It just depends on how much fragment and ROP bound it already is. But you pay a rapidly increasing amount of resources for for something you can't see (on the contrary, you might indeed see aliasing, it might look *worse*).
So... if one can help it, this is something one tries to avoid.

This example illustrates the pretty much most desastrous case of too small triangles:

Of the shown 6 triangles, only one actually contributes to a pixel. Every other one touches (but does not affect in the end) at least two fragments, and all of them are in different 2x2 fragment blocks.
The red triangle touches all four 2x2 blocks although it doesn't contribute to any single pixel. It causes 16 fragment shader invocations for exactly zero effect. In total, the 6 triangles run 244 fragment shader invocations and 244 ROP operations for *one pixel* of output.

Compare that to a textured billboard, which will, ideally, run one fragment shader invocation and one ROP operation.

But worse, you cannot even consider this a high image quality, despite its huge cost. If the vertices of that one triangle which *does affect* a pixel move only so and so much, even only by rounding errors, you will have the pixel flickering on and off between frames ("temporal aliasing").
> 0 votes

---
Tags: performance
---


# Question
Title: data structure fails to instantiate GMS2
Error message: Data structure with index does not exist. at gml\_Object\_enemy\_actor\_Step\_0 (line 10) - hand\[i\] = ds\_stack\_push(deck);

Code snippit that is referenced in the error message:

```
if global.phase == 0
{
    //fill inital hand of cards
    if global.turn == 0 && hand[0] = noone
    {
        for (i=0; i<4; i++)
        {
            hand[i] = ds_stack_push(deck);
        }
    }
}

```

The code that creates the ds\_stack

```
/// @description hold the enemy player's outfit

scale = 0.25;

image_xscale = scale;
image_yscale = scale;

outfit = ds_stack_create();
hand = array_create(8,noone);
//hand[0] = noone;
draw = false;

//create a deck and fill it
deck = ds_stack_create();
fill_deck(deck);

```

The fill\_deck() function just adds usable numbers to the ds\_stack

```
//argument0 is the deck being passed to fill

var temp = ds_stack_create();

for (i=0; i<20; i++)
{
    var index = round(irandom(46));
    ds_stack_push(temp, index);
}

ds_stack_copy(argument0,temp);

```

# Answer
> 1 votes
> hand\[i\] = ds\_stack\_push(deck);

maybe you wanted `hand[i] = ds_stack_pop(deck);`?

And couple things...

```
//argument0 is the deck being passed to fill

var temp = ds_stack_create();

for (i=0; i<20; i++)
{
    var index = round(irandom(46));
    ds_stack_push(temp, index);
}

ds_stack_copy(argument0,temp);

```

don't forget to destroy `temp` data structure, otherwise you'll have a memory leak. And you can fill it without extra data structure:

```
var data = argument0;

for (var i=0; i<20; i++)
{
    var index = irandom(46);
    ds_stack_push(data, index);
}

```

And you don't need use `round()`, because `irandom` already is integer.

---
Tags: game-maker
---


# Question
Title: What is a good path-finding algorithm when a target is moving?
I've been looking for a path-finding algorithm for a moving target. If there are no obstacles in proximity Seek behaviour would be good. However, A\* or some other path-findings are needed when obstacles are on the way to the moving target.

The problem I'm facing now is that calculating a path using A\* seems not efficient for a moving target. so I want to know if there are some good or preferred ways to solve this problem.

The image below shows some basic background of the problem. The red arrow shows the direction my Seek behavior calculates. But I want the "Chaser" to take the green direction instead.

Thanks in advance.

# Answer
> 4 votes
You can switch between pursuit behaviour and A\* depending on case. If chaser can actually 'see' the target (without obstacles on the way), it uses pursuit (maybe its characteristics makes it evade obstacles), and when it dont see the target, it use A\* once to position where he thinks that target is (or last position where target was seen). When it reachs that position, it's up to you: It will continue trying to pursuit target (using A\* to random locals), or will move around randomly (A\* to random positions or wander behavior) or will stop and wait until it sees target again? :)

To 'seek' the target, you can use raycast.

---
Tags: path-finding
---


# Question
Title: How can I render a 2D image to my screen using Direct X 11?
I am trying to render an image to my window using Direct X but I don't really want a "3D" world as such, and I don't really want to set up all the vertex/index buffers as I won't need them. I am performing all of my calculations and operations using compute shaders which returns me an image. As the file io is quite a bottleneck, I am looking to just render the image directly to the screen to increase performance. My question is, how would I go about this using Direct X 11? I have looked at some examples already such as rastertek and other questions on SO but they are either over-complicating the matter, or they want a solution to font drawing etc.

At the moment I am able to produce a blank screen using the following code and the screen size is the size of the image retrieved from the GPU. I am looking to draw this entire image to my back buffer or some render target, and then display it.

```
void Application::Draw()
{
    float ClearColor[4] = { 0.5f, 0.125f, 0.3f, 1.0f };
    context->ClearRenderTargetView(_pRenderTargetView, ClearColor);

    // compute shader operations, retrieve image data from gpu
    // draw image to back buffer/render target then present

    swapChain->Present(0, 0);
}

```

---

From Why can't I write to my render targets?, I have tried the solution using

```
ID3D11Resource * backBufferResource;
_pRenderTargetView->GetResource(&backBufferResource);//backbuffer render target
context->CopyResource(backBufferResource, gpuResource);

```

This doesn't seem to throw any errors, but it doesn't change the output on the screen. It is mentioned that the back buffer must be the exact same format as the image we're trying to copy to it so this may be the issue. My swap chain desc is as follows

```
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = _WindowWidth;
sd.BufferDesc.Height = _WindowHeight;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//FORMAT DIFFERENT
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = _hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;

```

and my image format is

```
DXGI_FORMAT_R32G32B32A32_FLOAT

```

If I try to change the swap chain format it throws a memory access violation.

# Answer
> 1 votes
Changing my image format to match the swap chain's format seemed to do the trick!

`DXGI_FORMAT_R8G8B8A8_UNORM`

---
Tags: directx11
---


# Question
Title: How to remove gameObjects once they are out of screen
My game has a player that keeps running forward automatically.

Here is the code I'm using:

```
void Update()
{
    Vector3 position = Camera.main.WorldToViewportPoint(transform.position);

    if (position.x < 0 || position.x > 1 || position.y < 0 || position.y > 1)
    {
        OnBecameInvisible();
    }
}

void OnBecameInvisible()
{
    Destroy(gameObject);
}

```

With this solution I'm able to remove the objects behind me and the ones out of the screen. The problem is that it also removes the gameObjects far away (if I turn the camera everything gets removed).

Can anyone please tell me what I am doing wrong?

# Answer
there is a nice built in renderer is visible check that you can use. instead of checking against the position you can just check if it is visible by any scene cameras

In your case you can simply check if they are not visible and then call your OnBecameInvisible method.

```
if(!GetComponent<Renderer>().isVisible) {
    OnBecameInvisible();
}

```
> 2 votes

---
Tags: unity, 3d
---


# Question
Title: Moving lights or scene objects in Unity seems to cause a second point light to shrink or dim
Moving a Point Light in 2d space seems to be dimming lights around it. What is this and how can I solve it?

# Answer
I think your problem is caused by the rendering path you are currently using. In the forward rendering path there are only a limited amount of pixel lights allowed, where in deferred all of the lighting is done per-pixel. I recommend reading the references here: deferred and forward rendering. This will explain the issue that you were describing: In Forward Rendering, some number of brightest lights that affect each object are rendered in fully per-pixel lit mode. Then, up to 4 point lights are calculated per-vertex. The other lights are computed as Spherical Harmonics (SH), which is much faster but is only an approximation. Unfortunately, the deferred pipeline is not currently supported on mobile, so you will need to use forward and SH lighting for dynamic lighting. You may want to consider using a feature such as light probes in conjunction with light mapping to get better quality lighting at less cost if that is an option. Hope it helps
> 3 votes

---
Tags: unity, lighting
---


title: How do I climb up a ledge

text:
# Question
Title: How do I climb up a ledge
I am currently working on a 3D game in unity. I want my player to be able to grab a ledge, and climb up on it. Please I will like to inform you that I am new to this, so a basic and easy to follow example will be nice. thanks

# Answer
> 1 votes
There are loads of ways to do this, i assume you are using Inverse Kinematics for your player. I know a series of videos on youtube that explains the whole process on how to make a climbing system from schratch here is the link this playlist is really good, i learned a lot of things from this guy ;)

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


# Question
Title: How to detect collision occurring on a child object, from a parent script?
I have an enemy with this structure:

* Enemy
    + Body
        - Head
        - Arm Left
        - Arm right

...and so on. I also have a collider for each part of the body.

In my "Enemy" object I've attached a script, and in that script I would like to intercept possible collisions (from a bullet) hitting the body, head, arm, left etc.

How can I to do this?

# Answer
> 29 votes
If you're using a Rigidbody with the character, you can get this out of the box. :)

So your hierarchy could look like this:

* **Character** (has Rigidbody and control script)
    + **child** (maybe has colliders)
        - **grandchild** (maybe has colliders)

OnCollisionEnter messages will fire on the GameObject containing the Rigidbody, reaching your parent control script without needing to write an extra relay script to stick on each collider.

If you need to find out which of your child colliders was involved in the collision, you can do it like so:

```
void OnCollisionEnter(Collision collision) {
    Collider myCollider = collision.GetContact(0).thisCollider;
    // Now do whatever you need with myCollider.
    // (If multiple colliders were involved in the collision,
    // you can find them all by iterating through the contacts)
}

```

# Answer
> 10 votes
One way to solve this would be to have two scripts: one for the Enemy object and another one for the child(that you need to assign to the children of the Enemy obj)

***Parent script***

```
using UnityEngine;

 public class ParentScript : MonoBehaviour
 {
     public void CollisionDetected(ChildScript childScript)
     {
         Debug.Log("child collided");
     }
 }

```

***Child script***

```
using UnityEngine;

public class ChildScript : MonoBehaviour
{
     void OnCollisionEnter(Collision collision)
     {
         transform.parent.GetComponent<ParentScript>().CollisionDetected(this);
     }
 }

```

This way you should get notified whenever a collision occurs to a child

# Answer
> 3 votes
Direct quote from Unity Answers (written by Ashish Dwivedi):

> Add a script to child and inside it have a reference of script of parent object. Now write 3 methods in parent script like ( OnCollisionEnter2DChild , OnCollisionStay2DChild , OnCollisionExit2DChild ) and called respective method from the methods (OnCollisionEnter2D , OnCollisionStay2D , OnCollisionExit2D) which are in child object script by passing the collision object.

# Answer
> 2 votes
You can simply pass the top object to the children and call a function directly on it. This guarantees that you don't have to rely on parent propagation. So you don't end up doing silly things like `transform.parent.parent`

You could however automate this process with GetComponentInParent. This retrieves the first script it finds. Then cache that in your collision object, directly call functions on said cached object.

Alternatively you could make use of UnityEvents ( don't use Messages ) to bind functions to the child object. With unity events you can add any arbitrary listener so you can do more than just notify the top level object of the child object being hit.

# Answer
> 1 votes
You can perform a check on the collision and see which hit box was hit and also get the point of impact if needed.

note: the rigidbody is placed on the same object that has the Collision Check script.

This example is checking to see which hitbox the 'projectile' hit on a target.

```
private void OnCollisionEnter(Collision collision)
{
    if (collision.contacts[0].otherCollider.transform.gameObject.name == "HeadShot")
       //DO STUFF

    if (collision.contacts[0].otherCollider.transform.gameObject.name == "BodyShot")
       //DO STUFF
}

```

---
Tags: unity, collision-detection
---


# Question
Title: Coordinate system not working properly! OpenGL
I am learning `opengl` and tried to add `texture` to a `rectangle` using `shaders` but unfortunately my `rectangle` is not displaying at correct location and changing the coordinate of the `rectangle` does not seem to change it's position but rather changes the size of `texture` applied. I'm using `opengl` 2.1. And here are my codes and screenshot of my problem.

```
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.imageio.ImageIO;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;

import RenderEngine.Window;

public class Test {

    private int vertexShaderID;
    private int fragmentShaderID;
    private int programID;

    public static void main(String[] args) {
        new Test().run();
    }

    public void run() {
        Window.CreateWindow();

        float[] vertices = {
                -0.5f, 0.5f, 0f,
                -0.5f, -0.5f, 0f,
                0.5f, -0.5f, 0f,
                0.5f, 0.5f, 0f
        };

        float[] texCoords = {
                0f, 0f,
                0f, 1f,
                1f, 1f,
                1f, 0f
        };

        short[] indices = { 0, 1, 2, 2, 3, 0 };

        int tex = loadTexture("res/image.png");

        int v_id = bindArrayBuffer(vertices);
        int t_id = bindArrayBuffer(texCoords);
        int i_id = bindIndices(indices);

        initShader();

        while(!Window.isCloseRequested()){
            Window.PollEvents();
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
            GL11.glClearColor(0, 0, 0, 1);

            GL20.glUseProgram(programID);

            GL13.glActiveTexture(GL13.GL_TEXTURE0);
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex);

            int loc = GL20.glGetUniformLocation(programID, "samplr");
            if (loc != -1){
                GL20.glUniform1i(loc, 0);
            }

            GL20.glEnableVertexAttribArray(0);
            GL20.glEnableVertexAttribArray(1);

            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, v_id);
            GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0);

            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t_id);
            GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 0, 0);

            GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, i_id);

            GL11.glDrawElements(GL11.GL_TRIANGLES, indices.length, GL11.GL_UNSIGNED_SHORT, 0);

            GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);

            GL20.glDisableVertexAttribArray(1);
            GL20.glDisableVertexAttribArray(0);

            GL20.glUseProgram(0);

            Window.UpdateWindow();
        }

        GL20.glDetachShader(programID, vertexShaderID);
        GL20.glDetachShader(programID, fragmentShaderID);
        GL20.glDeleteShader(vertexShaderID);
        GL20.glDeleteShader(fragmentShaderID);
        GL20.glDeleteProgram(programID);

        Window.CloseWindow();
    }

    public void initShader(){
        vertexShaderID = loadShader("src/shaders/vertexShader.glsl", GL20.GL_VERTEX_SHADER);
        fragmentShaderID = loadShader("src/shaders/fragmentShader.glsl", GL20.GL_FRAGMENT_SHADER);
        programID = GL20.glCreateProgram();
        GL20.glAttachShader(programID, vertexShaderID);
        GL20.glAttachShader(programID, fragmentShaderID);
        GL20.glLinkProgram(programID);
        GL20.glValidateProgram(programID);
        GL20.glBindAttribLocation(programID, 0, "position");
        GL20.glBindAttribLocation(programID, 1, "textures");
    }

    private int bindArrayBuffer(float[] vertices) {
        int b_id = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, b_id);
        FloatBuffer buffer = toFloatBuffer(vertices);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
        return b_id;
    }

    private int bindIndices(short[] indices) {
        int b_id = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, b_id);
        ShortBuffer buffer = toShortBuffer(indices);
        GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
        GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
        return b_id;
    }

    private static ShortBuffer toShortBuffer(short[] data) {
        ShortBuffer buffer = BufferUtils.createShortBuffer(data.length);
        buffer.put(data);
        buffer.flip();
        return buffer;
    }

    private static FloatBuffer toFloatBuffer(float[] data) {
        FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
        buffer.put(data);
        buffer.flip();
        return buffer;
    }

    public int loadTexture(String fileName){
        BufferedImage bi;
        try {
            bi = ImageIO.read(new File(fileName));
            int width = bi.getWidth();
            int height = bi.getHeight();

            int[] pixel_raw = new int[width * height * 4];
            pixel_raw = bi.getRGB(0, 0, width, height, null, 0, width);

            ByteBuffer pixels = BufferUtils.createByteBuffer(width * height * 4);

            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++){
                    // 0xAARRGGBB
                    int pixel = pixel_raw[i * width + j];
                    pixels.put((byte) ((pixel >> 16 ) & 0xFF)); // RED
                    pixels.put((byte) ((pixel >> 8) & 0xFF));   // GREEN
                    pixels.put((byte) ((pixel) & 0xFF));    // BLUE
                    pixels.put((byte) ((pixel >> 24) & 0xFF));  // ALPHA
                }
            }

            pixels.flip();

            int id = GL11.glGenTextures();

            GL11.glBindTexture(GL11.GL_TEXTURE_2D, id);

            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
            GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels);

            return id;
        } catch (IOException e) {
            System.err.println("Could not load texture: " + fileName);
            e.printStackTrace();
            System.exit(-1);
        }

        return -1;
    }

    public int loadShader(String file, int type) {
        StringBuilder shaderSource = new StringBuilder();

        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append('\n');
            }
            reader.close();
        } catch (IOException e) {
            System.out.println(String.format("Could not read file %s:", file));
            e.printStackTrace();
            System.exit(-1);
        }

        int shaderID = GL20.glCreateShader(type);
        GL20.glShaderSource(shaderID, shaderSource);
        GL20.glCompileShader(shaderID);
        if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
            System.out.println(GL20.glGetShaderInfoLog(shaderID));
            System.err.println("Could not compile shader!");
            System.exit(-1);
        }
        return shaderID;
    }

}

```

**Vertex Shader**

```
#version 120

attribute vec3 position;
attribute vec2 textures;

varying vec2 tex_coord;

void main()
{
    tex_coord = textures;
    gl_Position = vec4(position, 1);
}

```

**Fragment Shader**

```
#version 120

uniform sampler2D samplr;

varying vec2 tex_coord;

void main()
{
    gl_FragColor = texture2D(samplr, tex_coord);
}

```

**Output**

**When I change my vertices to:**

```
    float[] vertices = {
        -1f, 1f, 0f,
        -1f, -1f, 0f,
        1f, -1f, 0f,
        1f, 1f, 0f
    };

```

**Without Texture**

**Problem :** For some reason `texCoords` is acting as `position` and `vertices` is acting as `textures` in `shaders`.

**Fix** Apparently adding the `vertex` buffer to `attrib` index `1` fixes the problem.

```
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, t_id);
GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 0, 0);

GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, v_id);
GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, 0, 0);

```

Even though `position` is binded to `attrib` location `0`.

```
GL20.glBindAttribLocation(programID, 0, "position");
GL20.glBindAttribLocation(programID, 1, "textures");

```

*Can anyone explain this?*

# Answer
> 2 votes
After calling glBindAttribLocation you need to link your program again: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindAttribLocation.xhtml

---
Tags: opengl, java, textures, coordinates, lwjgl3
---


# Question
Title: Unity generates changes in GitHub on saving scene
So, here is my problem.

First I have a look at the changes in the repository which I am working with.

Initially there are no changes:

Then I open up Unity, i don't make any changes and just save the scene:

I then go to GitHub Desktop and suddenly there are a lot of changes appearing which I did not make:

How can I avoid that?

The files which are getting changed are `.prefab` files.

# Answer
**Short answer:**

Those changes ~~seem to be of `.meta` file contents, and/or scene stuff~~ \[**Update:** As pointed out in the comments, they seem to be prefab data. But the issue and solution are the same\]. It's not unthinkable that some floats will have the least significant bits changed due to floating-point precision errors. You can just ignore the fact that those changes exist, and commit them.

---

**Slightly longer answer:**

Don't worry... A `position` or `rotation` changed by `1e-6` (`0.000001`; BTW, yours are, like, `1e-12+` \[`0.000000000001`\]) is not going to have any noticeable difference in most games (in fact, unity considers anything with difference under `1e-5` as "equal", if you look at the source code). Your game would need to be a game like KSP trying to shoot something across the solar-system to hit a relatively tiny target in order for those to make a noticeable difference. =D

---

**Bonus:**

Since you seem to be unaware of the concept of FPPEs (floating-point precision errors), I will ***strongly*** recommend you to take a look at **What Every Programmer Should Know About Floating-Point Arithmetic**
> 1 votes

---
Tags: unity, git
---


# Question
Title: Shooting projectiles towards mouse position in Unity 2D
I'm currently creating a scrip that handles the projectile movement and it's almost where I want it to be. Currently the script correctly instantiates the projectiles, moves the projectiles towards the mouse and deletes them off screen, but the speed of the projectile is not constant (faster or slower depending on how close the mouse is to the player) and after the projectile is fired, it follows the position of the mouse until it flies off screen.

```
public class LetterController : MonoBehaviour {
    private List<GameObject> letters = new List<GameObject>();
    public GameObject letterPrefab;
    public float letterVelocity;
    Vector3 direction;
    void Update()
    {
        direction = Input.mousePosition;
        direction.z = 0.0f;
        direction = Camera.main.ScreenToWorldPoint(direction);
        direction = direction - transform.position;
        if (Input.GetMouseButtonDown(0))
        {
            GameObject letter = (GameObject)Instantiate(letterPrefab, transform.position,Quaternion.identity);
            letters.Add(letter);
        }
        for (int i = 0; i < letters.Count; i++)
        {
            GameObject goLetter = letters[i];
            if (goLetter != null)
            {
                goLetter.transform.Translate(direction * Time.deltaTime * letterVelocity);
                Vector3 letterScreenPosition = Camera.main.WorldToScreenPoint(goLetter.transform.position);
                if (letterScreenPosition.y >= Screen.height || letterScreenPosition.y <= 0 || letterScreenPosition.x >= Screen.width - 20 || letterScreenPosition.x <= -20)
                {
                    DestroyObject(goLetter);
                    letters.Remove(goLetter);
                }
             }
          }
       }
   }

```

I tried moving everything from `Update()` into a separate function called `Shoot()` and called that from `Update()`. I tried putting `Vector3 direction` in its own Vector3 function and calling it in `goLetter.transform.Translate`. I also tried using `LateUpdate()`. Nothing I've tired has made any significant changes to how the projectile interacts in Unity. I'd like to have the projectiles move at a constant speed and not follow the cursor but rather travel in a straight line anyone got any clues?

# Answer
> 3 votes
Your problem here is two fold:

First, when you spawn an object, that should be the last the current script interacts with it. From that point forward, the new object should control its own behavior. You need to modify your projectile to handle its own movement.

The second is the use of `Vector2.MoveTowards()` instead of `Translate()`.

For projectiles that don't track the mouse, like a bullet:

```
using UnityEngine;
using System.Collections;

public class FixedProjectile : MonoBehaviour {
    public Transform target;
    public float speed=6.0f;

    void OnStart()
    {
        target=Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    void Update() {
        float step = speed * Time.deltaTime;
        transform.position =Vector2.MoveTowards(transform.position,target.position,step);
    }
}

```

For projectiles that track the mouse, like a guided missile:

```
using UnityEngine;
using System.Collections;

public class MouseGuidedProjectile : MonoBehaviour {
    public Transform target;
    public float speed=6.0f;

    void Update() {
        target=Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float step = speed * Time.deltaTime;
        transform.position =Vector2.MoveTowards(transform.position,target.position,step);
    }
}

```

For projectiles that track a specific target, like a guided missile with target lock, simply remove the target line from Update() :

```
using UnityEngine;
using System.Collections;

public class GuidedProjectile : MonoBehaviour {
    public Transform target;
    public float speed=6.0f;

    void Update() {
        if(target!=null)
        {
            float step = speed * Time.deltaTime;
            transform.position =Vector2.MoveTowards(transform.position,target.position,step);
        }
    }
}

```

and set the target transform after you instantiate the object

```
GameObject missile = (GameObject)Instantiate(prefab, transform.position,Quaternion.identity);
missile.target=GameObjectToTarget.transform;

```

---
Tags: unity, c#, 2d, projectile-physics
---


# Question
Title: How to render a large number of colored dots in 3d space?
I would like to create a game similar to Scanner Sombre. The player is in a dark environment and can't see their surrounding unless they use a scanner. That scanner sends out rays which mark little dots on all surfaces, creating 3D map of environment.

I tried to just paint visible dots on transparent textures, but that does not work because the dots are supposed to always face the player.

I considered to instantiate a new game object for every single dot. But as the game progress, the player will see billions of these dots at once, and that would likely be terrible in terms of performance. Can someone suggest a possible technique to do this?

# Answer
> 2 votes
One option would be to use a particle system to host all the dots. Particle systems are optimized for rendering a large number of very simple billboard objects. That means a particle in a ParticleSystem generates far less management overhead than a full-fledged GameObject. You can manually add particles to the system using `GetParticles` and write them back to the particle system with `SetParticles`.

The way particles are colored seems to depend on the distance to the camera. This should be implemented with a custom shader which uses the z-depth to pick the particle color. When you already have to write a custom shader anyway, you could also use it for a LOD (level of detail) optimization. After a certain z-depth, skip most of the particles, but render the remaining particles larger. That means far away areas are rendered with a lower level of detail. The player won't notice the difference, but it will be far easier on the GPU.

# Answer
> 1 votes
It's probably not billions of dots but "just" 10s of millions. Also if the points are the only thing being rendered then you will have plenty of memory to spare for all those points.

gpus are pretty good at rendering pointclouds. So the points will just get pushed into a vbo and that gets rendered with a standard vertex shader using GL\_POINTS.

The points themselves are acquired using a standard raycast based on the scanner location and direction it's pointing.

Doing a partition of the world to avoid having to render points behind the player and maybe a way to reduce the number of points rendered when far away (LOD), but that's about it for possible optimizations.

# Answer
> 1 votes
**Idea** **Compute Shader**:

1. take z-buffer and take random screen points(with blue noise sampling).
2. convert screen point to ray and multiply by distance from z-buffer.
3. fill RWStructuredBuffer

**Visualisation Shader**:

1. use RWStructuredBuffer
2. convert point to bilboard in geometry shader
3. add Color

But, i dont have simple and fast idea for blue noise sampaling

This is my scanner shader. For visulizing use any point cloud shader with geometry shader

```
#pragma kernel Scan
#include "UnityCG.cginc"
#include "./Camera.cginc"

struct Point
{
    float3 position;
    float3 color;
};

struct ScreenPoint
{
    float2 pos;
};

Texture2D<float> depth;
Texture2D<float3> gradient;
Texture2D<float3> frame;
float3 cameraPosition;
float2 nearFarClip;
RWStructuredBuffer<Point> outBuffer;
float time;
matrix InvVP;
int stride;

SamplerState my_point_clamp_sampler;

float LinearEyeDepth2( float rawdepth )
{
    float _NearClip = nearFarClip.x;
    float _FarClip = nearFarClip.y;
    float x, y, z, w;
/*
    x = -1.0 + _NearClip/ _FarClip;
    y = 1;
    z = x / _NearClip;
    w = 1 / _NearClip;
*/

    x = 1.0 - _NearClip/ _FarClip;
    y = _NearClip / _FarClip;
    z = x / _NearClip;
    w = y / _NearClip;

  return 1.0 / (z * rawdepth + w);
}

[numthreads(256,1,1)]
void Scan(uint3 id : SV_DispatchThreadID)
{
    half threads = 256;
    half even = 2.0*(id.x&1)-1;
    half x = even*(sin(time + 0.005*id.x));
    half y = 1-sin(((2*id.x)/threads)-2)*1.5-1.8;
    float2 pPos = float2(x, y);

    float2 uv = float2(0.5f*(pPos.xy+1));
    float z = asfloat(depth.SampleLevel(my_point_clamp_sampler, uv, 0));
    float dist = LinearEyeDepth2(z);

    float4 clip = float4(pPos.x, pPos.y, 0.5f, 1);
    float3 dir = mul(InvVP, clip).xyz;
    float3 pos = dist * dir + cameraPosition;

    float3 col = frame.SampleLevel(my_point_clamp_sampler, uv, 0).xyz;

    half t = step(dist, nearFarClip.y- 0.01);
    pos = lerp(float3(0,0,0), pos, t);

    int index = stride * threads + id.x;
    outBuffer[index].color = col;
    outBuffer[index].position = pos;
}

```

Inverse VP matrix

```
private Matrix4x4 GetInvVPMatrix()
{
   var p = GL.GetGPUProjectionMatrix(_camera.projectionMatrix, false);
   var v = GetVMatrix();
   var clipToWorld = Matrix4x4.Inverse(p * v) * Matrix4x4.TRS(new Vector3(0, 0, -p[2,2]), Quaternion.identity, Vector3.one);
   return clipToWorld;
}

private Matrix4x4 GetVMatrix()
{
    var m = Matrix4x4.TRS(Vector3.zero, _camera.transform.rotation, Vector3.one);
    m = Matrix4x4.Inverse(m);
    m.m20 *= -1f;
    m.m21 *= -1f;
    m.m22 *= -1f;
    m.m23 *= -1f;
    return m;
 }

```

# Answer
> 0 votes
Well, i can't be sure, but a custom shader that would only render the vertices of a mesh should do the trick, and i think its the cheapest sollution. Something similar to a wireframe shader.

---
Tags: unity, shaders, graphic-effects
---


title: Unity3d: Delay between animation cycles

text:
# Question
Title: Unity3d: Delay between animation cycles
trying to create simple 360 rotation animation on 2d object but can't understand delay between animation cycles, please check youtube video with issue: https://www.youtube.com/watch?v=JlLJLHvnkgo

# Answer
In your animation curves view, click & drag to select the keys representing the start and end of your rotation.

Right-click and choose Both Tangents -\> Linear from the context menu.

This will change your rotation from one that has a slow start and finish (those rounded plateaus at the beginning and end of the curve) to one that proceeds at a consistent rate throughout (a straight line on the graph)
> 1 votes

---
Tags: unity, 2d, animation
---


# Question
Title: Rotating according to ground normal on Unity 3D
I know there are already some threads about this, but my problem isn't exactly with the algorithm itself. I was able to use RayCast and get the ground normal, using it to store the rotation necessary to align to the ground in a quaternion using:

```
slopeRotation = Quaternion.FromToRotation (transform.up, hit.normal);

```

Where hit.normal is the normal of the ground. After this, I check whether the player is moving (the user is moving the joystick axis) or standing still. If it's standing still, I align it with the ground using:

```
transform.rotation = Quaternion.Slerp(transform.rotation,slopeRotation * transform.rotation,10*Time.deltaTime);

```

When the player is moving, I rotate using:

```
transform.rotation = Quaternion.Slerp (transform.rotation,slopeRotation *camRotation*movementRotation , 10 * Time.deltaTime);

```

Where camRotation is simply the rotation of the MainCamera(a third person one) on the Y axis and movementRotation is the rotation of the joystick axis, also on the Y axis, calculated using:

```
movementRotation = Quaternion.LookRotation (new Vector3(Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")));
camRotation = Quaternion.Euler (0, cam.transform.rotation.eulerAngles.y, 0);

```

Although the code above makes sense in my head, it doesn't work as expected, as seen in the picture below:

As you can see, it works fine when you're standing still, which means that the ground normal and the slopeRotation are correctly calculated. When the player moves though, the combination of all the quaternions seems to cause some kind of problem that makes the player slightly deviate from the correct rotation. It might be worth noting that camRotation and moveRotation also work completely fine on their own, so the player moves correctly according to both the rotation of the camera and of the joystick, both on the floor and on ramps.

# Answer
> 3 votes
Nevermind guys. I just realized a really silly mistake behind all of this. The thing is, when I use:

```
slopeRotation = Quaternion.FromToRotation(transform.up, hit.normal);

```

to get the rotation necessary to align to the ground, once the Player aligns itself to the ground, slopeRotation will become `Quaternion.identity`, since `transform.up`'s direction will be the same as`hit.normal`. It work's fine if the Player is standing still.
However, if I try to move on a ramp, the Player *will* correctly rotate according to the camera and to the joystick input, but since `slopeRotation == Quaternion.identity`, the Player will always try to revert back to it's initial rotation.
Thus, when the player is moving, I create another Quaternion, called `slopeRotationMoving = Quaternion.FromToRotation(Vector3.up)`. So, because `slopeRotationMoving` is relative to `Vector3.up` which is always pointing up (as opposed to `transform.up`, which will eventually align with the surface), it will never revert back to `Quaternion.identity`. Now, when the player is moving, I use:

```
transform.rotation = Quaternion.Slerp (transform.rotation,slopeRotationMoving *camRotation*movementRotation , 10 * Time.deltaTime);

```

And it works perfectly. So, as a reminder, always remember to use `transform.up`, `transform.forward`,`Vector3.up`,`Vector3.forward`, etc. according to your needs, since they're very different.

---
Tags: unity, c#, vector, quaternion
---


# Question
Title: How do I deal with this tilemap wraparound edge case?
I'm building a 2D game engine that uses tilesets to build levels. I recently added functionality to handle wraparounds (ie. where the right edge of the map connects to the left edge.) The engine scrolls the map to follow the character around, remaining centered on the player whenever possible.

I implemented wraparound as follows:

The map engine has a Viewport object, which has a bounding rect and can test each tile to see if the tile is contained within the viewport. When the screen coordinates are such that wraparound is needed, the viewport can set up sub-viewport objects that display different parts of the coordinate space, and place them side by side.

Each frame, I test the tiles on the map against the viewport to see if they can render. Each tile object has a `viewport` property designating which viewport it's rendering into. In the case of a composite viewport, this will delegate the test to each sub-view in turn, and on the first match, set the tile's viewport object and break the loop.

This works just fine in practice, until I hit one specific edge case: When the map is the minimum size, which is exactly the size of the screen, while trying to scroll, the tiles along the edge will be in the area of both viewports at once until the scroll completes the full width of that tile, which causes it to render on one edge and the other edge to show blank space for a moment.

I could resolve this by giving each tile a list of viewports instead of a single one, but that would significantly increase the complexity of my rendering, which I want to keep as fast and simple as possible, just to deal with a minor edge case.

Does anyone know of an elegant way to resolve this issue?

# Answer
It sounds like what you have is this: (pseudocode)

```
for each tile:
  find viewport that tile is in
  if viewport != null:
    render tile according to viewport

```

Instead consider doing this:

```
for each viewport:
  for each tile in the viewport:
    render tile according to viewport

```

Not only will this fix your problem, it should give you a speed improvement on big maps because you only need to check the tiles that are on-screen (using the viewport's coordinates), instead of every tile in the map.
> 1 votes

---
Tags: architecture, tilemap, viewport
---


# Question
Title: How to control an Unity character with mouse clicks?
I am trying to make a 2D RPG game in Unity with an isometric tile setup.

Using Unity/C#, how do I code the character's upward, right, left, down and diagonal animations and movements using mouse button as the controls (much like Red Alert 2). Normally, this can easily be done using keyboard inputs, however, what I am trying to do is control the character by clicking the mouse. For example, if I click in a diagonal location from the character, the character should follow the mouse and also do the diagonal animation.

# Answer
The way I would approach this is casting a ray from the camera in the direction the mouse has clicked in order to find the position on the map. This should give you the position on the terrain as a Vector3. Then use basic vector maths to find the direction in which your character should move:

```
Vector3 direction = character.position - target.position
direction.Normalize()

```

You can then calculate a velocity for the character using the direction:

```
Vector3 velocity = direction * speed; // ex: float speed = 5;

```

Then use this velocity accordingly:

```
character.position += velocity * Time.deltaTime;

```

This is the way I would implement it anyway. In order for the character to move around obstacles, you need to research pathfinding.

The direction the character is moving to is the direction the character model should face as well.

---

How to raycast from the camera: https://docs.unity3d.com/Manual/CameraRays.html

Direction from one vector to another: https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html

Basic top-down movement: https://unity3d.com/learn/tutorials/topics/2d-game-creation/top-down-2d-game-basics
> 1 votes

# Answer
This tutorial off the Unity website should help you with the **entire project**, especially if you're trying to emulate the *Red Alert* series.

Player movement and animation **using the mouse** is covered in Chapter 2, right after they set up the environment, **if you want to just skip to that**. The tutorial's written in Unity 4.6, but they have the 5.x project files on there as well so it shouldn't be all too hard to make the switch.

Better yet, it's beginner-level and includes both the code and a video, so it'll be relatively easy to pull off.
> 0 votes

---
Tags: unity, c#, path-finding
---


# Question
Title: Accessing variables defined in another .js file in rpgmaker MV
I'm coming from C++, diving into JS and enjoying the journey so far but I've been at an en passe for the past 2 days and I'm exhausted.

I need help figuring out how to access variables across plugins.

I tried following the guidance in this posting (and numerous others stating to follow the same syntax): https://forums.rpgmakerweb.com/index.php?threads/mv-syntax-for-variables-in-script-calls.48422/

I set these values in plugin1.js:

```
var weaponRight = 0;
var weaponHeight = 0;

var a = weaponRight;
var b = weaponHeight;

$gameVariables.setValue(5, a);
$gameVariables.setValue(6, b);

```

Then try to access them in this script:

```
var z1 = eval($gameVariables[5]);
var z2 = eval($gameVariables[6]);
...
this.x += (z1 || 0);
...

```

if I just enter an int, say 5--in place of z1--the transform executes. In addition, I emulated the parsing logic in the first JS file to the 't', so I'm certain the error is coming from my ignorance.

# Answer
> 1 votes
So, I figured it out. I ended up just using a global variable, ensuring that I defined it outside the scope of any function so its value would not be cleared when that function went out of scope.

```
var globalDummyVariable = 0;

```

Then I just made a call directly in the scope of another function like this:

```
Yanfly.globalDummyVariable

```

This is the quick and dirty way to get it up and running, but I think it's a bit safer for new programmers to get a handle on instead of using the new keyword and not deleting objects.

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


# Question
Title: How can i find the player local position plus 1.5 on each 4 directions?
I know the current player position:

```
private void Test()
    {
        Vector3 playerPosition;
        playerPosition = player.localPosition;

        Vector3 fwd = player.TransformDirection(Vector3.forward);
        Vector3 left = player.TransformDirection(Vector3.left);
        Vector3 right = player.TransformDirection(Vector3.right);
        Vector3 back = player.TransformDirection(Vector3.back);
    }

```

Now i want to find from the player position each direction position + 1.5f from the player.

# Answer
> 4 votes
Just multiply by 1.5, no?

```
Vector3 rightOnePointFive = player.localPosition + player.right * 1.5f;
Vector3 leftOnePointFive = player.localPosition - player.right * 1.5f;
Vector3 forwardOnePointFive = player.localPosition + player.forward * 1.5f;
Vector3 backOnePointFive = player.localPosition - player.forward * 1.5f;

```

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


# Question
Title: Calculating correct normal direction from multi-variable function
I am working with a plane model which I am offsetting the vertices on the up axis to look like waves by using the function:

Sin(vertex.x * frequency) * amplitude + Cos(vertex.y * frequency) * amplitude

Previously, I did this with a single variable and was able to confirm my normal directions were correct by getting the derivative, taking the tangent direction from that, and getting the perpendicular direction to the tangent in order to get my normal direction. I then just flipped them so they were facing the right way.

Now that I have added in the second, y, variable I have tried to take a similar approach. Where I take the two partial derivatives, get the tangent direction for each, get the normal for each from that, and then add the normals together to get my final normal direction. However, it seems that the results I am getting are different from those of the Unity calculation, which is correct.

Here is an image comparing my results to the correct Unity calculation:

Does anyone know where about I am going wrong in my calculation? I think it may be related to where and when I am normalizing, but I have tested out a bunch of different options and can't seem to get it to look correct and am now questioning if perhaps my method for combining the two normals is wrong. Thanks for any input. Below is a snippet of the code I am using to do this.

```
offsetAmount = Mathf.Sin(vertices[i].x * _Frequency) * _Amplitude + Mathf.Cos(vertices[i].y * _Frequency) * _Amplitude;

private void DifferentiateNormals()
{
    // Loop through every normal and calculate it manually
    for (int i = 0; i < vertices.Length; i++)
    {
        // The derivative is also an equation for the slope of a tangent line
        float offsetAmountDerivative = Mathf.Cos(_Frequency * vertices[i].x) * (_Frequency * _Amplitude);
        float offsetAmountDerivative2 = Mathf.Sin(_Frequency * vertices[i].y) * -(_Frequency * _Amplitude);

        // Rise / Run => Rise is the derivative function, run is 1
        Vector2 tangent = new Vector2(1, offsetAmountDerivative);
        tangent.Normalize();
        Vector2 tangent2 = new Vector2(1, offsetAmountDerivative2);
        tangent2.Normalize();

        // The perpendicular of tangent direction (x,y) is (y,-x)
        Vector3 normal = new Vector3(tangent.y, 0, -tangent.x);
        normal.Normalize();
        Vector3 normal2 = new Vector3(tangent2.y, 0, -tangent2.x);
        normal2.Normalize();
        // Flip the normals to be the correct direction (up)
        normal = -normal;
        normal2 = -normal2;

        Vector3 finalNormal = normal + normal2;
        //Vector3 finalNormal = new Vector3(_Amplitude * _Frequency * Mathf.Cos(_Frequency * vertices[i].x), -(_Amplitude * _Frequency) * Mathf.Sin(_Frequency * vertices[i].y), -1);
        finalNormal.Normalize();
        //finalNormal = -finalNormal;

        if (direction == ModelUpDirection.Y_Up)
        {
            // Works for Unity Plane
            normals[i] = new Vector3(finalNormal.x, finalNormal.z, 0.0f);
        }
        else if (direction == ModelUpDirection.Z_Up)
        {
            // Works for 100x100 Plane
            normals[i] = new Vector3(finalNormal.x, 0.0f, finalNormal.z);
        }
    }
    mesh.normals = normals;
}

```

# Answer
This trick

```
Vector3 normal = new Vector3(tangent.y, 0, -tangent.x);

```

works great in 2D, when we only have 2 perpendiculars to choose from. It's not the right technique to use in 3D though, when we have a whole circle of possible perpendiculars!

So, you compute your tangent along the x direction:

```
Vector3 xTangent = new Vector3(1, 0, offsetAmountDerivative);

```

...and your y direction. Note that since we're differentiating with respect to y, the rate of change of x is 0 and the rate of change of y is one:

```
Vector3 yTangent = new Vector3(0, 1, offsetAmountDerivative2);

```

Now we have two vectors in space, one pointing mostly along the x direction and the other mostly along the y. Between them, they describe a flat tangent plane representing the incline of our surface at this point. We want the normal of that plane: a vector that's perpendicular to *both* of them at once (not just an average of some perpendicular of each).

We can get this with a cross product:

```
Vector3 normal = Vector3.Cross(xTangent, yTangent).normalized;

```
> 1 votes

---
Tags: mathematics, shaders, normals, direction
---


# Question
Title: Finding the closest point of a structure/building that has a path
I am making an RTS game, and I implemented path finding with A\*. My A\* algorithm uses 8 directions and terminates early in the case of no path found (I use 50\*the vector distance between the unit and the point as the limit to dequeueing the fringe). If there's no path then they will go to the nearest valid point to the destination. This problem arises because a structure is bigger than 1 tile

I am having trouble now with attacking a structure, right now I have it so that it checks each "tile" of the structure, and gets the distance between the unit and the structure "tile". Plus, it will see if theres a path from that tile to the unit, and if there is then the tile is put in a priority queue, where priority is min distance.

Here, this can be a lot of path finding calls for 1 unit using this, the number of calls is dependent on the x\*y size of the structure. Here is a picture to illustrate (with the orange being the unit, red being barrier (that can potentially move) and the blue being the structure)

Here there will be 9 calls to path finder, 8 of them will fail almost immediately , 9 will produce the path from the unit in orange to the bottom right corner of the structure.

It can get much worse with an example like this:

Here there will be 6 path finding calls which could take a long time depending on the space between the unit and the structure. So there must be a better way to path to a closest available tile of a structure without calling path finder for each tile in the structure and I need help with that. How would I go about treating the entire blue region as the goal? My node only encompasses one tile, so would I need multiple destinations (so multiple f values)?

# Answer
> 1 votes
Modify your goal check from something like:

```
if(currentNode == goalNode)

```

to `if(goalRegion.Contains(currentNode))` or `if(currentNode.isAGoal == true)`

Now your search can stop on any goal tile, not just one specially-chosen one.

Next, adjust your heuristic. If you're using a Chebyshev distance from a single tile like this:

```
int h(int x, int y) {
    return max(abs(x - goal.x), abs(y - goal.y));
}

```

You can modify it to a distance from a rectangle like so:

```
int h(int x, int y) {
    goalX = clamp(x, goalRegion.minX, goalRegion.maxX);
    goalY = clamp(y, goalRegion.minY, goalRegion.maxY);
    return max(abs(x - goalX), abs(y - goalY));
}

```

Now you can run your pathfinding exactly once, and have it find the shortest path to any point in the goal region.

If you keep track of the tile with the smallest heuristic value `h` you've seen, as this answer describes, then you can fall back on a path to that tile in the event that your main search fails to find a reachable goal - getting you as close as possible instead.

---
Tags: path-finding
---


# Question
Title: Prevent parent alarms to activate a child alarm event
I'm working on a small game using Gamemaker Studio 2 and I've noticed that my Parent `o_enemy.Alarm[0]` Is activating the Child `enemy_1.Alarm[0]` event.

Both alarms were supposed to be activated under different conditions, (The parent alarm is used for all enemies, but the child alarm is used for the specific enemy) but they seem that they'll activate each other because they share the same name `Alarm[0]`.

I could fix it by setting one of the alarms to `Alarm[1]`, but seeing that I've only a limited amount of 9 Alarms, I think there should be an easier solution to solve this problem.

So far I've tried `Event.inherited()` on the child alarm, but that didn't solved the problem.

Is there a way that a child's Alarm will ignore the conditions of the parent alarm?

# Answer
Instead of

```
o_enemy.alarm[0] = value;

```

Try something like this

```
with o_enemy
{
    if object_index != enemy_1
    {
        alarm[0] = value;
    }
}

```
> 1 votes

---
Tags: game-maker, events, timer
---


# Question
Title: How to place an instance of Editor Window in screen center?
I want to create an instance of `Editor Window` by using `CreateInstance` or `GetWindow`. And I want to place it in center of the screen (or center of Unity).

I didn't find any methods in Unity Engine that could help me. Do they exist?

How can I do it within the script?

**Note:** I mean: how can I find out what is the user's screen resolution? Which method can give me that?

P.S. `Screen.width/Screen.height` \- is not what I need. Because it refers to the Game View's window, not Unity.exe Editor's size and not monitor Screen

# Answer
> 0 votes
Even though I've already found the code that were presented by **@GabrieleVierti** in **his answer** (I think it's too big and massive), I found and preferred to use **Screen.currentResolution**, which returns the current screen resolution.

For now it's fine for me.

# Answer
> 2 votes
There is a way of obtaining Unity Editor's main window. From there you can just obtain window size and set your custom editor window position :). I will just leave you the link.

\[In case the link is broken\]

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

 public static class Extensions
 {
 public static System.Type[] GetAllDerivedTypes(this System.AppDomain aAppDomain, System.Type aType)
 {
     var result = new List<System.Type>();
     var assemblies = aAppDomain.GetAssemblies();
     foreach (var assembly in assemblies)
     {
         var types = assembly.GetTypes();
         foreach (var type in types)
         {
             if (type.IsSubclassOf(aType))
                 result.Add(type);
         }
     }
     return result.ToArray();
 }

 public static Rect GetEditorMainWindowPos()
 {
     var containerWinType = System.AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(ScriptableObject)).Where(t => t.Name == "ContainerWindow").FirstOrDefault();
     if (containerWinType == null)
         throw new System.MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity");
     var showModeField = containerWinType.GetField("m_ShowMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
     var positionProperty = containerWinType.GetProperty("position", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
     if (showModeField == null || positionProperty == null)
         throw new System.MissingFieldException("Can't find internal fields 'm_ShowMode' or 'position'. Maybe something has changed inside Unity");
     var windows = Resources.FindObjectsOfTypeAll(containerWinType);
     foreach (var win in windows)
     {
         var showmode = (int)showModeField.GetValue(win);
         if (showmode == 4) // main window
         {
             var pos = (Rect)positionProperty.GetValue(win, null);
             return pos;
         }
     }
     throw new System.NotSupportedException("Can't find internal main window. Maybe something has changed inside Unity");
 }

 public static void CenterOnMainWin(this UnityEditor.EditorWindow aWin)
 {
     var main = GetEditorMainWindowPos();
     var pos = aWin.position;
     float w = (main.width - pos.width)*0.5f;
     float h = (main.height - pos.height)*0.5f;
     pos.x = main.x + w;
     pos.y = main.y + h;
     aWin.position = pos;
     }
 }

```

This is a js script, so if you are using Unity 2017.x you should probably translate it to c#(which shouldn't be too difficult since the syntax is pretty much the same). In this script there is also a function that let's you position every editor window in the center of the Main Unity window. All we have done here was using Extensions.GetEditorMainWindowPos() to get back the rect of the main window in screen coordinates.

# Answer
> -1 votes
**EditorWindow - How do I center a Editor Window?**

> To set position your editor windows instance you need to use windows.positon.

var window = new MyWindow(); window.position = new Rect(Screen.Width/2,Screen.Height/2,599,299);

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

class MyWindow : EditorWindow
{
    string myString = "Hello World";
    bool groupEnabled;
    bool myBool = true;
    float myFloat = 1.23f;

    // Add menu item named "My Window" to the Window menu
    [MenuItem("Window/My Window")]
    public static void ShowWindow()
    {
        //Show existing window instance. If one doesn't exist, make one.
        var window = EditorWindow.GetWindow(typeof(MyWindow));
        window.position = new Rect(Screen.width / 2, Screen.height / 2, 599, 299);
    }

    void OnGUI()
    {
        GUILayout.Label("Base Settings", EditorStyles.boldLabel);
        myString = EditorGUILayout.TextField("Text Field", myString);

        groupEnabled = EditorGUILayout.BeginToggleGroup("Optional Settings", groupEnabled);
        myBool = EditorGUILayout.Toggle("Toggle", myBool);
        myFloat = EditorGUILayout.Slider("Slider", myFloat, -3, 3);
        EditorGUILayout.EndToggleGroup();
    }
}
```

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


title: Unity Physics Not Getting Bounce Angle

text:
# Question
Title: Unity Physics Not Getting Bounce Angle
I've got a ball rolling along a flat surface towards a wall. If the ball collides with the wall, it always bounces perpendicular to the wall, no matter what it's velocity before, instead of following the angle of reflection.

Here is the relevant information about the ball: Non-Kinematic Rigidbody Collisions set to Continuous Physic Material with 0.6 friction and 0.7 bounciness Combine Modes are both average

And the wall: Non-Kinematic Rigidbody Collisions set to Continuous Physic Material with 0.6 friction and 0.7 bounciness Combine Modes are both average

I can probably manually check for collisions and change the velocity along the angle using Vector3.reflect, but this should be something the Unity Physics engine handles if I can figure out how. Is there anything that can be done in-engine to get the bounce angles to set properly?

# Answer
> 1 votes
Based on this question, try setting a lower friction value, and a higher bounciness.

---
Tags: unity, collision-detection, physics
---


# Question
Title: Is there a specific name for this type of concept art and the artist who does them?
Let's say you already have the fundamentals of your game: you created gameplay that you and your (possible) playtesters find enjoyable to play, and you think you can flesh out your game more. However, it's all just colorless blocks and cones at this stage. It's still just a prototype and you don't have a clear vision of how you want the game to actually *look*.

Before you try to glue together something compelling in your game engine, you want to create a mockup of how your game could possibly look like, just like how Bloodstained did on their Kickstarter page:

These aren't ingame screenshots, those were made before the game even started. How are these prototype images called and what are their artists called? What kind of "keywords" do I have to look for if I want to hire an artist to prototype one or multiple possible looks for my game?

# Answer
The art itself is a kind of concept art often called a "mockup," although sometimes you see people refer to them as "pre vis" artwork (particularly among those coming from a film background) or "overpaints" (the latter is sometimes used if some hand work is being done over some existing game art versus producing the concept image entirely by hand).

Sometimes people call them "visual bibles" or "art bibles," although that's usually (in my experience at least) in reference to the *collection* of the mockup shots themselves.

Somebody billing themselves as a concept artist could probably produce these for you. It's not a big enough need, and not too fundamentally different from the goals of other styles of concept art, to have really developed its own dedicated sub-discipline.

The key thing you'd need when finding somebody to produce this kind of material for you is a clear description of what you're after -- that you're looking for some kind of art to represent the idea of what the actual final in-game product may look like. With a clear enough set of guidelines, bolstered by structural examples like you've provided in the question, and a good back-and-forth relationship between the both of you, you should be able to hire any sort of artist with the appropriate skills to produce these.
> 13 votes

---
Tags: terminology
---


# Question
Title: Procedural generation of semi-correct planetary systems
So there are lots of resources you can find via Google or using the search here on how to procedural generate a whole galaxy. But I couldn't find any good resource on how to generate planetary systems that follow these criteria:

The systems don't have to be accurate simulations of orbits but should be close to plausible orbits. I don't care about any simulation that cares about how the system might look in 200k years, the orbits could be rock solid. The main problem I'm facing is how to randomly generate a system that could be seen as plausible. This becomes especially interesting when you have a system with a binary star.

Just randomly creating orbits won't make up a plausible system, you'll end up with obviously non working orbits. Yes, I'm aware of the N-body problem :) but this doesn't help me, at least I think so, to solve the problem of generating a plausible system procedural?

I think you could just randomly spawn planets on their orbit and give them a mass and then use the N-body mathematics to calculate if they're more or less valid, if not start over and randomly generate new orbits until you get something that matches, but this would be very inefficient.

# Answer
> 13 votes
In order to create a plausible solar system, make sure every orbit is within the sphere of influence of the parent body, but not within the hill sphere or roche limit of another body.

The sphere of influence is the maximum radius around a planet where stable satellites can be expected.

The roche limit is the minimum orbital radius one celestial body can have around another. When it is on a lower orbit, it breaks apart and becomes a ring.

The hill sphere is relevant when you want to prevent to create two satellites around the same body which have very close orbits. It is the range between minimum and maximum orbital radius a planet "occupies".

All three values can be calculated from the mass and orbital radius with the formulas in the linked Wikipedia articles.

So I would then try the following algorithm:

1. Create a random number of celestial bodies with a random orbital radius and mass. Radius and mass should be on a logarithmic scale.
2. Starting from most to least massive, calculate the hill sphere of each planet. Any less massive planet in the hill sphere of a more massive planet becomes a moon of that planet. Randomly-generate the orbital radius of the moon around the parent with a logarithmic distribution between 0 and the sphere of influence of the parent.
3. Perform step 2 for all moon systems to resolve hill-sphere conflicts of moons. Whether a moon can have a stable satellite is a matter of debate among the astronomy community (no example is known in our solar system). When you don't want any moon-moons, simply delete the smaller moon or put it on a different random orbit.
4. Check the Roche limit of every object around its parent. When it is below the roche limit, convert it to a ring (or just delete it).

This covers single-star systems, but not binary star systems. A binary star system has two stars which orbit a common barycenter. Planets can either orbit one of the stars (S-type orbit) or the common barycenter on a very wide orbit (P-type orbit).

If you want a binary star system, I would recommend to generate the second star as another satellite around the primary star at first. Anything in the hill sphere of the second star orbits the second star and anything with a radius smaller than the hill sphere of the second star orbits the first star. Calculate the barycenter and have both stars with their moons orbit that. Anything with a larger obit than the hill sphere orbits the barycenter of the two stars (P-type orbit).

Trinary and larger n-ary star systems are only stable when the stars beyond the 2nd are very small compared to the other. These additional stars should be handled just like any other planet.

# Answer
> 15 votes
Simplify to 2-body physics. N-body physics is in general chaotic and you cannot simulate them to a stable orbit.

**Single stars**

For systems with a single star, I'd ignore the N-body problem and just make a set of planets roughly distributed in a geometrically increasing distance from the sun. Perhaps you could have a rule that if a particularly large Planet is generated, any neighbors that are too close get destabilized and form an asteroid belt.

Planets close to the star are not necessarily rocky as is the case in our solar system.

The mass, distance and orbital speed of a planet are interlinked -- when you're randomly choosing values, make one of these (probably orbital speed) dependent on the other two.

**Binary Stars**

I didn't really know anything about habitable binary stars previously before checking Wikipedia for this answer, so read up on Habitability\_of\_binary\_star\_systems where I got some of these numbers.

1. In non circumbinary planets (the planet orbits only one of the stars in the binary system), if a planet's distance to its primary exceeds about one fifth of the closest approach of the other star, orbital stability is not guaranteed. This means if Stars A and B form a binary system with distance *AB*, you can have stable planetary orbits around either A or B at distances closer than 0.2 * *AB*. For these systems, I'd again use 2-body physics as an approximation.
2. In circumbinary systems, as long as the planet is 2-4 times further away from the binary pair as they are from each other, you can again treat this as a 2-body problem where the planet orbits around the center of mass of the two stars
3. You could also have planets orbiting the L4 and L5 Lagrange points of the binary system. I've only seen discussions of this in sci-fi settings -- I think only asteroid-sized bodies are known to occupy Lagrange points of planets in our solar system, although they can be useful for spacecraft. Technically, One of the stars needs to be significantly bigger than the other for these points to be stable, but it's up to you how much you want to let real physics get in the way of your game setting.

# Answer
> 0 votes
This is a long comment to supplement existing answers.

Given enough time, a planetary system becomes mostly planar. You may as well simplify your simulation by setting it to be planar from the start. Then you can get the rest done with the Binet equation, at least if you're using the 2-body simplification Jimmy suggested. If you neglect general relativity, the solution is analytic; if you don't, you'll need something like Runge-Kutta.

---
Tags: procedural-generation
---


title: Blur just one object in Unity

text:
# Question
Title: Blur just one object in Unity
I've recently encountered a problem where I needed to blur an object that is inside another object. I've tried several methods to fix this but none of them works properly. In the screenshot below, renders have to happen in order so that the shape is preserved but the middle portion is blurred.

My current setup is this: 3 Cameras each rendering different objects (one object per camera), the white one below is actually a depth mask and only the camera that renders it is clearing the depth mask. The others aren't clearing anything.

When I apply a blur mask on the camera that has the middle portion (Object in the blurmask layer), everything else gets blurred too (there's a background off screen which shouldn't get blurred, that's the reason for Vuforia tag). How do I solve this? Frankly, I'm absolutely stumped at this point and willing to try anything (comments are welcome too).

This is what I have right now (The longer cylinder had a depth-shader in its material which clears any 3D object parts behind it):

# Answer
This shader that I've come across in another post here seems to do the job quite well:

```
Shader "Custom/SimpleGrabPassBlur" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _BumpAmt  ("Distortion", Range (0,128)) = 10
        _MainTex ("Tint Color (RGB)", 2D) = "white" {}
        _BumpMap ("Normalmap", 2D) = "bump" {}
        _Size ("Size", Range(0, 20)) = 1
    }

    Category {

        // We must be transparent, so other objects are drawn before this one.
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque" }

        SubShader {

            // Horizontal blur
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #pragma fragmentoption ARB_precision_hint_fastest
                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                };

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    return o;
                }

                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                float _Size;

                half4 frag( v2f i ) : COLOR {
//                  half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
//                  return col;

                    half4 sum = half4(0,0,0,0);

                    #define GRABPIXEL(weight,kernelx) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x + _GrabTexture_TexelSize.x * kernelx*_Size, i.uvgrab.y, i.uvgrab.z, i.uvgrab.w))) * weight

                    sum += GRABPIXEL(0.05, -4.0);
                    sum += GRABPIXEL(0.09, -3.0);
                    sum += GRABPIXEL(0.12, -2.0);
                    sum += GRABPIXEL(0.15, -1.0);
                    sum += GRABPIXEL(0.18,  0.0);
                    sum += GRABPIXEL(0.15, +1.0);
                    sum += GRABPIXEL(0.12, +2.0);
                    sum += GRABPIXEL(0.09, +3.0);
                    sum += GRABPIXEL(0.05, +4.0);

                    return sum;
                }
                ENDCG
            }

            // Vertical blur
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #pragma fragmentoption ARB_precision_hint_fastest
                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                };

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    return o;
                }

                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                float _Size;

                half4 frag( v2f i ) : COLOR {
//                  half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
//                  return col;

                    half4 sum = half4(0,0,0,0);

                    #define GRABPIXEL(weight,kernely) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x, i.uvgrab.y + _GrabTexture_TexelSize.y * kernely*_Size, i.uvgrab.z, i.uvgrab.w))) * weight

                    //G(X) = (1/(sqrt(2*PI*deviation*deviation))) * exp(-(x*x / (2*deviation*deviation)))

                    sum += GRABPIXEL(0.05, -4.0);
                    sum += GRABPIXEL(0.09, -3.0);
                    sum += GRABPIXEL(0.12, -2.0);
                    sum += GRABPIXEL(0.15, -1.0);
                    sum += GRABPIXEL(0.18,  0.0);
                    sum += GRABPIXEL(0.15, +1.0);
                    sum += GRABPIXEL(0.12, +2.0);
                    sum += GRABPIXEL(0.09, +3.0);
                    sum += GRABPIXEL(0.05, +4.0);

                    return sum;
                }
                ENDCG
            }

            // Distortion
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #pragma fragmentoption ARB_precision_hint_fastest
                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                    float2 uvbump : TEXCOORD1;
                    float2 uvmain : TEXCOORD2;
                };

                float _BumpAmt;
                float4 _BumpMap_ST;
                float4 _MainTex_ST;

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    o.uvbump = TRANSFORM_TEX( v.texcoord, _BumpMap );
                    o.uvmain = TRANSFORM_TEX( v.texcoord, _MainTex );
                    return o;
                }

                fixed4 _Color;
                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                sampler2D _BumpMap;
                sampler2D _MainTex;

                half4 frag( v2f i ) : COLOR {
                    // calculate perturbed coordinates
                    half2 bump = UnpackNormal(tex2D( _BumpMap, i.uvbump )).rg; // we could optimize this by just reading the x  y without reconstructing the Z
                    float2 offset = bump * _BumpAmt * _GrabTexture_TexelSize.xy;
                    i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;

                    half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
                    half4 tint = tex2D( _MainTex, i.uvmain ) * _Color;

                    return col * tint;
                }
                ENDCG
            }
        }
    }
}

```

I just made another cylinder on top of the existing one (copy paste), then I enlarged that one by 5% and put a material with this shader on top of it. Though this does blur some other stuff and not just the object, it's still passable in terms of quality. Here's the result:
> 0 votes

---
Tags: unity, rendering, camera, graphic-effects, vuforia
---