# Question
Title: Drawing a pixel perfrect rectangle with stroke using shader
I'm drawing a rectangle based on input sizes and use it to mask the screen. Now I want to give it 1 pixel stroke but it doesn't rasterize to one pixel. I tried UnityPixelSnap but still no chance.

**Here's My Shader:**

```
Shader "MyShaders/Frame"
{
    Properties
    {
        [PerRendererData] _MainTex ("Frame Overlay", 2D) = "white" {}
        framesize ("Frame Sizes", Vector) = (0.5 , 0.5, 0.0 , 0.0) // z & w are just value holders
    }
    SubShader
    {
        Cull Off ZWrite Off ZTest Off Lighting Off
        Blend One OneMinusSrcAlpha

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

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

            struct v2f
            {
                float4 c : COLOR;
                float4 pos : SV_POSITION;
                float4 p : TEXCOORD;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.c = v.color;
                o.p = ComputeScreenPos(o.pos);
                return o;
            }

            sampler2D _MainTex;
            float4  framesize;

            fixed4 frag (v2f i) : SV_Target
            {
                // Base Color
                fixed4 color = i.c;
                float2 screen = i.p.xy;
                float2 screenSize = _ScreenParams.xy;

                // Get Pixel Size
                framesize.z =  (1.0f  /  screenSize.x);
                framesize.w =  (1.0f /  screenSize.y);

                // Draw Stroke
                if(screen.x > (0.5f - (framesize.x/2) - framesize.z) && screen.x < (0.5f + (framesize.x/2) + framesize.z)
                    && screen.y > (0.5f - (framesize.y/2) - framesize.w) && screen.y < (0.5f + (framesize.y/2) + framesize.w))
                color = float4(1.0, 1.0, 1.0, 0.4f);

                // Delim Using Ratios
                if(screen.x > (0.5f - (framesize.x/2) - framesize.z*.2) && screen.x < (0.5f + (framesize.x/2) + framesize.z*.2)
                    && screen.y > (0.5f - (framesize.y/2) - framesize.w*.2) && screen.y < (0.5f + (framesize.y/2) + framesize.w*.2))
                color.a = 0;

                // Apply UI Alpha
                color.rgb *= color.a;
                return color;
            }
            ENDCG
        }
    }
}

```

It should be assigned to a full width/height panel in a canvas.

**This is what happens :**

I've found this useful shader, It works perfect but I have no idea how can I use it in my shader.

I'll be very greatful if someone know how to make it work :)

# Answer
> 1 votes
OK, After days of struggling the solution was god damn easy... Using **Int2/Int4** instead of **Float2/Float4**, Pixels are integer so when you have a pixel like 550.5 it goes invisible...

**Hope this help someone else :)**

---
Tags: unity, fragment-shader
---


# Question
Title: Can I save a score as highscore, if it's a float?
So I have this infinite runner type of game, subway surfers style. I chose a method where the player doesn't move, and instead the obstacles move towards him. My score is a float and it increases as time passes. However, I'm unable to figure out how can you save this as a highscore. I tried a few methods but most of them were for int so it didn't work out. Here is what I have for the score counting. It's currently missing the save score part completely.

```
    public class GameManagerC : MonoBehaviour
{
    float score = 0;
    public float scoreMulti = 5;

    void Update()
    {
        if (isPlayerAlive == true)
        {
            score += Time.deltaTime * scoreMulti;
            scoreText.text = score.ToString("Score: 0");
        }
    }

```

EDIT: Many of you asked how I tried to implement the code I've found so here it is:

```
public float score;
public float highScore;

void Start()
    {
        score = PlayerPrefs.GetFloat("score");
        highScore = PlayerPrefs.GetFloat("highScore");
        if (score > highScore)
            highScore = score;
        StartGame();
    }

    // Update is called once per frame
    void Update()
    {
        if (isPlayerAlive == true)
        {
            score += Time.deltaTime * scoreMulti;
            scoreText.text = score.ToString("Score: 0");
        }
    }

```

# Answer
> 1 votes
First, you will want to add `public float highscore;` with your other variables at the top. Then, you will want to change the old code to this in your script. This is a very basic save system, and can easily be modified to fit the needs of the game. The comments in the code explain the script in further detail.

```
void Update()
{
    // Increases score if player is still alive
    if (isPlayerAlive == true)
    {
        score += Time.deltaTime * scoreMulti;
        scoreText.text = score.ToString("Score: 0");

        // Changes highscore to current score if current score is higher
        if (score > highscore)
        {
            highscore = score;
        }
    }
}

// Saves the score when activated, from button, script, etc.
void SaveScore()
{
    PlayerPrefs.SetFloat("score", score);
    PlayerPrefs.SetFloat("highscore", highscore);
    PlayerPrefs.Save();
}

// loads the score and highscore from the save file, if there are any
void LoadScore()
{
    score = PlayerPrefs.GetFloat("score", 0);
    highscore = PlayerPrefs.GetFloat("highscore", 0);
}

```

# Answer
> 1 votes
So I could succesfully implement a different method from this guy: https://answers.unity.com/questions/1378780/save-timer-highscore-1.html Thanks everyone for your patience and help! Currently this is able to save my highscore if I hit the restart button to reload my scene. If you stop playing and hit the play again however it resets to zero, so there's a chance this isn't what others are looking for.

Modified code:

```
public TextMeshProUGUI scoreText;
public TextMeshProUGUI highScore;
float score;

// Start is called before the first frame update
    void Start()
    {
        StartGame();
        highScore.text = PlayerPrefs.GetFloat("HighScore", 0).ToString();
    }
    // Update is called once per frame
    void Update()
    {
        if (isPlayerAlive == true)
        {
            score += Time.deltaTime * scoreMulti;
            scoreText.text = score.ToString("Score: 0");

            if (score > PlayerPrefs.GetFloat("HighScore", 0))
            {
                PlayerPrefs.SetFloat("HighScore", score);
                highScore.text = score.ToString();
            }
        }
    }

```

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


# Question
Title: How to move a player (with camera) towards a target object until camera fill target object?
I'm trying to solve this 'algorithm' problem.

I have a player and a camera on it. I want to automatically move this player towards a target object and stop it when target object completely "fit" my camera.

So my question is : how can I find target Vector3 player position, and camera rotation (up/down) to perfectly "view" an object ?

Consider that my target objects are simple Box.

Thanks

Edit: X is the "right" transform.position to "full" see target object

# Answer
*Disclaimer: I don't use Unity or C#. All Unity-specific information was obtained from the documentation and not tested.*

The field of view angle (FOV) determines the ratio of an object's size to its distance from the camera.

First, take the FOV and divide it by 2 (to get the angle from center rather than edge-to-edge, which is necessary by the next step) and, if it is in degrees, convert it to radians.

Then take the *tangent* of the angle. The tangent function tells us the *slope* — the ratio of distance to sideways movement — corresponding to the angle. (Another interpretation of this is “if an object is 1 unit away from the camera, how big will it be on screen?”)

Then, take the size of the object in terms of its radius or the maximum distance from its origin to an edge (supposing that you want the object to be as big as possible while still fitting in the camera's frame), and *divide it* by the tangent.

```
float targetCameraDistance =
  objectRadius / Mathf.Tan(fovDegrees * (Mathf.Deg2Rad / 2));

```

Now you know how far away the camera *should* be and you can steer it there.

---

Note that since screens are not square or circular, this will only perfectly fit the object in one dimension, unless the object has the same aspect ratio as the screen. Instead, the screen effectively has *two* FOV values — horizontal and vertical.

How you handle this will depend on how you intend your game's UI to scale to different screen aspect ratios, but a place to start is Unity's VerticalToHorizontalFieldOfView (and the corresponding vertical to horizontal conversion if needed).

* Simple case: If you want to the object to fit *within* the screen bounds, and your FOV is defined as a vertical FOV and your aspect ratio is always wider than tall, then you can just use the vertical FOV to get a perfect fit.
* If you want the object to fit within and you allow free window resizing so it might be taller than wide, you need to use whichever of the vertical or horizontal FOV is smaller.
* If you want the object to *completely fill the screen* (no pixel left uncovered), then you need to think about what size will fill the *corners* of the screen. That size will depend on the shape of the object, and the aspect ratio of the screen.
> 2 votes

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


# Question
Title: How can I unregister an event from another scene or another script?
This is where and how I register the event :

```
void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                DisableEnableUiTexts(true);
                SceneManager.UnloadSceneAsync(0);
                if (fadeImage != null)
                    fadeImage.SetActive(true);
                GetGameMusicVolume();
                Cursor.visible = false;
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
                MenuController.LoadSceneForSavedGame = false;
                SceneManager.LoadScene(0, LoadSceneMode.Additive);
                SceneManager.sceneLoaded += SceneManager_sceneLoaded;
                Cursor.visible = true;
            }
        }
    }

```

And the event :

```
private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
    }

```

I need to be able to unregister the event either from another scene or another script.

# Answer
> 1 votes
The solution is to unregister the event in the end of the event it self :

```
void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                DisableEnableUiTexts(true);
                SceneManager.UnloadSceneAsync(0);
                if (fadeImage != null)
                    fadeImage.SetActive(true);
                GetGameMusicVolume();
                Cursor.visible = false;
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
                MenuController.LoadSceneForSavedGame = false;
                SceneManager.LoadScene(0, LoadSceneMode.Additive);
                SceneManager.sceneLoaded += SceneManager_sceneLoaded;
                Cursor.visible = true;
            }
        }
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        fadeImage = GameObject.FindWithTag("Game Scene Fader");
        if (fadeImage != null)
            fadeImage.SetActive(false);
        audioMixer.SetFloat("gamemusicvolume", Mathf.Log(0.0001f) * 20);
        DisableEnableUiTexts(false);
        var pauseResumeMainMenuMode = FindInActiveObjectByName("MenuDefaultButtons_Canvas_Pause_Resume");
        var newFreshGameMainMenuMode = FindInActiveObjectByName("MenuDefaultButtons_Canvas_NewFreshGame_SaveGame_Not_Exist");

        newFreshGameMainMenuMode.SetActive(false);
        pauseResumeMainMenuMode.SetActive(true);

        SceneManager.sceneLoaded -= SceneManager_sceneLoaded;
    }

```

In the Update registering :

```
SceneManager.sceneLoaded += SceneManager_sceneLoaded;

```

In the bottom of the event unregistering :

```
SceneManager.sceneLoaded -= SceneManager_sceneLoaded;

```

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


# Question
Title: PBR Graph option not showing up in Unity
I downloaded the URP render pipeline into an existing project of mine (created using the 3D template) to try out shader graphs. All of the guides and tutorials I'm following use an option called the "PBR Graph". However, I can not find that option in Unity. Did they change the name of the graph? How can I get access to it?

When I open up a new project using the URP template, I have the option to choose the PBR graph, but not in my original project, so do I have to create the project with the URP template to begin with?

The version I am using is 2020.2.3.

# Answer
As you can see here, Unity removed that option in the 10.0.x version of shader graphs, and added cross-platform master nodes to the master stack as long as the shaders are compatible with both the Universal Render Pipeline (URP) and the High Definition Render Pipeline (HDRP). Unity did not remove the option entirely however, and people can still use them, according to what Unity has said in the website above.

> In URP, you can now find all PBR Master Node settings in the URP Lit Target. The Unlit Master Node settings are in the URP Unlit Target. These settings are the same, and the final shader should appear the same as before the upgrade.
> 3 votes

---
Tags: unity, unity-shader-graph
---


# Question
Title: Looking for a game engine to make a game like "Ikariam" or "Ogame"
I'm an IT student and currently in my spare time I want to start a project. I would like to make a game that resembles a browser games like "Ikariam" or "OGame". I don't want this game to be a browser game, but It has to work like the games above with a couple of players.

What game engine would you suggest?

# Answer
Technically speaking, it’s all a matter of personal preference. Nearly all game engines have the ability to create the games you listed above. But, here’s a list of some of the engines best suited for what you want:

1. **Godot** is an open source game engine that anyone can modify. It can compile games for nearly all devices. It is coded in *GDScript*, a Python like programming language.
2. **Unreal Engine** is a free game engine created by Epic Games. It can also compile games for most devices. It uses *C++* as the main programming language, and is commonly used for online games.
3. **Unity** is a game engine that is licensed in three different ways: Free, Plus, and Pro. The free version includes most, but not all features of the others, such as watermark removal. But, it is one of the most powerful and easy to use engines, that can create games for basically every device. It uses *C#* as the main language.

There are many other different game engines, but this is just a list of my preferred programs.
> -3 votes

---
Tags: c++, 2d, game-design, architecture, multiplayer
---


# Question
Title: Calling a function from Super is getting an error
I am following GameDev.tv's unreal C++ course, but I am getting an error that is causing my compiler to fail. I'm coding a player controller, and I think I followed all the steps right but when I call the `GameHasEnded()` function from Super in the playercontroller.cpp, It gets an error saying: `anything followed by '::' must be followed by a class or namespace.`

Here is my .h file which has no known compiler errors.

```
    #pragma once

#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "ShooterPlayerController.generated.h"

/**
 *
 */
UCLASS()
class SIMPLESHOOTER_API AShooterPlayerController : public APlayerController
{
    GENERATED_BODY()
public:
    virtual void GameHasEnded(class AActor *EndGameFocus = nullptr, bool bIsWinner = false) override;
};

```

Here is my .cpp file with the problem.

```
// Fill out your copyright notice in the Description page of Project Settings.

#include "ShooterPlayerController.h"

void GameHasEnded(class AActor *EndGameFocus, bool bIsWinner)
{
    //this is the problem super
    Super::GameHasEnded(EndGameFocus, bIsWinner);
}

```

I have a lot of other scripts, but I don't think they're related to the problem. I'm using Unreal 4.26, and Visual Studio 2019. I have no idea why this is getting an error, the code is exactly the same as the instructor’s code.

# Answer
Since I didn't have much work done on this class, I decided to delete it and start over. This done, I added the same code and got no errors. My guess is that Unreal had a bug and didn't generate some code Super needs to work. Hopefully this will help someone.
> 0 votes

---
Tags: unreal-4, visual-studio, error-management
---


title: Multipurpose buttons

text:
# Question
Title: Multipurpose buttons
As in the title, I am trying to figure out how to use a button for multiple purposes in Unity.

In my specific case for instance, I am currently using the joystick button 0 (the A button) to perform a simple melee attack:

```
if (Input.GetButtonDown("Fire1") && currentState != PlayerState.attack && currentState != PlayerState.stagger)
//second clause because I do not want to indefinitely attack every frame
{
    StartCoroutine(GetComponent<Player_Melee>().FirstAttack());
}

```

In the conditions I make sure that I am pressing the right button and determining in which state my player is (the state is then changed in the attack coroutine). In order to interact with a given object, I created a trigger to check that the player is within range to inspect the object:

```
if (Input.GetButtonDown("Interact_Alt") && playerInRange)
{
    if (dialogueBox.activeInHierarchy)
    {
        dialogueBox.SetActive(false);
    }
    else
    {
        dialogueBox.SetActive(true);
        dialText.text = dialogue;
    }
}

```

In the Input manager settings in unity, I set the 'Interact\_Alt' button to be the same as the 'Fire1' used in the attack script. The scripts actually work, however whenever I check an object I also perform an attack. How can i make so that when I want to inspect an object I do not attack?

I was considering create a new finite state similarly to the one I use to attack e.g. 'PlayerState.interact', but then I was wondering, how would unity give the priority to which command to use?

Another alternative would be to check if I am in the range of some object when I want to attack and if within range it inspects the object instead, but it seems to me a much more convoluted solutions.

How should I solve this?

# Answer
> 0 votes
Solved. For information, the solution i used was to create a boolean attached to the player that upon entering in the trigger area of the object in question would have been turned true and prevent to use the button to perform an attack, allowing instead to only inspect the object.

---
Tags: unity, c#, input, control, statemachine
---


# Question
Title: Unity3d Sprite Mask Nonexistent in Build
I am developing a 2D game which uses sprite masks to limit the player's information to a circle around them. The feature works perfectly in the Unity Editor. It can be disabled and reenabled, have the shape of the mask itself change, and more.

However, whenever I build the project and run the executible the screen is blank. If I disable the sprite masks altogether, the sprites are all visible. I have debugged Unity3d builds before, but that was specifically looking at variables as they changed during the execution of the program.

Does anyone have any specific knowledge related to sprite masks or have any idea why this would occur? I can provide more information if necessary. My current thought is that the sprite mask is masking everything for some reason. It's weird to me though that it would only break in the build.

All help is appreciated.

# Answer
> 1 votes
I had a similar issue before. It seemed to be related to the mask custom range. For example if my target order in layer is 99, then I have to set the range as \[98,100\]alt text

If I set the range as \[98,99\], the editor works fine, but the build shows no effect.

Here's a link to the Unity forum post where I posted this in reply to a similar problem.

---
Tags: unity, sprites, debugging, build-process
---


# Question
Title: Libgdx - overlapping stages - textbutton unclickable
I've created a few TextButtons for a menu that render on top of another stage area, however the textbuttons that i've created for menu aren't clickable or don't provide any events. The MenuComponent class I created is being instantiated/rendered in another class.

The buttons show up, just unable to click anything or get any events from the buttons. Can someone take a look at the code I provided and maybe show me mistakes or something I forgot to implement to make them work?

MenuComponent Class:

```
   @Override
    public void create() {
        batch = new SpriteBatch();
        this.stage = new Stage();
        setRenderer(new ShapeRenderer());
        Gdx.input.setInputProcessor(stage);
        menuUp = new Texture("assets/ui/disengage.png");
        menuDown = new Texture("assets/ui/disengagePressed.png");

        Table menuWindow = new Table();
        this.menuWindow = menuWindow;
        menuWindow.setPosition(675,160);
        //Button View
        SpriteDrawable upFormat=new SpriteDrawable(new Sprite(createRoundPixMap(Color.BLACK,100, 30,10)));
        SpriteDrawable downFormat=new SpriteDrawable(new Sprite(createRoundPixMap(Color.RED,100, 30,10)));
        SpriteDrawable checkedFormat=new SpriteDrawable(new Sprite(createRoundPixMap(Color.BLACK,100, 30,10)));
        TextButtonStyle buttonStyle=new TextButtonStyle(upFormat, downFormat, checkedFormat, new BitmapFont());
        //Individual Buttons
        lobbyButton = new TextButton("Back to Lobby",buttonStyle);
        mapsButton = new TextButton("List Maps",buttonStyle);
        menuWindow.add(lobbyButton).pad(3,0,3,0).row();
        menuWindow.add(mapsButton).pad(3,0,3,0).row();
        menuWindow.setVisible(false);
        stage.addActor(menuWindow);
        stage.getRoot().setPosition(65,150);
    }

    @Override
    public void update() {
    }

    @Override
    public void render() {
        batch.begin();
        batch.draw((menuButtonIsDown)?menuDown:menuUp, MENU_buttonX, MENU_buttonY);

        batch.end();
        stage.act();
        stage.draw();
    }

```

Part of the class its being rendered/created in:

```
    @Override
    public void create() {
        generator = new FreeTypeFontGenerator(Gdx.files.internal("assets/font/Roboto-Regular.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.size = 10;
        parameter.spaceX = 0;
        parameter.shadowColor = new Color(0, 0, 0, 0.5f);
        parameter.borderColor = Color.BLACK;
        parameter.borderWidth = 1;
        parameter.borderStraight = true;
        parameter.shadowOffsetY = 1;
        parameter.shadowOffsetX = 1;
        font = generator.generateFont(parameter);

        renderer = new ShapeRenderer();
        this.batch = new SpriteBatch();
        sea = context.getManager().get(context.getAssetObject().sea,Texture.class);
        sea.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight() - 200);
        this.mainmenu = new MenuComponent(context, this);
        mainmenu.create();
    }

    @Override
    public void render() {
        batch.setProjectionMatrix(camera.combined);
        batch.begin();

        Gdx.gl.glViewport(0,200, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() - 200);

        mainmenu.render();
    }

```

# Answer
Instead of having two stages, just have one stage, and have multiple tables.

That way you can set any actors in the stage (tables, buttons, labels) that are in front of your text buttons to be untouchable. Example:

```
Label lBasketEndlessMode = new Label("(Endless Mode)", AssetLoader.defaultSkinSmall);
lBasketEndlessMode.setPosition(0, 0);
lBasketEndlessMode.setTouchable(Touchable.disabled);
stage.addActor(lBasketEndlessMode);

```

This allows you to display anything you want, and still have anything behind it be able to take input.
> 0 votes

---
Tags: libgdx, menu
---


title: Fresnel shader excluding one axis

text:
# Question
Title: Fresnel shader excluding one axis
I'm trying to get an outline like effect shown on the right in this video. Using fresnel seems to make the whole thing go white at certain angles. How do I prevent that? I'm using amplify to make this. Here's my current setup

# Answer
> 0 votes
Figured it out! this is the setup I used

---
Tags: shaders
---


# Question
Title: Getting a TileMap wrapping as a toroid on player movement
**\[libgdx version 1.9.13 - Desktop Game\]**

This question seems to have been asked many times, but I have yet to find a decent solution. I want to display a map without edges, where the player moves in all directions on a 'world' which is toroidal.

I load my tiles into cells of an `OrthogonalTiledMapRenderer`, which I then render. This gives me a map which draws in the game window - works fine - but it has edges. The player can walk up to the edge of map.

So my questions:

1. How do I get a tiled map to draw without edges (I.E. no background color around edge of tile map, as per attached screen shot, which shows character about to walk off the map)

2. How do I then make the map *toroidal* \- so the player moves off left map edge and is moved to right edge. Same for top/bottom. I can set the players coordinates to do this, but screen 'jumps' to the other edge.

So if the player continually presses a single up/down/left/right key, eventually they will come back to their starting position.

# Answer
Wrapping a tiled map can be achieved by rendering the `TiledMap` multiple times if the camera position is closer to the borders of the map than the size of the camera viewport.

So for example on a map that is 16 world units wide and viewed by a camera with a viewport width of 8 and the camera is at `X=2` then the map needs to first be renderer as normal using the camera `(2, y)`, and then once more with a camera that is at `(16 + x, y)` (or `(mapWidth + x, y)`), because 2 is less than 8 so we know that the camera position is far enough to the left for us to require to render the right-most part of the map to the left of the map.

For when x is close to the right-hand side of the map the position is `(x - mapWidth, y)`.

The same is replicated for `y` and there's also the case when both `x` and `y` are close to the edges, in which cases the map needs to be rendered once more for the corner.

It's also important to wrap the position of the main camera to always be *inside* of the map:

```
    if (position.x < 0.0f)
        position.x = mapWidth + position.x;
    if (position.x > mapWidth)
        position.x = mapWidth - position.x;

    if (position.y < 0.0f)
        position.y = mapHeight + position.y;
    if (position.y > mapHeight)
        position.y = mapHeight - position.y;

```

When the wrapping is done the "*extra*" rendering of the `TiledMap` might look like this:

```
    // Render normally first
    camera.update();
    mapRenderer.setView(camera);
    mapRenderer.render();

    // Now render the extra views depending on where the camera is
    if (position.x < camera.viewportWidth)
    {
        wrapCamera.position.set(mapWidth + position.x, position.y, 1.0f);
        wrapCamera.update();
        mapRenderer.setView(wrapCamera);
        mapRenderer.render();

        if (position.y < camera.viewportHeight)
        {
            wrapCamera.position.set(mapWidth + position.x, mapHeight + position.y, 1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();
        }

        if (position.y > mapHeight - camera.viewportHeight)
        {
            wrapCamera.position.set(mapWidth + position.x, position.y - mapHeight,1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();
        }
    }

    if (position.x > mapWidth - camera.viewportWidth)
    {
        wrapCamera.position.set(position.x - mapWidth, position.y, 1.0f);
        wrapCamera.update();
        mapRenderer.setView(wrapCamera);
        mapRenderer.render();

        if (position.y < camera.viewportHeight)
        {
            wrapCamera.position.set(position.x - mapWidth, mapHeight + position.y, 1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();
        }

        if (position.y > mapHeight - camera.viewportHeight)
        {
            wrapCamera.position.set(position.x - mapWidth, position.y - mapHeight,1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();
        }
    }

    if (position.y < camera.viewportHeight)
    {
        wrapCamera.position.set(position.x, mapHeight + position.y, 1.0f);
        wrapCamera.update();
        mapRenderer.setView(wrapCamera);
        mapRenderer.render();
    }

    if (position.y > mapHeight - camera.viewportHeight)
    {
        wrapCamera.position.set(position.x, position.y - mapHeight,1.0f);
        wrapCamera.update();
        mapRenderer.setView(wrapCamera);
        mapRenderer.render();
    }

```

In the above example there are two `Camera`s, one called `camera` which is the main camera that follows the player, and `wrapCamera` that has the same viewport size as `camera` but has a position that is updated for each wrapped view that needs to be rendered.

Complete source code for the gif is:

```
package com.bornander.sandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.BatchTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;

public class MyGdxGame extends ApplicationAdapter {
    TiledMap map;
    float mapWidth;
    float mapHeight;

    OrthogonalTiledMapRenderer mapRenderer;
    OrthographicCamera camera;
    OrthographicCamera wrapCamera;
    SpriteBatch batch;
    Texture tank;
    Vector2 position = new Vector2();
    Vector2 direction = new Vector2(1, 0);
    float speed = 0.0f;

    @Override
    public void create () {
        float aspectRatio = (float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight();
        // Set camera to view 16 tiles wide
        camera     = new OrthographicCamera(16, 16 * (1.0f / aspectRatio));
        wrapCamera = new OrthographicCamera(16, 16 * (1.0f / aspectRatio));
        batch = new SpriteBatch();
        tank = new Texture("tank_huge.png");
        TmxMapLoader mapLoader = new TmxMapLoader();
        map = mapLoader.load("map.tmx");
        mapWidth = map.getProperties().get("width", Integer.class);
        mapHeight = map.getProperties().get("height", Integer.class);
        mapRenderer = new OrthogonalTiledMapRenderer(map, 1.0f / 128.0f);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (Gdx.input.isKeyPressed(Input.Keys.A))
            direction.rotate( 90f * Gdx.graphics.getDeltaTime());
        if (Gdx.input.isKeyPressed(Input.Keys.D))
            direction.rotate(-90f * Gdx.graphics.getDeltaTime());
        if (Gdx.input.isKeyPressed(Input.Keys.W))
            speed = Math.min(8.0f, speed + Gdx.graphics.getDeltaTime());

        if (Gdx.input.isKeyPressed(Input.Keys.S))
            speed = Math.max(-4.0f, speed - Gdx.graphics.getDeltaTime());

        position.add(direction.x * speed * Gdx.graphics.getDeltaTime(), direction.y * speed * Gdx.graphics.getDeltaTime());

        if (position.x < 0.0f)
            position.x = mapWidth + position.x;
        if (position.x > mapWidth)
            position.x = mapWidth - position.x;

        if (position.y < 0.0f)
            position.y = mapHeight + position.y;
        if (position.y > mapHeight)
            position.y = mapHeight - position.y;

        System.out.println(String.format("(%.2f, %.2f)", position.x, position.y));
        camera.position.set(position, 1.0f);

        // Render normally first
        camera.update();
        mapRenderer.setView(camera);
        mapRenderer.render();

        // Now render the extra views depending on where the camera is

        if (position.x < camera.viewportWidth)
        {
            wrapCamera.position.set(mapWidth + position.x, position.y, 1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();

            if (position.y < camera.viewportHeight)
            {
                wrapCamera.position.set(mapWidth + position.x, mapHeight + position.y, 1.0f);
                wrapCamera.update();
                mapRenderer.setView(wrapCamera);
                mapRenderer.render();
            }

            if (position.y > mapHeight - camera.viewportHeight)
            {
                wrapCamera.position.set(mapWidth + position.x, position.y - mapHeight,1.0f);
                wrapCamera.update();
                mapRenderer.setView(wrapCamera);
                mapRenderer.render();
            }
        }

        if (position.x > mapWidth - camera.viewportWidth)
        {
            wrapCamera.position.set(position.x - mapWidth, position.y, 1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();

            if (position.y < camera.viewportHeight)
            {
                wrapCamera.position.set(position.x - mapWidth, mapHeight + position.y, 1.0f);
                wrapCamera.update();
                mapRenderer.setView(wrapCamera);
                mapRenderer.render();
            }

            if (position.y > mapHeight - camera.viewportHeight)
            {
                wrapCamera.position.set(position.x - mapWidth, position.y - mapHeight,1.0f);
                wrapCamera.update();
                mapRenderer.setView(wrapCamera);
                mapRenderer.render();
            }
        }

        if (position.y < camera.viewportHeight)
        {
            wrapCamera.position.set(position.x, mapHeight + position.y, 1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();
        }

        if (position.y > mapHeight - camera.viewportHeight)
        {
            wrapCamera.position.set(position.x, position.y - mapHeight,1.0f);
            wrapCamera.update();
            mapRenderer.setView(wrapCamera);
            mapRenderer.render();
        }

        batch.setProjectionMatrix(camera.combined);
        batch.begin();

        batch.draw(
                tank,
                position.x-0.5f,
                position.y-0.5f,
                0.5f, 0.5f, /* origin */
                1.0f, 1.0f, /* width, height */
                0.5f, 0.5f, /* scale */
                direction.angle() + 90,
                0, 0,
                tank.getWidth(), tank.getHeight(),
                false, false /* flip */);

        batch.end();
    }

}

```
> 2 votes

---
Tags: 2d, libgdx, tilemap
---


# Question
Title: 2D shadow from polar coordinates has hard cut-off at a certain radius
I'm trying to cast shadows from a 1D texture that goes from white to back according to the distance given by an occlusion map. That part I think I got it right. The problem lies on the algorithm to check if a given pixel is in shadow.

As you can see, the outer limits are clamped, as if it is in shadow. The result I would expect is that it would slowly fade. I don't know why my shader yields this result.

Here is the shader I use for casting the shadows:

```
#version 330
#define numTextures 32
#define PI 3.14

in vec2 TexCoords;
in vec4 pass_colors;
in vec4 fragPos;
in vec4 worldFragPos;
in mat4 outWorld;

out vec4 color;
uniform vec4 ambientColor;
uniform sampler2D texture_diffuse;
uniform float radius;
uniform vec2 screenResolution;
uniform int lightCounter;

struct LightData
{
    float radius;
    vec3 position;        //light position, normalized
    vec4 color;      //light RGBA -- alpha is intensity
};

uniform LightData lights[numTextures];
uniform sampler2D shadows;

float n3ddistance(vec3 first_point, vec3 second_point)
{
    float x = first_point.x-second_point.x;
    float y = first_point.y-second_point.y;
    float val = x*x + y*y;
    return sqrt(val);
}

float sample(vec2 coord, float r) {
    return step(r, texture(shadows, coord).r);
}

float GetShadow(int lightIndex)
{
    vec2 dir = fragPos.xy - lights[lightIndex].position.xy;
    dir /= lights[lightIndex].radius / 2;
    //rectangular to polar
    dir.y *= -1;
    vec2 norm = dir.st;// * 2.0 - 1.0;
    float theta = atan(norm.y, norm.x);
    float r = length(norm);
    float coord = (theta + PI) / (2.0*PI);

    //the tex coord to sample our 1D lookup texture
    //always 0.0 on y axis
    vec2 tc = vec2(coord, 0.0);

    return sample(tc, r);
}

vec3 GetColor(int lightIndex)
{
    float dst = n3ddistance(lights[lightIndex].position.xyz, fragPos.xyz);
    float intensity = clamp(1.0 - dst / lights[lightIndex].radius, 0.0, 1.0);
    vec3 color = lights[lightIndex].color.rgb * intensity * GetShadow(lightIndex);
    return color;
}

void main()
{

    vec4 DiffuseColor = vec4(texture(texture_diffuse, TexCoords)) * pass_colors;

    vec3 sum = vec3(0);
    for(int i = 0; i < lightCounter; i++)
        sum += GetColor(i);

    vec3 intensity = ambientColor.xyz + sum;
    vec3 finalColor = DiffuseColor.rgb * intensity;
    color = vec4(finalColor.rgb, DiffuseColor.a);
    if (color.a <= 0.0)
        discard;
}

```

And here is the shader responsable for writing to that 1D texture

```
#version 330

#define PI 3.14159265359

in vec2 TexCoords;
in vec4 fragPos;
in vec3 lightPos;

out vec4 color;

uniform float radius;
uniform sampler2D occlusion;

void main()
{
    float distance = 1;

    for (float y=0.0; y < radius; y += 1.0)
    {
        vec2 norm = vec2(TexCoords.s, y / radius) * 2.0 - 1.0;
        float theta = PI * 1.5 + norm.x * PI;
        float r = (1.0 + norm.y) * 0.5;
        vec2 coord = vec2(-r * sin(theta), -r * cos(theta))/2.0 + 0.5;

        vec4 data = texture(occlusion, coord);
        float dst = y/radius;
        float caster = data.r;
        if (caster > 0.75) {
            distance = min(distance, dst);
            break;
        }
    }
  color = vec4(vec3(distance), 1.0);
}

```

How can I get a smooth fall-off instead of this sudden stop at a particular radius?

# Answer
> 0 votes
So It seems I has to use this line

```
 return sample(tc, r)* smoothstep(1.0, 0.0, r);

```

which solves the problem...Thank you!

---
Tags: opengl, 2d, glsl, shadows, shadow-mapping
---


title: Item counter unity

text:
# Question
Title: Item counter unity
How is it possible that a create an item counter in unity?

My current Scripts -

Counter.cs

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

public class Counter : MonoBehaviour
{
    public int ScoreAmount;
    private Text ScoreText;
    // Start is called before the first frame update
    void Start()
    {
        ScoreText = GetComponent<Text>();
        ScoreAmount = 0;
    }

    // Update is called once per frame
    void Update()
    {
        ScoreText.text = "" + ScoreAmount;
    }

```

Where I have a text UI called ScoreText

ItemPickup.cs

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

public class ItemPickup : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Fruit"))
        {
            Debug.Log("Picking up fruit...");
            Counter.ScoreAmount += 1;
        }
    }
}

```

But I get this error

```
"Assets/ItemPickup.cs(12,13): error CS0120: An object reference is required for the non-static field, method, or property 'Counter.ScoreAmount'"

```

How do I fix it please?

# Answer
The problem is that Unity allows you to put your `Counter` script on as many gameObjects as you want, and each one would have an own `ScoreAmount`. So `Counter.ScoreAmount` is ambiguous. Unity doesn't know which one you mean.

So how could you fix that?

## Solution A: Make ScoreAmount static.

When you declare a variable as `static`, then all instances of that script share the same value. That allows you to refer to that variable by the class name instead of any particular instance. So when you change `public int ScoreAmount;` to `public static int ScoreAmount;`, then you should get the behavior you want.

But while this might solve the problem for now, it might cause some problems later. For example when you want for some reason create a second object with an own count, like a 2nd player or an AI actor which can also collect things and count them.

## Solution B: Make the ItemPickup get the component on the same object.

However, looking at your code, it seems like the `ItemPickup` component is on the gameObject which actually does the picking (and not on the item which can be picked up, which is why I would have done it, but I digress...). It is not clear from your question where the Counter component is housed, but if it is on the same gameObject, then you can use `GetComponent<Counter>()` to get a reference to it.

```
void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Fruit"))
    {
        Debug.Log("Picking up fruit...");
        GetComponent<Counter>().ScoreAmount += 1;
    }
}

```

## Solution C: Give the FruitPickup script a reference to the Count script.

This solution allows multiple Count script, but does not requires that they are on the gameObject which does the collecting. So you can put it on a manager object or a UI element.

Give the `FruitPickup` script a variable `public Count count` and assign the object with the Count script using the inspector.

## Solution D: Put the ItemPickup script on the items and have it detect which object collected it.

This is how I would do this, but it requires you to approach this a bit differently.

1. Put the `Counter` object on the player
2. Make the collider of the player **not** a trigger
3. Put the `FruitPickup` component on object which can be picked up
4. Make the colliders of the fruits triggers
5. Write the `FruitPickup` class like this:

```
    void OnTriggerEnter2D(Collider2D other)
    {
        Counter counter = other.GetComponent<Counter>()
        if (counter != null) // the object is able to count fruit
        {
            counter.ScoreAmount += 1; // increase score of the object which collected this
            Destroy(gameObject); // self-destruct
        }
    }

```

But now the Counter loses its connection to the Text element it used to control. The reason is that it used the method B to get a reference to its own Text component, which now won't work anymore. How do we fix that? By using the solution C and tell it which text object to use to visualize its state. Make the ScoreText variable `public` and remove its initialization in Start:

```
public class Counter : MonoBehaviour
{
    public int scoreAmount;
    public Text scoreText;
    void Start()
    {
        scoreAmount = 0;
    }

    void Update()
    {
        if (scoreText != null) {
             scoreText.text = scoreAmount.ToString();
        }
    }
}

```

Then go to the Inspector and drag the Text object which you want to visualize the score on the "Score Text" inspector field of the Counter component.

Although personally I recommend to separate mechanics from UI visualization, so I would probably use a 3rd script for UI elements for visualizing the state of an arbitrary Counter on its own Text. But that's a different topic.

## Why do I recommend option D?

* an object should contain the components which dictate its own behavior, not that of other things. Increasing the player's score and then disappearing is something the fruits do, not something the player-character does. So this behavior should be defined in a component of the Fruit gameObjects. Also, this allows you to do things like making the amount by which a fruit increases the player's score a public variable of that script. So you can create prefabs for different fruits which increase the player's score by different amounts.
* I would avoid putting a trigger on the player. Triggers should be on the objects in the world which other objects interact with. Not on the objects which do the interacting.
* detecting what the other object is in a collision by seeing what components it has allows you to create very modular and reusable code. The fruit doesn't care if whatever picks it up is a "Player". It only cares that it has the components which require it to be able to collect it. So you can have multiple players which collect fruit and even NPC characters which collect fruit, and you don't need to change anything about the fruits to do that.
> 2 votes

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


# Question
Title: Reopening Unity project after two week break, project is trashed
I've spent about 6 months using Unity nearly every day. Then I take a two-week break, re-open my project, and the entire build is trashed.

There are 166 errors, here are a few:

```
Assets\TextMesh Pro\Examples & Extras\Scripts\ChatController.cs(6,14): error CS0101: The
namespace '<global namespace>' already contains a definition for 'ChatController'

private Renderer renderer;Assets\Scripts\Board\Tile.cs(23,22): warning CS0108: 'Tile.renderer'
hides inherited member 'Component.renderer'. Use the new keyword if hiding was intended.

Assets\TextMesh Pro\Examples & Extras\Scripts\ObjectSpin.cs(8,18): error CS0101: The namespace
'TMPro.Examples' already contains a definition for 'ObjectSpin'

```

I've re-imported Text Mesh Pro Examples & Extra, restarted my project multiple times, to no avail. This is very concerning to me because it makes me feel like Unity is not a stable plaform ... Are Unity projects attacked by gremlins if not used every couple days?

# Answer
> 1 votes
To answer your question, Unity projects are not corrupted after being left for a couple days. But, this can depend on a few factors, such as if you are using a LTS **(Long Term Support)** version of Unity or a standard version that updates commonly. If you are using a version that updates commonly, certain packages that worked one day can stop working the next, due to bugs, and so on. This same issue you are having has happened to me before. I recommend removing all your packages from the `Package Window` and removing the package cache. This worked for me.

---
Tags: unity
---


# Question
Title: Is it possible to get object rotation in a shader for dynamically batched objects?
All the batched objects **have the same rotation**. To simulate the effect of directional light I need to determine the object sides actual (world) directions. Normally I would use `unity_ObjectToWorld` & `unity_ObjectToWorld` for that, which is not possible when the objects are batched.

Is it possible to pass the object rotation to the shader in one action (since it's the same for all of them) without breaking the batching?

---

This is a simplified shader example (here I use colors instead of light/shadow effect and only 2 sides instead of 4):

```
Shader "Test/UnlitTest"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _TopColor ("TopColor", Color) = (1, 0, 0, 1)
        _BottomColor ("_BottomColor", Color) = (0, 0, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        ZTest Off
        ZWrite Off
        Lighting Off
        Cull Off
        Fog { Mode Off }

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

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            fixed4 _TopColor, _BottomColor;

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

            struct fragData
            {
                float2 uv : TEXCOORD0;
                float2 uvW : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            fragData vert (vertData v)
            {
                fragData f;
                f.vertex = UnityObjectToClipPos(v.vertex);
                f.uv = TRANSFORM_TEX(v.uv, _MainTex);
                f.uvW = mul(unity_ObjectToWorld, f.uv);
                return f;
            }

            fixed isTransparentPixel(fixed2 uv)
            {
                return step(tex2D(_MainTex, uv).a, 0.0);
            }

            fixed isEdgePixel(fixed2 uv)
            {
                uv = mul(unity_WorldToObject, uv); // back to object space
                return isTransparentPixel(uv);
            }

            fixed4 frag (fragData f) : SV_Target
            {
                fixed isTransparent = isTransparentPixel(f.uv);
                clip(-isTransparent);

                fixed4 c = tex2D(_MainTex, f.uv);
                float2 borderSize = float2(3, 3); // border size in tex pixels
                float dy = borderSize.y * _MainTex_TexelSize.y;
                fixed3 borderColor = fixed3(0, 0, 0);
                float borderColorsCount = 0;
                float2 uvW = f.uvW; // UV in the world space

                // Top edge:
                fixed isEdge = isEdgePixel(uvW + float2(0, dy));
                borderColor += isEdge * _TopColor.rgb;
                borderColorsCount += isEdge;

                // Bottom edge:
                isEdge = isEdgePixel(uvW + float2(0, -dy));
                borderColor += isEdge * _BottomColor.rgb;
                borderColorsCount += isEdge;

                fixed noBorderColor = step(length(borderColor), 0);
                fixed hasBorderColor = 1 - noBorderColor;
                c.rgb = c.rgb * noBorderColor + hasBorderColor * borderColor / max(borderColorsCount, 1);
                return c;
            }
            ENDCG
        }
    }
}

```

It gets a semi-transparent image as a texture. The image is completely transparent at the edges and contains an opaque shape in the center.

The shader colors the top edges of the non-transparent shape in red and the bottom ones in yellow. It uses `unity_WorldToObject` & `unity_ObjectToWorld` to check the edges facing directions in the world space.

# Answer
> 0 votes
Here is an edited version of the code of the resolved question:

**C#**

```
using UnityEngine;

[DisallowMultipleComponent]
public class UnlitTest : MonoBehaviour
{
#pragma warning disable CS0649

    [SerializeField]
    private MeshFilter _meshFilter;

#pragma warning restore CS0649

    private void OnValidate()
    {
        SetNormals();
    }

    private void SetNormals()
    {
        Mesh mesh = _meshFilter.sharedMesh;
        Vector3[] normals = new Vector3[mesh.vertexCount];

        for (int i = 0; i < mesh.vertexCount; i++)
        {
            normals[i] = Vector3.up;
        }

        mesh.normals = normals;
    }
}

```

**Shader**

```
Shader "Test/UnlitTest"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _TopColor ("TopColor", Color) = (1, 0, 0, 1)
        _BottomColor ("_BottomColor", Color) = (0, 0, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        ZTest Off
        ZWrite Off
        Lighting On
        Cull Off
        Fog { Mode Off }

        Blend SrcAlpha OneMinusSrcAlpha

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

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;
            fixed4 _TopColor, _BottomColor;

            struct vertData
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float3 normal : NORMAL;
            };

            struct fragData
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float3 up : NORMAL;
            };

            fragData vert (vertData v)
            {
                fragData f;
                f.vertex = UnityObjectToClipPos(v.vertex);
                f.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                f.up = mul(unity_ObjectToWorld, v.normal);
                return f;
            }

            fixed isTransparentPixel(fixed2 uv)
            {
                return step(tex2D(_MainTex, uv).a, 0.0);
            }

            fixed isEdgePixel(fixed2 uv)
            {
                return isTransparentPixel(uv);
            }

            fixed4 frag (fragData f) : SV_Target
            {
                float2 borderSize = float2(3, 3); // border size in tex pixels
                float dx = borderSize.x * _MainTex_TexelSize.x;
                float dy = borderSize.y * _MainTex_TexelSize.y;
                fixed3 borderColor = fixed3(0, 0, 0);
                float borderColorsCount = 0;
                fixed2 uv = f.uv;

                // Top edge:
                float2 dTop = float2(-f.up.x * dx, f.up.y * dy);
                fixed isEdge = isEdgePixel(uv + dTop);
                borderColor += isEdge * _TopColor;
                borderColorsCount += isEdge;

                // Bottom edge:
                float2 dDown = dTop * -1;
                isEdge = isEdgePixel(uv + dDown);
                borderColor += isEdge * _BottomColor;
                borderColorsCount += isEdge;

                fixed noBorderColor = step(length(borderColor), 0);
                fixed hasBorderColor = 1 - noBorderColor;
                fixed4 c = tex2D(_MainTex, uv);
                c.rgb = c.rgb * noBorderColor + hasBorderColor * borderColor / max(borderColorsCount, 1);
                return c;
            }
            ENDCG
        }
    }
}

```

---
Tags: unity, batching
---


# Question
Title: How can i change the hit distance of RaycastHit?
I'm using this script to send a raycast from the center of the camera to objects. It's working fine but only if i'm getting close enough to objects. But for example if it's npc person i want to be able to detect him as "Interactable" from a more distance. How can i change/set the hit distance ?

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

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
            if (hit.transform.tag == "Interactable")
            {
                print("I'm looking at " + hit.transform.name);
            }
            else
                print("I'm looking at nothing!");
    }
}

```

# Answer
> 2 votes
If you look at the documentation at https://docs.unity3d.com/ScriptReference/Physics.Raycast.html you'll find that the function is overloaded. The very next parameter you can add is distance:

```
Physics.Raycast(ray, out hit, 100)

```

# Answer
> 1 votes
Ok, so if you are aware of the Vector3 you are passing as a parameter you are giving to **Camera.ViewportToRay()**, that is a normalized space (I think that it is a Moebius Space). You are giving to z a 0 parameter, so the ray would reach the start of the viewport, you may play with values between 0.1-1.0 for z, to deal with distance.

Another solution, would be to instance a Ray using the Camera's position as reference, but without using ViewportToRay().

Something like this (you may use transform.forward, instead of TransformDirection):

```
    public float distance;  /// Distance of your Ray.
    public Camera camera;   /// The camera (duh).

    void Update()
    {
        Ray ray = new Ray(camera.transform.position, camera.transform.TransformDirection(0f, 0f, distance));
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        if (hit.transform.tag == "Interactable")
        {
            print("I'm looking at " + hit.transform.name);
        }
        else print("I'm looking at nothing!");
    }

```

# Answer
> 0 votes
Thank you! This is what worked for me:

```
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);

```

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


# Question
Title: In Unity, why does DrawProceduralNow work in OnRenderObject but DrawProcedural does not?
In Unity, if I call `DrawProcedural` (or one of its variants) from `Update()` it works fine, but if I make the exact same call from `OnRenderObject()` it draws nothing. (It also doesn't work from `OnPreRender` or `OnPostRender`).

HOWEVER, `DrawProceduralNow()` works fine from all of these functions.

Why is that so? Is it documented somewhere? What can I do to make `DrawProcedural` and variants work in `OnRenderObject`? What is different about `DrawProceduralNow` that makes it work? (Yes, I have tried using `material.SetPass(0)` in the `DrawProcedural` version and it still renders nothing.

I understand that the `OnRender` functions are called later in the frame and some graphics state is different at that point, but it seems like `DrawProcedural` is exactly the kind of thing we should be doing in `OnRenderObject`. I feel like there is some fundamental thing about the Unity rendering pipeline that I am misunderstanding that would clarify all this. (Tested in 2019 LTS and 2020.2.3)

For example:

C#

```
public class TestRender : MonoBehaviour {

  public Material material ;
  private ComputeBuffer vertexBuffer;
  private GraphicsBuffer indexBuffer;
  private ComputeBuffer paramsBuffer;

  private Bounds _bounds;

  void Start () {
    material = new Material(material);

    // Copy geometry from MeshFilter (you can just use a cube for testing)
    Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
    vertexBuffer = new ComputeBuffer(mesh.vertices.Length, Marshal.SizeOf<Vector3>());
    indexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Index, mesh.triangles.Length, Marshal.SizeOf<int>());

    vertexBuffer.SetData(mesh.vertices);
    indexBuffer.SetData(mesh.triangles);

    paramsBuffer = new ComputeBuffer(5, sizeof(int), ComputeBufferType.IndirectArguments);
    paramsBuffer.SetData(new int[] { mesh.triangles.Length, 1, 0, 0, 0 });

    material.SetBuffer("_VertexBuffer", vertexBuffer);

    _bounds = new Bounds(transform.position, new Vector3(5, 5, 5));
  }

  private void Update() {
    // This works!
    Graphics.DrawProcedural(material, _bounds, MeshTopology.Triangles, indexBuffer, indexBuffer.count);

    // So does this!
    material.SetPass(0);
    Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count);
  }

  private void OnRenderObject() {
    // This does NOT work
    Graphics.DrawProcedural(material, _bounds, MeshTopology.Triangles, indexBuffer, indexBuffer.count);

    // But this does!
    material.SetPass(0);
    Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count);
  }
}

```

Simple shader:

```
Shader "Test Render" {
     SubShader {

         Pass {
         CGPROGRAM
         #include "UnityCG.cginc"
         #pragma target 4.5
         #pragma vertex vertex_shader
         #pragma fragment fragment_shader

         StructuredBuffer<float3> _VertexBuffer;

         struct v2f {
             float4 pos : SV_POSITION;
         };

         v2f vertex_shader (uint id : SV_VertexID, uint inst : SV_InstanceID)
         {
             v2f o;
             float4 vertex_position =  float4(_VertexBuffer[id],1.0f);
             o.pos = UnityObjectToClipPos(vertex_position);
             return o;
         }

         fixed4 fragment_shader (v2f i) : SV_Target
         {
            fixed4 final = fixed4(0, 0, 1, 1);
            return final;
         }

         ENDCG
     }
     }
}

```

# Answer
> 2 votes
From what I could gather over the internet, it appears that calls to functions that don't draw immediately like `Now` methods are removed from queue after scene was rendered.

From one of the unity forums, part official response - "Another alternative could be using Graphics.DrawMesh (which does not draw mesh immediately, but "adds it into the scene"), and/or using CommandBuffers."

And from official docs - OnRenderObject \- "OnRenderObject is called after camera has rendered the Scene.".

So in the end we can come to the conclusion that `DrawProceduralNow` immediately renders something, while `DrawProcedural` adds it to the render queue, but since a call of `OnRenderObject` is happening after scene was rendered - it never gets invoked.

I am not proficient enough to know how it works internally, but this is the best answer I can give right now, since there are 0 answers to your question at the moment.

---
Tags: unity, rendering, graphics
---


# Question
Title: Why when saving a game it's writing the saved game only if I leave the editor window and then coming back?
It's not saving in runtime for some reason. Only when I stop the game and only when leaving the editor window then when coming back to the editor window I see it's writing the saved game file on the hard drive.

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

public static class SaveSystem
{
    private static readonly string SAVE_FOLDER = Application.dataPath + "/Saved Games";
    private static string content;

    public static void Init()
    {
        if (!Directory.Exists(SAVE_FOLDER))
        {
            Directory.CreateDirectory(SAVE_FOLDER);
        }
    }

    public static void Save(string saveString)
    {
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");
        File.WriteAllText(fileName, saveString);
    }

    public static void Save(string SaveString, string FolderToSave, string FileName)
    {
        if (!Directory.Exists(FolderToSave))
        {
            Directory.CreateDirectory(FolderToSave);
        }

        string fileName = Path.Combine(FolderToSave, FileName);
        File.WriteAllText(fileName, SaveString);
    }

    public static string Load()
    {
        content = "";
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");

        if (File.Exists(fileName))
            content = File.ReadAllText(fileName);

        return content;
    }

    public static string Load(string FolderToLoadFrom, string FileName)
    {
        content = "";
        string fileName = Path.Combine(FolderToLoadFrom, FileName);

        if (File.Exists(fileName))
            content = File.ReadAllText(fileName);

        return content;
    }
}

```

It should make the whole saving and writing the file in runtime.

# Answer
> 1 votes
The solution is to refresh the Assets data base when writing the file to the hard disk :

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

public static class SaveSystem
{
    private static readonly string SAVE_FOLDER = Application.dataPath + "/Saved Games";
    private static string content;

    public static void Init()
    {
        if (!Directory.Exists(SAVE_FOLDER))
        {
            Directory.CreateDirectory(SAVE_FOLDER);
        }
    }

    public static void Save(string saveString)
    {
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");
        File.WriteAllText(fileName, saveString);

        AssetDatabase.Refresh();
    }

    public static void Save(string SaveString, string FolderToSave, string FileName)
    {
        if (!Directory.Exists(FolderToSave))
        {
            Directory.CreateDirectory(FolderToSave);
        }

        string fileName = Path.Combine(FolderToSave, FileName);
        File.WriteAllText(fileName, SaveString);

        AssetDatabase.Refresh();
    }

    public static string Load()
    {
        content = "";
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");

        if (File.Exists(fileName))
            content = File.ReadAllText(fileName);

        return content;
    }

    public static string Load(string FolderToLoadFrom, string FileName)
    {
        content = "";
        string fileName = Path.Combine(FolderToLoadFrom, FileName);

        if (File.Exists(fileName))
            content = File.ReadAllText(fileName);

        return content;
    }
}

```

This line did the trick :

```
AssetDatabase.Refresh();

```

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


# Question
Title: How to edit a Rigged 3D Model without Ruining the Rig?
I have some rigged 3D models that I want to use. They came as .fbx. and sometimes I want to make some minor edits such as merging/moving/removing some vertices or something of that nature.

**The Problem:** That (using Unity & Blender) I cannot seem to be able to make changes to a 3D model without ruining the model's Rig.

Blender's importing seems to be the problem, if you care to take a look - but it may be unfixable.

> (The first picture is what happens because Blender f\*#ks up the the leaf nodes, the 2nd is me trying to reattach the mesh to a Rig)

I have been completely stuck for a full day; however, **it would seem that there are several potential fixes/work-arounds for this problem**. And I am wondering which of these you would take? These could be:

1. Figuring out why importing a .fbx into Blender breaks the model. I'm not confident that this is going to happen, so let's discuss other possibilities.
2. Using Unity / Unity's API, and an unedited copy of the model *that is working*, apply the changes that I've made to the model, and then (instead of using Blender's broken Rig) somehow apply the Rig of this working model to my edited model, such that the same vertices are attached to the same bones, and new ones are attached to the nearest bone, ect.
3. Just completely give up on the old Rig and re-rig it in Blender.
4. Through Unity, somehow applying the vertex changes I've made to the model to the model that does have a working Rig.
5. Something else that I haven't thought of.

This is frustrating and I want to move on to the next thing already, so if Blender's importing can be fixed I am interested in looking into one of the above work-arounds. What would you advise that I look into?

# Answer
Given that we do not know from what tool did the fbx come from I will just share our experience. Importing rigs from fbx in blender that were made in other tools does not work. Altough blender might have the same functionality as lets say Maya, its internals are different and there seems to be no corelation between features. I would reccomend you give up on your existing rig and re-rig in blender. In the long term this will svae you time by not having to fight ghosts.
> 1 votes

---
Tags: unity, animation, blender, 3d-meshes, rigging
---


# Question
Title: Is an inertia tensor in local-space always diagonal?
I'm looking at the implementation of a physics engine and I observe that the inertia tensor of a rigid body, in local-space coordinates, is stored as a 3 dimensional vector, rather than a 3x3 matrix, and the description says "A vector with the three values of the diagonal 3x3 matrix".

A diagonal matrix is one with all zero off-diagonal entries.

What I don't understand is why the inertia tensor in local coordinates would be diagonal? Why couldn't it have non-zero off-diagonal entries?

# Answer
> 1 votes
Think about what the inertia tensor is doing- it describes an objects resistance to rotational motion along each of the 3 axes. Each of the 3 elements which comprise the diagonal of the inertia tensor describe the resistance to motion along each of the 3 local space axes. If you made some of the elements in the column vectors non-zero, you would simply be limiting one of the other two axes- which is the natural result of applying a rotation to the inertia tensor.

Since any given object must have an origin and original orientation, it only makes sense to define them in local space as simply as possible, for both memory reasons as well as simplicity.

I suggest reviewing the polyhedral mass properties algorithm to gain a better understanding of how the diagonal is calculated. It is essentially a volume integral of a solid defined by triangular regions.

I should also mention that the inverse inertia tensor is the quantity actually used by a physics engine, so defining them as a diagonal makes the inverse process significantly simpler.

---
Tags: physics, mathematics, physics-engine
---


# Question
Title: How to animate objects with bobbing up and down motion in Unity?
I have created a 2D platform game with Unity and C# where I have collectable items that can be picked up by the player. What I want is to give the items more focus by having them bobbing up and down.

I came up with the following version:

```
Vector2 floatY;

public float FloatStrength; // Set strength in Unity

void Update () {
    floatY = transform.position;
    floatY.y = (Mathf.Sin(Time.time) * FloatStrength);
    transform.position = floatY;
}

```

But, this makes the object float in the middle of the level instead of where the object is positioned. How can I fix that?

Here is a screenshot of the prototype of the game:

The player can collect the wood stumps which should be bobbing up and down in space just above the ground.

# Answer
You have a pretty simple solution. What your problem here is that you are not preserving the original y position. Essentially, you need to store the original y position in a variable, that would look like this: (Don't forget to set the variable in the Start() function.)

```
Vector2 floatY;
float originalY;

public float floatStrength;

void Start ()
{
    this.originalY = this.transform.position.y;
}

void Update () {
    floatY = transform.position;
    floatY.y = (Mathf.Sin(Time.time) * floatStrength);
    transform.position = floatY;
}

```

After that, I suggest that instead of directly setting the y value of the floatY to `Mathf.Sin(Time.time) * floatStrength`, you set it based on the sum of that value and the original transform position. The final code should look something like this:

```
Vector2 floatY;
float originalY;

public float floatStrength;

void Start ()
{
    this.originalY = this.transform.position.y;
}

void Update () {
    floatY = transform.position;
    floatY.y = originalY + (Mathf.Sin(Time.time) * floatStrength);
    transform.position = floatY;
}

```

Finally, instead of storing floatY as a Vector, you could store it as a float. Alternatively, you could use `transform.position` directly, doing something like this:

```
Vector2 floatY;
float originalY;

public float floatStrength;

void Start ()
{
    this.originalY = this.transform.position;
}

void Update () {
    /* Old code:
    floatY = transform.position;
    floatY.y = originalY + (Mathf.Sin(Time.time) * floatStrength);
    transform.position = floatY;
    */
    transform.position = new Vector2(transform.position.x,
        originalY + (Math.Sinf(Time.time) * floatStrength));
}

```

Finally, the last step is to do some minor refactoring as to remove some errors that have popped up along the way. `Math.Sin` (Note: not `Math.Sinf`) yields a `double` instead of the desired `float`, so we have to explicitly convert that value. Next, we can remove the `Vector2 floatY` completely. Note that this would need to actually be a Vector3 to store `transform.position`, as that also has a `z` component, if we were to actually have kept using that. Finally, we must fix that same problem in the `Update()` function, and change:

```
    transform.position = new Vector2(transform.position.x,
        originalY + (Math.Sinf(Time.time) * floatStrength));

```

to:

```
    transform.position = new Vector3(transform.position.x,
        originalY + (Math.Sinf(Time.time) * floatStrength), transform.position.z);

```

That code segment does not implement the other changes that I mentioned. In the end the complete code is as follows:

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

public class FloatBehavior : MonoBehaviour
{
    float originalY;

    public float floatStrength = 1; // You can change this in the Unity Editor to
                                    // change the range of y positions that are possible.

    void Start()
    {
        this.originalY = this.transform.position.y;
    }

    void Update()
    {
        transform.position = new Vector3(transform.position.x,
            originalY + ((float)Math.Sin(Time.time) * floatStrength),
            transform.position.z);
    }
}

```

Note that this code can be attached to an object either through `New Object >> 2D >> Sprite` and then by adding this code as a script, or through the following code programmatically:

```
    GameObject object = new GameObject();
    object.name = "Floating Box";
    object.AddComponent<SpriteRenderer>().sprite = SOME_SPRITE;
    object.AddComponent<FloatBehavior>();

```

Here's an example of what this could look like:

Edit: Fixed compile errors
> 12 votes

# Answer
I use this for my 3D game:

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

public class BobbingEffect : MonoBehaviour
{
    float originalY;

    public float floatStrength = 1; // You can change this in the Unity Editor to
                                    // change the range of y positions that are possible.

    void Start()
    {
        this.originalY = this.transform.position.y;
    }

    void Update()
    {
        transform.position = new Vector3(transform.position.x,
            originalY + ((float)Math.Sin(Time.time) * floatStrength),
            transform.position.z);
            transform.Rotate(0,1,0);
    }
}

```
> -1 votes

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


# Question
Title: Can I legally use movie sounds for game production?
Can I legally use short sounds from movies, like a door closing, in my game?

Is there a way for others know from where the sounds came from originally? Does it matter if I apply audio editing to the sample?

# Answer
Using stock sound effects is actually very common in the film industry (like the infamous Wilhelm Scream). But movie studios actually pay for the rights to these sound effects, usually in form of buying larger libraries of stock sound effects. So they will expect you to do the same thing.

Don't use audio samples when you don't have an explicit permission to do so.

And by the way: Doing your own Foley is actually very easy, doesn't require any special equipment you likely won't have laying around anyway and it is a lot of fun.
> 6 votes

# Answer
I'm not a lawyer and this is not legal advice. However our studio recently had to deal with a bunch of sound copyright issues and I can tell you that it is taken very seriously. We bought a bunch of recordings of CC0 music and somehow we are still getting flagged by automatic detection for copyright infringment in a lot of places. We went over our issue and a bunch of others with a lawyer and I can assure you that what you are proposing is NOT legal in any way. You will need to either purchase sound banks or find free CC0 sfx resources.
> 4 votes

---
Tags: audio, copyright
---


# Question
Title: Why my calculated value is far different from actual value?
I using `CharacterController` and not using a `Rigidbody` so I writing a script for downward velocity which is velocity=-9.81\*(time) and I declare my initial velocity as 12. Supposing from this calculation, the max height it can reach from the equation is roughly 6.7891 unit on y axis. By using the formulae `distance travel=initial velocity*(time)-0.5g*(time)^2`,differentiate this w.r.t time, getting `time=u/g=12/9.81=1.223`, then `max distance travel=12*(1.223)-0.5*(-9.81)*(1.223)^2=7.339` but from the coordinate below, can clearly seen the max distance travel before falling down is `13.2803unit--0.5499unit=13.8302unit`? This is far exceed calculated value, wonder what went wrong?

Initial coordinate of y on ground=-0.5499

approximate final coordinate of y=13.2803

```
using UnityEngine;

public class NewPlayerMovement : MonoBehaviour
{
    public CharacterController Controller;
    //speed of the character
    public float Speed = 12f;
    // earth gravitational value
    public float Gravity = -9.81f;
    Vector3 velocity;
    //hit point of character
    float hp = 90;

    bool Grounded = true;

    public void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Grounded = true;
        hp -= velocity.magnitude;
        velocity.y = 0;
        Debug.Log(hp);
    }

    public void OnControllerColliderExit(ControllerColliderHit hit)
    {
        Grounded = false;
    }

    public void Checkstatus()
    {
        if(Grounded==false)
        {
            velocity.y += 0.5f * Gravity * Time.deltaTime;
        }
    }

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 move = transform.right * x + transform.forward * z;

        Controller.Move(move * Speed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space) && velocity.y == 0)
        {
            velocity.y = 12;
            Grounded = false;
        }

       //check if it grounded
        Checkstatus();
        Controller.Move(velocity * Time.deltaTime);
    }
}

```

# Answer
> 1 votes
Calculating the new velocity should be

```
velocity.y += Gravity * Time.deltaTime;

```

without the `0.5f *`. This is because the velocity remains the same during the whole time step unlike in the continuous case where we have an inclined velocity curve approximated with infinitesimal small triangles calculated as baseline * height / 2. This is where the 0.5 comes from when we integrate.

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


# Question
Title: More loosely coupled way to design this attack and target concept?
In my 2d game in unity and c sharp, my friendly units are squares. Each square has a grid on it. Each cell of the grid can have one enemy attached to it at a time.

This means that my enemy's targets are not just the friendly game object, but the cell as well. Because of this, I've created a Target class for this (just contains a gameobject and cell). Enemies carry their Target reference so they know where to move to and who to attack.

However, my friendlies do not need the cell to target an enemy. Enemies are small and don't have grids on them. I cannot figure out a nice way to make this polymorphic(?) Target concept work without doing checks for "if cell is not null" in all of my targeting code.

For example, code in my behavior tree for checks like "HasTarget" are tightly coupled to check for existence of a gameobject and cell. It just feels wrong. Am I stuck using custom checks and code for an enemy vs friendly target?

I tried interfaces but they require the same return types. That differs depending on if they are an enemy or friendly. Something like unit.Itargettable.GetTarget() won't work.

Help!

# Answer
> 1 votes
> I tried interfaces but they require the same return types. That differs depending on if they are an enemy or friendly. Something like unit.Itargettable.GetTarget() won't work.

It sounds like you haven't used interfaces correctly. If the return type needs to be the same type, then make the return type an interface. Then have both your friendly and enemy units implement that interface.

It's hard to understand exactly how your game is currently set up, because you haven't shared any of your code, but here's a rough example of how you might use an interface:

```
public ITargetableEvent : UnityEvent<ITargetable> {}

public interface ITargetable {
    string Name { get; }
    int HP { get; set; }
    Vector3 Position { get; set; }
    ITargetableEvent DeathEvent { get; }
}

public class Unit : ITargetable {
    [SerializeField] private string name;
    [SerializeField] private int hp = 100;
    [SerializeField] private int attackPower = 5;
    [SerializeField] private ITargetableEvent deathEvent = new ITargetableEvent();
    private ITargetable target;

    public string Name => name;
    public int HP {
        get => hp;
        set {
            this.hp = value;
            if (this.hp <= 0) deathEvent.Invoke(this);
        }
    }

    virtual public Vector3 Position => transform.position;

    //our target can be anything that implements ITargetable
    public ITargetable Target { get => target; set => target = value; }

    public void Attack() {
        if (target != null) target.HP -= attackPower;
    }
}

//friendly unit position is determined by the cell?
public class FriendlyUnit : Unit {
    [SerializeField] private Cell cell;
    override public Vector3 Position => cell.transform.position;
}

```

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


# Question
Title: Rotating an object to face the same direction as another object
Feel like I should know this, maybe I'm just over thinking it. What I'm attempting to do is create a bullet hole plane/texture object on top of an existing mesh when a ray cast returns a hit point. I have everything working except rotating the plane to face the same direction as the contact normal.

The way my engine works, every "Actor" (my game object essentially) has a transform. This transform tracks the actor's translation, rotation, and scale, then generates a model matrix that is used to generate an mvp matrix down the road.

The way I am attempting to solve this at the moment is to *generate a quaternion that will rotate the bullet plane actor in the same direction as the contact normal*. However, I'm unsure how to go about this at the moment and was hoping someone might be able to point me in the right direction.

**EDIT**

Transform.h

```
class Transform
    {
    private:
        glm::vec3           translation;
        glm::quat           rotation;
        glm::vec3           scale;

    public:
                            Transform();
                            Transform(glm::vec3 t, glm::quat r, glm::vec3 s);
        void                setTranslation(glm::vec3 translation);
        void                setRotation(float angle, glm::vec3 axis);
        void                setRotation(glm::quat rotation);
        void                setScale(glm::vec3 scale);
        const glm::vec3&    getTranslation() const;
        const glm::quat&    getRotation() const;
        const glm::vec3&    getScale() const;
        const glm::mat4     getMatrix() const;
        void                print();

        glm::vec3           getRotationEulers();

        static glm::vec3    interpolateTranslations(const Transform& previousTransform, const Transform& currentTransform, float alpha);
        static glm::quat    interpolateRotations(const Transform& previousTransform, const Transform& currentTransform, float alpha);
        static glm::vec3    interpolateScales(const Transform& previousTransform, const Transform& currentTransform, float alpha);
        static glm::mat4    interpolateTransforms(const Transform& previousTransform, const Transform& currentTransform, float alpha);

    };

```

Transform.cpp

<pre><code>    Transform::Transform() :
        translation(glm::vec3(0.0f, 0.0f, 0.0f)),
        scale(glm::vec3(1.0f, 1.0f, 1.0f)),
        rotation(glm::quat())
    {}

    Transform::Transform(glm::vec3 t, glm::quat r, glm::vec3 s) :
        translation(t),
        rotation(r),
        scale(s){}

    void Transform::print()
    {
        std::cout << "T:(" << this->translation.x << "," << this->translation.y << "," << this->translation.z << ")\n";
        std::cout << "R:(" << this->rotation.x << "," << this->rotation.y << "," << this->rotation.z << "," << this->rotation.w << ")\n";
        std::cout << "S:(" << this->scale.x << "," << this->scale.y << "," << this->scale.z << ")\n";
        std::cout << "---------------------------------\n";
    }

    glm::vec3 Transform::getRotationEulers()
    {
        auto tmp = glm::eulerAngles(this->rotation);
        return glm::vec3((tmp.x * 180.0f / 3.141592653589793f), (tmp.y * 180.0f / 3.141592653589793f), (tmp.z * 180.0f / 3.141592653589793f));
    }

    void Transform::setTranslation(glm::vec3 translation)
    {
        this->translation = translation;
    }

    void Transform::setRotation(glm::quat rotation)
    {
        this->rotation = rotation;
    }

    void Transform::setRotation(float angle, glm::vec3 axis)
    {
        this->rotation = glm::angleAxis(glm::radians(angle), axis);
    }

    void Transform::setScale(glm::vec3 scale)
    {
        this->scale = scale;
    }

    const glm::vec3& Transform::getTranslation() const
    {
        return this->translation;
    }

    const glm::quat& Transform::getRotation() const
    {
        return this->rotation;
    }

    const glm::vec3& Transform::getScale() const
    {
        return this->scale;
    }

    const glm::mat4 Transform::getMatrix() const
    {
        glm::mat4 m = glm::mat4(1.0f);
        m = glm::translate(m, this->translation);
        m = m * glm::toMat4(this->rotation);
        m = glm::scale(m, this->scale);
        return m;
    }

    glm::vec3 Transform::interpolateTranslations(const Transform& previousTransform, const Transform& currentTransform, float alpha)
    {
        return glm::lerp(previousTransform.getTranslation(), currentTransform.getTranslation(), alpha);
    }

    glm::quat Transform::interpolateRotations(const Transform& previousTransform, const Transform& currentTransform, float alpha)
    {
        return glm::slerp(previousTransform.getRotation(), currentTransform.getRotation(), alpha);
    }

    glm::vec3 Transform::interpolateScales(const Transform& previousTransform, const Transform& currentTransform, float alpha)
    {
        return glm::lerp(previousTransform.getScale(), currentTransform.getScale(), alpha);
    }

    glm::mat4 Transform::interpolateTransforms(const Transform& previousTransform, const Transform& currentTransform, float alpha)
    {
        Transform t;
        t.setTranslation(glm::lerp(previousTransform.getTranslation(), currentTransform.getTranslation(), alpha));
        t.setRotation(glm::slerp(previousTransform.getRotation(), currentTransform.getRotation(), alpha));
        t.setScale(glm::lerp(previousTransform.getScale(), currentTransform.getScale(), alpha));
        return t.getMatrix();
    }
```
</code></pre>

# Answer
> 3 votes
You can do this without the back-and-forth to matrix steps by computing your new quaternion directly.

Here we use the fact that the axis to rotate around must be perpendicular to the start and ending directions (like their cross product), and that the cross product of two unit vectors has length equal to the sine of the angle between them. Then we can construct a quaternion angle-axis style.

```
// Assumes startDirection and endDirection are unit vectors (length 1)
Quaternion FromToRotation(Vector3 startDirection, Vector3 endDirection) {

    Vector3 crossProduct = Cross(startDirection, endDirection);

    float sineOfAngle = Length(crossProduct);

    float angle = Asin(sineOfAngle);
    Vector3 axis = crossProduct / sineOfAngle;

    Vector3 imaginary = Sin(angle/2.0f) * axis;

    Quaternion result;
    result.w = Cos(angle/2.0f);
    result.x = imaginary.x;
    result.y = imaginary.y;
    result.z = imaginary.z;

    return result;
}

```

You'll want to add a case to handle when the vectors are already parallel - in this situation, the output is either the identity quaternion (w, x, y, z) = (1, 0, 0, 0), or a 180 degree flip around any perpendicular vector if they're pointing opposite one another.

# Answer
> 0 votes
Was able to resolve this using glm's lookat method. The process was to take the hitpoint from my raycast, then create a second point by adding the product of the normal and a distance vector to the original hit point. After this I used `glm::lookat` to generate a matrix, transposed that matrix, and then converted to a quaternion that I then set as the rotation for my bullet object. My code is below:

```
auto hitPoint = vel::helpers::functions::bulletToGlmVec3(raycast.m_hitPointWorld);
auto normal = vel::helpers::functions::bulletToGlmVec3(raycast.m_hitNormalWorld);

auto bulletHolePosition = hitPoint + (normal * glm::vec3(0.001f, 0.001f, 0.001f));

glm::mat4 bulletHoleRotationMatrix = glm::transpose(glm::lookAt(hitPoint, bulletHolePosition, glm::vec3(0.0f, 1.0f, 0.0f)));

bulletHoleActor.getTransform().setTranslation(bulletHolePosition);
bulletHoleActor.getTransform().setRotation(glm::toQuat(bulletHoleRotationMatrix));

```

---
Tags: opengl, c++, glm
---


title: 2D physics without "rebound"

text:
# Question
Title: 2D physics without "rebound"
I'm trying to get my 2D top down shooter to use -some- physics.

I want the player and enemies not be able to exist in the same position, in other words, use collisions.

My first attempt was to use a CharacterController, but I could not get my other game objects to collide with my player, even though I had a RigidBody2D and a BoxCollider2D on them. Obviously, due to using a CharacterController, I was not able to add these components on my player.

Going one step back, I removed the CharacterController, and rather opted to go the Rigidbody2D route. This worked partially. I now get collisions on my player when he walks into other gameobjects (with RB2D and BC2D on them), but there seems to be a "rebound" anomaly occurring; my player moves around after collision.

I've tried playing around with the settings on the RigidBody2D on the player, but it does not seem to have any effect.

This is my PlayerMovement script :

```
void Update()
{
    HandleRotation();
    HandleMovement();
}

void HandleRotation()
{
    var mousePos = Input.mousePosition;
    mousePos.z = 5.23f;

    var objectPos = Camera.main.WorldToScreenPoint(transform.position);
    mousePos.x -= objectPos.x;
    mousePos.y -= objectPos.y;

    float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}

void HandleMovement()
{
    float horizontal = Input.GetAxisRaw(Constants.Axis.Horizontal);
    float vertical = Input.GetAxisRaw(Constants.Axis.Vertical);

    Vector3 direction = new Vector3(horizontal, vertical, 0f).normalized;

    if (direction.magnitude >= 0.1f)
    {
        var speed = (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            ? mobileController.runningSpeed
            : mobileController.walkingSpeed;
        var moveVector = (direction * speed) + transform.position;
        mobileController.rigidbody2d.MovePosition(moveVector);

        var camPosition = new Vector3(mobileController.transform.position.x, mobileController.transform.position.y, -10);
        cam.position = camPosition;

    }
}

```

The settings on my Player :

I would like my player to stop dead in his tracks when colliding with another RigidBody2D. Is this possible? And if so, how would I go about doing that?

# Answer
> 0 votes
Resolved by setting the "Freeze Rotation" on the Z axis in the RigidBody2D component

# Answer
> 0 votes
To prevent things from bouncing, what you want are "inelastic" collisions.

In Unity all collisions below a configurable Velocity Threshold are inelastic. You can change that velocity threshold inside your Physics2D settings. (menu: Edit \> Project Settings \> Physics 2D).

See also https://answers.unity.com/questions/1393846/rigidbody-sticks-to-walls-or-how-the-hll-do-you-fo.html

---
Tags: unity, 2d, physics
---


# Question
Title: Need help projecting 2D projectile motion in 2.5/isometric 2D game
So I’ve been researching this a lot and have hit a road block. I’ve read pretty much every thread on here regarding this and while I understand the concept I don’t understand how to implement it. For reference I’m using Godot, but the explanation does not need to be in gdscript or anything.

Basically I have a projectile launcher and an isometric perspective. The best way I can describe what I am trying to achieve is a 8/16 bit Baseball game which many did this quite well. Visually simulating height and 3D physics in a 2D game.

I understand and have in my code the basic kinematic equations. So I can input variables such as initial velocity and the angle. I then get the X and Y position output as variables that update each processing tick, in this case 60 fps.

I’m using kinematic equations because I want to use those values in other places like the total distance and max height.

But this is in a 2D plane, basically from the side view, which would be perfect if I was making a side scroller.

I am having trouble projecting this XY position into the isometric view of my game.

Basically I have a distance and a height of my projectile.

# Answer
> But this is in a 2D plane, basically from the side view, which would be perfect if I was making a side scroller.
>
> I am having trouble projecting this XY position into the isometric view of my game.

We are going to define an skewed coordinate system. For that coordinate system the vertical will remain vertical. But the horizontal will be a vector in the direction of the throw.

So you have two unit vectors `up` and `forth`. Where `up` is vertical, and `forth` is the direction on the isometric plane. Both unit vectors (in whatever scale you are using).

Now, multiply them by your coordinates. The final position is:

```
var position = X * forth + Y * up;

```

Note: this position is relative to the origin of the throw.

Or if you prefer:

```
var position = Vector2(X * forth.x + Y * up.x, X * forth.y + Y * up.y);

```

Which, given that up is vertical, and unit length, is the same as:

```
var position = Vector2(X * forth.x, X * forth.y + Y);

```

As you can see when forth is `Vector(1, 0)`, you would have `Vector2(X, Y)`, which is the case of the side view.

*If you want the position on the ground (for example, for a shadow), you replace `Y` with the height of the terrain. Assuming the height of the terrain is 0 (for example, for a flat terrain), then it is just `X * forth`.*
> 1 votes

---
Tags: physics, isometric, godot, projection, projectile
---


title: Flat and crispy shading

text:
# Question
Title: Flat and crispy shading
Im trying to create a mobile game that has flat, bright colors and I want every place to be lightened the same. Like this game:

and this is my game's current state:

I don't know what the problem is. It is too dark and not as good-looking as the first image. If i increase the light, it gets bright, not saturated and crispy. Maybe wrong lighting or wrong material usage? First image looks so crispy and it almost like a Vector art. I modeled all of the assets myself in Blender. I tried using Ambient lighting but it didn't work. I also turned off shadows but still the same. Also there is a distortion in the big red circle i drew and i don't know why is it hapening. And i don't want the shiny light in the little red circle.

# Answer
In the Mesh Renderer component you can select if that object will cast and receive shadows. So if there are some 3D objects that you don't want to have a shadow, just disable **Shadow Casting** and **Shadow Receiving** in the chosen model’s Mesh Renderer component. (I found that from here.)

Additionally, you may want to increase the ambient lighting and decrease the directional light intensity, which means the light is technically everywhere and will give you the cartoon effect that is desired.
> 1 votes

---
Tags: unity, graphics, shading
---


# Question
Title: Removing FMOD from a Unity WebGL project causes an error about not being able to copy fmod_register_static_plugins.cpp
When I imported the FMOD plugin into a Unity WebGL project, then removed it afterwards, I wasn't able to build it due to errors about trying to copy an FMOD file: fmod\_register\_static\_plugins.cpp

Restarting the editor, reimporting everything, deleting Library/Temp folders did not help. Neither did deleting the FMod folder.

# Answer
Using AstroGrep, I was able to find that ProjectSettings/ProjectSettings.asset was still referencing the file. Search for either "fmod\_register\_static\_plugins.cpp" or "additionalIl2CppArgs", and delete the references to the offending files. Building the project again worked.
> 1 votes

---
Tags: unity, webgl, fmod
---


title: Runtime Issues on 144Hz Monitors

text:
# Question
Title: Runtime Issues on 144Hz Monitors
I've recently finished my first ever Unity game. The game runs okay in my end but two of my friends had issues with the game. They both have 144hz monitors and the issues are solved when they lower the refresh rate to 60Hz. The problems are that any object who has a velocity depending on Time.deltatime, it gets halved. Is there a way to fix this on code so that nobody has to reduce their refresh rate when playing?

Here is an example code of a snowball projectile's behaviour. The snowball usually stays alive for `3f` seconds and that allows him to go across the whole screen but in 144hz runtime, the snowball goes really slow and it does not last enough to even get across the half of the screen.

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

public class Snowball : MonoBehaviour
{
    [SerializeField] private float speed = 20f;
    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private GameObject impactEffect;

    // Start is called before the first frame update
    void Start()
    {

        Destroy(gameObject, 3f);
    }

    void Update()
    {
        rb.velocity = transform.right * speed * Time.deltaTime * 75;
    }

    void OnTriggerEnter2D(Collider2D hitInfo)
    {
        if(hitInfo.CompareTag("Player") || hitInfo.CompareTag("Enemy"))
        {
        Destroy(gameObject);
        Instantiate(impactEffect, transform.position, transform.rotation);
        }
    }
}

```

Here is my game if anyone is interested in further examination: itch.io link

# Answer
> 2 votes
You don't need to adjust `rigidbody.velocity` by `Time.deltaTime`, because it is already defined in units per second. The Unity physics engine will take care of taking deltaTime (or rather fixedDeltaTime) into account when applying the velocity to the position.

---
Tags: unity
---