# Question
Title: Animating a line around an image for Unity app
I would like to animate a line around an image, starting from the top right going clockwise around the image and then show the check mark.

* The animation should be possibel to stop and restart.
* There are multiple images with two different shapes.

Because I'm a developer and not designer. The first thought I had was do it with a LineRenderer using the corners of the RecktTransform and DOTween but it is a bit ugly and gets complicated when I want to fine-tune the animation.

Now I'm thinking doing a sprite animation on top of the original image. I would have to do it for each shape.

Before I'm starting this I wanted to ask if there might be another better option I'm overlooking.

# Answer
In the end, the solution for me was to use the UI image's Fill settings with a separate green border image as suggested by DMGregory.

To start the animation in the top right corner, I rotated the border image by 45° and rotated it back in Unity as suggested here.

To run the animation and add the checkmark I used DoTween:

```
Sequence mySequence = DOTween.Sequence();
mySequence.Append(_border.DOFillAmount(1, _borderAnimationDuration).SetEase(Ease.Linear));
mySequence.Append(_checkMark.DOFade(1, _checkAnimationDuration).SetEase(Ease.Linear));

```
> 2 votes

# Answer
One way may be to create a simple mesh around the image and with some clever placement of the UVs, you could make a shader that appears to gradually fade in the line.

So the two vertices in the top-right corner would have the coordinates U coordinate 0.0, bottm-right 0.25, bottom-left 0.5, top-left 0.75, and finally circle back to top-right with 1.0. The V coordinate can stay at 0.0 for all vertices.

Then in a shader, you can the create a 0 to 1 gradient by lerping the saturated U value (so it stays between 0 and 1). By offsetting (adding/subtracting) the result, you can sort of fill-in the shape. If you want a sharp edge, you can use a cutout shader which will clip certain pixels below a specified opacity threshold.

Here's an example surface shader:

```
Shader "UV Progress"
{
    Properties
    {
        _Color("Color", Color) = (1,1,1,1)
        _Progress("Progress", Range( 0 , 1)) = 0

        [HideInInspector] _Cutoff( "Mask Clip Value", Float ) = 0.5
        [HideInInspector] _texcoord( "", 2D ) = "white" {}
    }

    SubShader
    {
        Tags
        {
            "RenderType" = "TransparentCutout"
            "Queue" = "AlphaTest+0"
        }

        Cull Back

        CGPROGRAM

        #pragma target 3.0
        #pragma surface surf Unlit

        struct Input
        {
            float2 uv_texcoord;
        };

        float4 _Color;
        float _Progress;
        float _Cutoff = 0.5;

        inline half4 LightingUnlit(SurfaceOutput s, half3 lightDir, half atten)
        {
            return half4(0, 0, 0, s.Alpha);
        }

        void surf(Input i, inout SurfaceOutput o)
        {
            o.Emission = _Color.rgb;
            o.Alpha = saturate(i.uv_texcoord.x - 0.5 + _Progress);

            clip(o.Alpha - _Cutoff);
        }

        ENDCG
    }
}

```

Demo of the shader on a simple quad while adjusting the `_Progress` property of the shader:
> 2 votes

---
Tags: unity, animation, sprites, line-renderer
---


title: Unity coroutine not yielding sometimes

text:
# Question
Title: Unity coroutine not yielding sometimes
I'm making a 2D platformer controller and I want to implement a coyote time and buffered jump, the way I implement both is by setting a bool to true when either action is enabled like this:

```
private IEnumerator ApplyCoyote()
{
    isCoyote = true;
    yield return coyoteDelay;
    isCoyote = false;
}

```

So if you were to press jump while `isCoyote` is true you would jump. But every now and then the coroutine appears not to work and `isCoyote` becomes false immediately. I confirmed this by logging the changes to `isCoyote` and most of the time I can notice the delay between it becoming true and false plus the time on both logs is different, but when it fails it just prints them at the same time.

BTW I'm not disabling any scripts and I stop any previous calls to this coroutine before starting a new one

# Answer
For making the coroutine wait for a few seconds before executing `isCoyote = false`, you will need to use `new WaitForSeconds()`.

What this function does is it waits for that delay and then executes `isCoyote = false`.

Try this code:

```
private IEnumerator ApplyCoyote()
{
    isCoyote = true;
    yield return new WaitForSeconds(coyoteDelay);
    isCoyote = false;
}

```
> 1 votes

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


# Question
Title: How to design an upgradeable skill system?
In my game skills can be leveled up to modify base stats like reducing cooldown by 20% and increasing fired projectile count by one. How would I architect the system so that each skill has its own custom upgrade tiers for example:

Projectile Skill Tier 1:

* Cooldown -20%
* Projectile Count +1

Projectile Skill Tier 2:

* Cooldown -10%
* Projectile Count +2

```
public abstract class Skill : ScriptableObject
{
    public float Cooldown;

    public abstract void Activate(Player player);
}

```

And an example of a subclassed skill:

```
public class ProjectileSkill : Skill
{
    [SerializeField] Projectile _projectile;
    [SerializeField] int _projectileCount;

    public override void Activate(Player player)
    {
        // Instantiates number of projectiles
    }
}

```

What I have tried:

* Storing the state in the scriptable object and updating the values. However this is saved between sessions whereas it needs to reset.

```
public void LevelUp()
{
    _projectileCount++;
}

```

# Answer
> 2 votes
Using scriptable objects to store game state is usually a bad idea. They are meant to represent game-specific static assets. "Upgrading a skill" by upgrading *the data* of the skill is an even worse idea. What if you need multiple gameObjects which have the same skill on different levels? What if you need the data of a different skill level than the current one, for example to preview the effects of an upgrade before the player buys it?

## Solution A: Skill tiers as separate assets

One option would be to represent each upgrade tier as a separate asset. So "Fireball Tier 1" and "Fireball Tier 2" are separate assets of the type `ProjectileSkill`.

Upgrade progressions can then be represented by adding a field

```
public ProjectileSkill nextTier;

```

to the class. Now you can use the inspector of "Fireball Tier 1" to assign "Fireball Tier 2" as the next upgrade tier. When a skill is the final upgrade tier, you can represent that by leaving `nextSkill` empty.

This would be the solution I would prefer if skills don't have too many upgrade tiers. But the downsides are that it does not scale too well when you have a very high number of upgrade tiers, and that it does not support infinite upgrade-able skills.

## Solution B: The asset contains the data for all its tiers

Another option would be to create one ScriptableObject for each skill, but then store the data of the different upgrade levels within that ScriptableObject. Now when a gameObject wants to "activate" a skill, it also needs to provide the level it wants to activate it at.

```
public class ProjectileSkill : Skill
{
    [Serializable]
    public struct UpgradeLevel{
        public Projectile projectile;
        public int projectileCount;
    }
    public UpgradeLevel[] upgradeLevels;

    public override void Activate(Player player, int level)
    {
        var upgradeLevel = upgradeLevels[level];
        // Use data from upgradeLevel to Instantiate number and type of projectiles
    }
}

```

Now this scriptable object has an array of levels where you can maintain the data for each upgrade level. That means the script which references this ScriptableObject needs an additional variable representing the current upgrade level.

```
[SerializeField] private Skill mySkill;
[SerializeField] private int mySkillLevel;

/*...*/

    mySkill.Activate(this, mySkillLevel);

```

This architecture also allows indefinitely upgradeable skills with a mathematical progression. Such skills wouldn't have an internal array of upgrade levels. Their `Activate` method would calculate all the numbers based on the requested `level`.

---
Tags: unity, c#, architecture, scriptable-object
---


# Question
Title: Emulating the use of video memory (the Space Invaders fortress problem)?
I'm a veteran programmer, but I'm new to Unity and game programming (although I've made games in the past, but not with an engine). The first game I'm making is an exact Space Invaders clone, but I've run into a situation that Unity doesn't seem to support out-of-the-box (although I have no doubt that it can do this).

To summarize, in case anyone is not familiar with the subtleties of Space Invaders, there are 4 fortresses between the player's laser base and the aliens. If any shot of the player or the aliens hits one of the fortresses, it gets damaged. Technically, an explosion sprite is drawn wherever the hit was detected and then erased, leaving the fortress pixels missing, which actually becomes an unprotected area of the fortress. So the collision detection in the original reads the video memory, looking for fortress pixels, and detonates the shot if it encounters even a single pixel during the shot's travel.

In my version, I'm using a 2D project with the Pixel Perfect Camera, and I'm using sprites to draw everything. I've made a sprite to use for the fortresses, but I don't think that's going to work. I think I need to use a texture so I can use `GetPixel()` and `SetPixel()` on it? Sprites have a `texture` property, but it's read-only. I would rather not have to call `SetPixel()` for every pixel of the explosion, but it would be better to XOR the pixels out of the instance of the sprite, if that's possible.

How can I go about this? Can I stick with using sprites for this?

# Answer
I would recommend separating the drawing portion of your program from the logic portion of your program. Pixels being on or off is really just an 2D array. I suggest having the logic of which parts of the fortress are damaged/standing stored in some kind of simple 2D array. Then, your drawing system would read the same array and draw appropriately, whether using sprites or textures, or some other system.

Another option could be to use 2D tilemaps. But depending on the size of the grid that might not be the best solution.
> 11 votes

# Answer
(Another old-timer here, been writing games for ZX Spectrum, so I think I can feel your pain).

In modern frameworks the "actual" display is logically very far from the "logical display". There is no reasonably straightforward (like in the 80') way to go from screen pixel to "pixel within a sprite" (you can use hacks, but they will not work universally).

It's enough to think that 2D sprites are always emulated through displaying a texture on a 3D quad (there are no "sprites" at all in the GPU pipeline, there are just quads and textures) - and that there are at least two additional programs (fragment shader and vertex shader) that can affect the position of the pixels.

Also, modern frameworks tend to punish people who go against the grain - and reward programmers who try to use their facilities to the fullest.

So - I would just make each pixel of each base a separate sprite (same for explosion) (edit, for clarification: by "sprite" I mean a full-fledged `GameObject`). This will give me a very clean model, immediately usable with all the Unity's APIs. I actually think this is the most elegant method to solve the problem.

If I wanted to design the shape of the bases as PNG files, I would write a short script that creates the sprite instances programmatically.

*EDIT*: There seems to be a knee-jerk reaction, saying that "Argh! It will be slow". I don't see any reasons for it to be too slow.

Why not?

1. With modern GPU, there's no cost of "a sprite". You only pay for:

* logic per screen pixel (not a texture pixel! these are free),
* logic per vertex,
* number of vertices,
* number of screen pixels touched (transparent or not).

Logic is same in both cases. Using sprite-per-base-pixel approach, you have more vertices, but less screen pixels (because GPU never visits "gone" pixels, and doesn't need to render transluent parts of bases, as is the case with rectangular base sprites). This is usually an *optimization*, not a problem! Many games employ non-rectangular sprites for performance, even though it costs more vertices.

2. The number of "game pixels" in the bases is really small for today's standards. Bases are built afaik on a grid of 24x16 game pixels, so they might have - perhaps - 350 lit pixels in them or less. it's only around 1000 sprites in the whole game.
3. The amount of calculations and memory management you need is the same, whether you use particle systems, sprites, custom 2D arrays of position objects, or whatever. The performance gain of using particle systems etc. comes from them being less generic and more "crippled". So yes, it makes no sense to use sprites for a simple explosion.

On the other hand, if you implement some 2D array scheme on top of particles, trying to trace them down to their screen coordinates (and further on -\> coordinates on a different texture), you will lose all the performance gain and basically reimplement sprites, only without the experience and time that went into the Unity sprites.

Bottom line: the "sprite tax" that everyone mentions is connected to all the runtime management of the Unity's sprite container. It is real, and it is the reason why particle systems in Unity are not implemented on top of sprites (and the reason for the emergence of the "new" ECS). I cannot rule out that for your specific use-case, the sprite approach will not prove too slow, for some obscure reasons (judging performance is *hard*).

But as someone who has written and optimized games both in low-level assembly (Z80 and Motorola 6800), limited virtual machines (J2ME on feature phones) and modern Android devices - I would go with sprite-per-game-pixel first.
> 5 votes

---
Tags: unity
---


# Question
Title: Why is Vector3.ProjectOnPlane() "drifting" further from desired rotation on steep slopes
I'm writing a simple player movement script in Unity 3D, and I've been using `Vector3.ProjectOnPlane()` to accomplish slope/ramp movement. For the most part, this works on smaller slopes but I've noticed that the steeper the slope is, the more the direction seems to drift further away than expected, causing the player to walk further to one side than the input would suggest.

(To clarify, `orientationTransform` is rotated via the Mouse Input, thus only needing to use `transform.forward/right` in the movement calculation.)

**Code:**

```
// Excerpt from main movement loop
Vector3 movementDirection = (orientationTransform.forward.normalized * inputs.y + orientationTransform.right.normalized * inputs.x).normalized;

if (stateHandler.IsGrounded) {
  if(stateHandler.IsOnSlope) {
    Debug.DrawRay(orientationTransform.position, movementDirection.normalized * 3f, Color.magenta);
    return GetVectorOnSlope(movementDirection) * movementForce * Time.fixedDeltaTime;
  } else {
    return movementDirection * movementForce * Time.fixedDeltaTime;
  }
}

// Vector Function
Vector3 GetVectorOnSlope(Vector3 vector) {
  RaycastHit hitInfo;
  if (Physics.Raycast(orientationTransform.transform.position, Vector3.down, out hitInfo,
  1f, groundLayer)) {
    Debug.DrawRay(orientationTransform.position, Vector3.ProjectOnPlane(vector,
    hitInfo.normal) * 2f, Color.red);
    return Vector3.ProjectOnPlane(vector, hitInfo.normal).normalized;
  } else {
    return vector;
  }
}

```

**Example:**
Desired Direction - Magenta
ProjectOnPlane Direction - Red

I've tried normalizing the result and experimenting with `Vector3.Cross()` as well as attempting to skip using `Vector3.ProjectOnPlane()` altogether, but I've not had much luck.

Is this the correct way for me to be implementing this? I feel like `Vector3.ProjectOnPlane()` is behaving exactly as it should, but I can't figure out an alternative to achieve what I'm looking for.

Any help is greatly appreciated!

# Answer
> 2 votes
If you wanted to achieve a similar result without using projections, you might want to try just rotating the vector. This should be relatively easy to do knowing the normal of the plane.

I would take the cross product of `Vector3.up` and the plane normal to find the rotation axis, and then create a quaternion with the `Quaternion.AngleAxis()` function. The angle can be found with `Vector3.SignedAngle()`, using our newly calculated axis.

Once you have that, quaternion\*vector should give you the rotated vector.

# Answer
> 0 votes
I think you want something more like this:

```
// Use ClampMagnitude to allow analog movement up to but not exceeding a magnitude of 1.
// If using a force, do not multiply by delta time.
// (And if using a speed/displacement, don't name your variable "force" - that misleads)
var movement = Vector2.ClampMagnitude(inputs, 1.0f) * movementForce;

// Track the slope we're standing on - assume flat, level ground by default.
Vector3 intoTerrain = Vector3.down;

// Splitting out our ray struct helps avoid a long wrapping line in the if condition.
var ray = new Ray(orientationTransform.position, Vector3.down);
if ( Physics.Raycast(ray, out var hitInfo, 1f, groundLayer)) {
    intoTerrain = -hitInfo.normal;
}

// Make an orientation where y+ points along the terrain in the "into the screen" direction
// and x+ points along the terrain in the "right / across the screen" direction.
var terrainOrientation = Quaternion.LookRotation(
                            intoTerrain,
                            Camera.main.transform.forward
                         );

// Transform our movement using this coordinate frame.
return terrainOrientation * movement;

```

---
Tags: unity, c#, 3d, movement, rigidbody
---


title: GGPO / peer to peer winstate

text:
# Question
Title: GGPO / peer to peer winstate
How do games using GGPO (or maybe peer to peer in general) like Guilty Gear determine a winner? Just reporting a winner consensus might work with many independent players per lobby, but in e.g. a 1v1 fighter or RTS, the loser has no incentive to report the truth.

---

Since a game using GGPO must be deterministic, it should be enough to run all inputs back to back to confirm the winner via a "referee" spectator, but this moves the problem: A cheater might send a "fake" set of inputs (e.g. just standing still) to the enemy and their "real" ones to the referee. From the perspective of the referee, it would seem as if the cheater won legitimately while the victim seemed to be punching the air.

Maybe both players could send a checksum of the inputs they received to the referee to allow it to check that it indeed received the same inputs as the players. If I understood it correctly, that is the approach of this paper. This eliminates the possibility of fooling the referee, but ends up with the same problem as we started with: The cheater can send a fake checksum, accusing the victim of cheating, which leaves the referee with the same kind of information as if both players simply stated that they and not the other won.

The simplest solution I can think of is to simply accept the disagreement, classify the match as a draw and mark both players as potential cheater to be monitored, e.g. ban them if 3 such cases happened in a certain time span. This follows the line of thinking of the comments in this question. But this would ban victims that just had the misfortune to run into cheaters that only cheat every once in a while.

# Answer
You're right. In a P2P connection, cheating is always a possibility. You mentioned a referee, but for P2P games, there's no authority to be a referee unless one of the players is considered the authority. That makes the P2P become client-authoritative, which brings you back to the issue of a cheater having authority over the game.

The only real solution against cheating is to build a client-server architecture where an independent server has the authority over the game. The reason why this solution is not as commonly used in fighting games is the added latency that the traffic between the client and the server adds to the game.

I've heard that Edgegap relies on edge computing to reduce latency for use cases like this. You can check out the case study they did with a 1v1 fighting game here: https://edgegap.com/2020/05/15/case-study-lower-lag-improve-fairness-in-1vs1-game/
> 1 votes

---
Tags: networking, multiplayer, rts, anti-cheat, peer-to-peer
---


# Question
Title: How do I create a toggle button in Unity Inspector?
I want to create a tool similar to Unity's Terrain tool, which has some nice toggle buttons in the inspector:

How can I achieve similar design to this? I know how to create normal buttons and other UI components in the inspector, but I can not find enough information to make the buttons toggle.

So far I have used normal toggles that produce a checkbox:

```
var tmp = EditorGUILayout.Toggle( SetAmountFieldContent, _setValue );

if ( tmp != _setValue )
{
  _setValue = tmp;
  if ( _setValue )
    _smoothValue = false;
}

tmp = EditorGUILayout.Toggle( SmoothValueFieldContent, _smoothValue );

if ( tmp != _smoothValue )
{
  _smoothValue = tmp;
  if ( _smoothValue )
    _setValue = false;
}

```

Setting the toggle `GUIStyle` to "Button" does not produce the wanted result. The text or image content goes on left of the button instead of inside.

```
var tmp = EditorGUILayout.Toggle( SetAmountFieldContent, _setValue, "Button" );

```

Also none of the options found in GUISkin does not seem to help.

# Answer
> 8 votes
I solved this problem by using buttons instead of toggles.

First define two button styles before any functions:

```
private static GUIStyle ToggleButtonStyleNormal = null;
private static GUIStyle ToggleButtonStyleToggled = null;

```

Then in `OnInspectorGui()` make sure they are generated if null:

```
if ( ToggleButtonStyleNormal == null )
{
  ToggleButtonStyleNormal = "Button";
  ToggleButtonStyleToggled = new GUIStyle(ToggleButtonStyleNormal);
  ToggleButtonStyleToggled.normal.background = ToggleButtonStyleToggled.active.background;
}

```

And then use the idea proposed by @jzx to toggle the styles:

```
GUILayout.BeginHorizontal(  );

if ( GUILayout.Button( SetAmountFieldContent, _setValue ? ToggleButtonStyleToggled : ToggleButtonStyleNormal ) )
{
  _setValue = true;
  _smoothValue = false;
}

if ( GUILayout.Button( SmoothValueFieldContent, _smoothValue ? ToggleButtonStyleToggled : ToggleButtonStyleNormal ) )
{
  _smoothValue = true;
  _setValue = false;
}

GUILayout.EndHorizontal();

```

This produces what I wanted:

# Answer
> 6 votes
Here is a basic, but simple way to do it:

```
 pressed = GUILayout.Toggle(pressed, "Toggle me !", "Button");

```

taken from here

# Answer
> 5 votes
Use GUILayout.Toolbar. The docs are misleading, it actually does run the buttons together:

Additionally, you can use styles "buttonleft", "buttonmid", "buttonright" to draw these button style directly.

```
        var left = GUI.skin.FindStyle("buttonleft");
        GUILayout.Button("left only button", left);

```

# Answer
> 4 votes
Toggle returns the current state of the button - either the same state passed in *value* or the new value as changed by the user. So a better pattern would be...

```
// TODO: Initialize these with GUIContent
private GUIContent _toggleButtonDepressedLabel;
private GUIContent _toggleButtonDefaultLabel;

// Current toggle state
bool _toggleButtonState;

void DisplayToggle()
{
    var image = _toggleButtonValue
                ? _toggleButtonDepressedLabel
                : _toggleButtonDefaultLabel;
    var newState = EditorGUILayout.Toggle(image, _toggleButtonState);
    if (newState != _toggleButtonState)
    {
        _toggleButtonState = newState;
        OnToggleButtonChanged();
    }
}

void OnGUI ()
{
    DisplayToggle();
}

void OnToggleButtonChanged()
{
    // Do stuff.
}

```

You can use the same state-dependent swapping pattern for GUIStyles.

```
private GUIStyle _toggleButtonDepressedStyle;
private GUIStyle _toggleButtonDefaultStyle;
// ...
    var image = _toggleButtonValue
                ? _toggleButtonDepressedLabel
                : _toggleButtonDefaultLabel;
    var style = _toggleButtonValue
                ? _toggleButtonDepressedStyle
                : _toggleButtonDefaultStyle;
    var newState = EditorGUILayout.Toggle(image, _toggleButtonState, style);

```

# Answer
> 3 votes
2022 solution here:

I needed to do such a thing for selecting custom tools like in a Collider component inspector.

The simple way of doing this is to use

```
EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit"), this);

```

which draws a series of buttons for all the available tools of the given component.

Internally, this series of button is created like this:

```
// The whole element is made of a label and one or more selectable buttons in a horizontal layout
using (new EditorGUILayout.HorizontalScope())
{
    // Draw Label
    EditorGUILayout.PrefixLabel("Edit 2");

    // Start Change check to see if we clicked on an already selected button
    EditorGUI.BeginChangeCheck();
    int prevIndex = index;
    // Draw "Toolbar" (a group of selectable buttons). "AppCommand" is the style used for the Tools toolbar
    index = GUILayout.Toolbar(index, new[]{ EditorGUIUtility.IconContent("Profiler.Video") }, "AppCommand");
    // Enter the condition if a button is pressed (even an already selected one)
    if (EditorGUI.EndChangeCheck())
    {
        // if we clicked on the same index, deselect it
        if (index == prevIndex)
            index = -1;
    }
}

```

which gives me the same result as the first solution:

source used:

CapsuleColliderEditor.cs

EditorToolGUI.cs

# Answer
> 0 votes
You can do this:

```
private GUIStyle buttonStyle;
private bool enableToogle;

public override void OnInspectorGUI()
{
    buttonStyle = new GUIStyle(GUI.skin.button);
    enableToogle = GUILayout.Toggle(enableToogle, "Toogle Me", buttonStyle);

    if(enableToogle)
    {
        // your stuff here
    }
}

```

It's very important that you instanciate `buttonStyle` inside `OnInspectorGUI()` otherwise you'll get an error. Also, don't do `buttonStyle = GUI.skin.button;` because you would be copying the `skin.button` reference and any change on `buttonStyle` would be changing all buttons styles.

---
Tags: unity
---


title: Line of sight on a 2d grid

text:
# Question
Title: Line of sight on a 2d grid
I've been looking for similar questions here and on google, but none have worked for me yet. I have a game, where I have a 2d array of square tiles (they're objects with accessible x and y pixel coords, side length in pixels, and whether are they see-through).

In there, there are enemies and the player. They can move independently from the grid (as in, pardon the example, Minecraft), and I have got access to their coords. What I want is a function that will tell me if a given enemy can see the player or not (just returning bool). Can you help me?

EDIT: I used Bresenham. If anyone there is from Poland, a great description of Bresanham's jest tutaj :http://edu.i-lo.tarnow.pl/inf/utils/002\_roz/2008\_06.php :)

# Answer
Just use a line drawing algorithm, e.g. Bresenham's line algorithm.

Instead of using pixel coordinates, you're using tile offsets (round the position or do multiple checks). And rather than drawing the line, you're considering the "drawn on" tiles for lookup.

If you'd have to draw at tile `(5, 4)`, then you'll check whether that tile is solid or not (i.e. whether it blocks line of sight).

If your line reaches the player without being blocked, the enemy is able to see them.
> 3 votes

# Answer
I agree with Mario — use a line drawing algorithm. However, there are simpler algorithms for drawing lines. The one I use is based on interpolation. Off the top of my head:

```
len = max(abs(x2-x1), abs(y2-y1))
loop for i from 0 to len:
    # interpolate between (x1,y1) and (x2,y2)
    t = float(i)/len
    # at t=0.0 we get (x1,y1); at t=1.0 we get (x2,y2)
    x = round(x1 * (1.0-t) + x2 * t)
    y = round(y1 * (1.0-t) + y2 * t)
    # now check tile (x,y)

```
> 2 votes

# Answer
To draw a line you might use also the very simple algorithm that uses the very simple slope formula y=ax+b (or x=ay+b). It requires one div and then uses float computations, but divs are no longer that slow now, same for float operations, and anyway such cost has to be balanced with the high number of branches that Bresenham uses.
For C++ Bresenham will be faster, for javascript the branch cost is so high that using a plain for loop with no branch will be faster.
As for the coding, slope drawing is way simpler than Bresenham.

I made a small demo in javascript, in which i included the linear interpolation (lerp) method that @amitp mentions.

lerp, used with the proper distance, the manhattan distance, generates exactly the same pointset as slope. (thx to @amitp for his comments/fiddle) .

lerp uses 4 muls , 5 add, and 2 roundings per points, when slope uses 2 add and 1 rounding per point, but lerp win on the line of code count.

fiddle is here :

http://jsfiddle.net/gamealchemist/M9y6z/4/

Code for slope drawing :

```
// draws a line using y=ax+b or x=ay+b
function line_slope(x1, y1, x2, y2) {
    // round input
    x1 = Math.floor(x1);
    x2 = Math.floor(x2);
    y1 = Math.floor(y1);
    y2 = Math.floor(y2);
    var pxCount = 0;
    if (Math.abs(x1 - x2) > Math.abs(y1 - y2)) {
        // first quarter
        if (x1 > x2) {
            // make it from left to right
            var swp = x1;
            x1 = x2;
            x2 = swp;
            swp = y1;
            y1 = y2;
            y2 = swp;
        }
        pxCount = x2 - x1;
        var slope = (y2 - y1) / (x2 - x1),
            y = y1;
        for (var x = x1; x <= x2; x++, y += slope) {
            context.fillRect(x, y, 1, 1);
        }
    } else {
        // second quarter
        if (y1 > y2) {
            // make it from top to bottom
            var swp = x1;
            x1 = x2;
            x2 = swp;
            swp = y1;
            y1 = y2;
            y2 = swp;
        }
        pxCount = y2 - y1;
        var slope = (x2 - x1) / (y2 - y1),
            x = x1;
        for (var y = y1; y <= y2; y++, x += slope) {
            context.fillRect(x, y, 1, 1);
        }
    }
}

```

and for linear interpolation (lerp) :

```
// draws a line using linear interpolation
function line_lerp(x1, y1, x2, y2) {
    x1 = Math.floor(x1);
    x2 = Math.floor(x2);
    y1 = Math.floor(y1);
    y2 = Math.floor(y2);
    var length = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2));
    var tIncr = 1/length ;
    for (var t = 0; t <= 1; t+=tIncr) {
        var lx = Math.round(x1 * t + x2 * (1 - t));
        var ly = Math.round(y1 * t + y2 * (1 - t));
        context.fillRect(lx, ly, 1, 1);
    }
}

```
> 0 votes

# Answer
Here is an old VB function that implements a solid square grid LOS that works great.

I hope this helps someone out.

```
Function CheckSquare(ByVal row, ByVal col) As Boolean
  ' Checks if the terrain type at map(col,row) is see through
  Dim result As Boolean

  'DotSquare P(col, row), vbBlue

  CheckSquare = TerrainTypes(Map(col, row)).SeeThrough

End Function

Function CheckSquareLOS(ByVal srow, ByVal scol, ByVal trow, ByVal tcol) As Boolean

Dim sx As Long, sy As Long, tx As Long, ty As Long, ex As Long, ey As Long
Dim x As Double, y As Double

' First check if the values are in range (ValidSquare is a function to test the square is within bounds on your map)
  If Not ValidSquare(P(scol, srow)) Then Stop ' : Exit Function
  If Not ValidSquare(P(tcol, trow)) Then Stop ' : Exit Function

  sx = scol * 3780: sy = srow * 3780
  tx = tcol * 3780: ty = trow * 3780
  tx = tx - sx: ty = ty - sy: sx = 0: sy = 0: x = scol: y = srow

' Repeat the following until we reach the target square or we are blocked

 While (srow <> trow) Or (scol <> tcol)

    If ty = 0 Then
     ' NPrint "Horizontal straight line"
     scol = scol + 1 * Sgn(tx)
    Else
      If tx = 0 Then
        ' NPrint "Vertical straight line"
        srow = srow + 1 * Sgn(ty)
      Else
        ey = 1890 * Sgn(ty)
        ex = sx + (ey - sy) * tx / ty
        If Abs(ex) < 1890 Then
          sx = ex: sy = -ey: srow = srow + Sgn(ty)
        Else
          ex = 1890 * Sgn(tx)
          ey = sy + (ex - sx) * ty / tx
          If Abs(ey) < 1890 Then
            sx = -ex: sy = ey: scol = scol + Sgn(tx)
          Else
          ' We must be going through a corner
            If Not CheckSquare(srow + Sgn(ty), scol) And Not CheckSquare(srow, scol + Sgn(tx)) Then
              CheckSquareLOS = False: Exit Function
            End If
            sx = -ex: sy = -ey: srow = srow + Sgn(ty): scol = scol + Sgn(tx)
          End If
        End If
      End If
    End If

    If (srow <> trow) Or (scol <> tcol) Then

      If CheckSquare(srow, scol) = False Then
        CheckSquareLOS = False: Exit Function
      End If

    End If

  Wend

' If view hasn't been blocked up until now, it must be a clear LOS

  CheckSquareLOS = True

End Function

```
> 0 votes

---
Tags: c++, 2d, grid
---


# Question
Title: How do you determine if a texture is primarily dark or light?
Particularly, how do you implement Color.GetBrightness (?)

```
public static bool isDark(Texture2D tex,float threshold=0.1f)
    {
        float sum = 0 ;
        for (int x = 0; x < tex.width; x++)
        {
            for (int y = 0; y < tex.height; y++)
            {
                sum += GetBrightness(tex.GetPixel(x, y));
            }
        }
        sum /= (int)(tex.width*tex.height);

        if (sum < threshold) return false;
        return true;
    }
    static float GetBrightness(Color color)
    {
        return (color.r + color.b + color.g) / 3f;
    }

```

# Answer
Dark and Light is a subjective feeling. First of all you'd need to define what you want to consider dark, or light.

Once you have that defined, start calculating.

First of all, I would not just add all components and divide them. Here is a simple example (For simplicity I go with ints, though it is the same for floats:

`r:100 b:100 g:100 = 300 / 3 = 100`

`r:250 b:50 g:0 = 300 / 3 = 100`

As you can see it is not as simple as taking all three channels.

What I would do instead is define a brightness factor per channel: e.g. red might not feel as bright as green. Then take this factors and calculate the amount.

This could be as simple as `r * 1.0 g * 1.3 b * 0.7 / 3`

The complexity is up to you.

Another (rather dumb) way is taking all channels and just adding them. Define threshold of say 400 is bright. Then `r:255 + g:105 :b:0 = 360` Not bright `r:255 + g:255 :b:50 = 560` Bright
> 0 votes

# Answer
A conventional way to determine the lightness of a colour is to compute its relative luminance for linear RGB data, or luma, if the colours you're working with are in gamma-compressed encoding (as is typically the case for textures).

Assuming your image is in sRGB format (gamma-compressed, ITU-R BT.709 colour primaries and white point), you'd implement this like so, using the colour coefficients from the links above:

```
static float GetLuma(Color color) {
    // Rec. 709 colour primaries.
    const float r = 0.2126f;
    const float g = 0.7152f;
    const float b = 0.0722f;

    return color.r * r + color.g * g + color.b * b;
}

```

You can make your categorization function a little faster by using one call to `GetPixels()` instead of many calls to `GetPixel()`:

```
public static bool IsDark(Texture2D tex, float threshold=0.1f)
{
    float sum = 0;
    var pixels = tex.GetPixels();
    foreach (var pixel in pixels)
        sum += GetLuma(pixel);

    sum /= pixels.Length;

    return sum >= threshold;
}

```
> 0 votes

---
Tags: unity, image-processing
---


# Question
Title: Getting data out of an AoT Dictionary in Unity using Visual Scripting
I have a NormalizedWidth AoT Dictionary with a Key of type String (basically, the alphabet)... and a Value of type Float. You can see it on the left side of this screenshot:

Here's what I'm doing: I have a string with five characters in a word. I'm splitting that string into a char array, and then looping through that array with a For Each Loop.

What I'd like to do is look up with the width of each of those characters, which is stored in a NormalizedWidth AoT Dictionary. Or at least I am trying to! I am currently using a Get Dictionary Item node to try and get values out of the. But as each character is sent into the node, the output is given as Null. (See picture above).

I must be making a mistake. The data appears to be there, but I am failing to access it. Should I be using a different node to get data out of the Dictionary... or is there another mistake I'm making? Thank you!

# Answer
The method `ToCharArray` will generate a `char[]`, in which each element is of type `char` instead of `string`, which is confusing because some nodes on the bolt interface are generic, which prevents the display of the types. You can convert the key to string type through the `ToString` method:

You can see the difference in their colors on the runtime bolt interface(which is very obscure):

Edit:

What if I don't have an `Object.ToString` node? Visual Scripting allows you to define your own assemblies. You can decide which nodes are needed. This can save *memory/search time/time of recompiling nodes.etc*. For example, maybe your 2D project doesn't need the unity VR/AR modules, you can cancel them manually.

Maybe you deleted some assemblies manually causing the System assembly to be missing. And `Object` is in it.

Go to `Edit` \> `Project Settings` \> `Visual Scripting` \> `Node Library`:

You can simply reset the configuration because the default configuration includes System (referenced by other assemblies). You can also manually click `+` to add System.

And dont forget to click `Regenerate Nodes` button.

If it doesn't work still, try to reset the configuration of `Type Options`, and regenerate it again.

Finally, search for `object.tostring` in the script interface:
> 2 votes

---
Tags: unity
---


title: Displaying a RenderTexture in 2D

text:
# Question
Title: Displaying a RenderTexture in 2D
I'm new to Unity and game programming, so I apologize in advance for any embarrassingly bad stupidities.

I'm not having any luck trying to reproduce the RenderTexture example at the bottom of this page: https://docs.unity3d.com/2022.2/Documentation/Manual/class-RenderTexture.html

The only difference is that I'm trying to recreate it in a 2D project, so instead of a 3D cube, I'm trying to apply the RenderTexture to a flat square. The issue is that nothing is appearing in the square once I set everything up.

The setup is (not everything, but hopefully enough):

1. I've created a PNG file my sprite graphic, which is just a single color (white) object on a transparent background. I put that in my Assets directory.
2. I went into Unity and dragged that sprite from the Project window into my scene in the Hierarchy window. I moved the sprite out of the main camera area.
3. I created an auxiliary camera and pointed it at the sprite.
4. I created a RenderTexture and assigned it to the TargetTexture of the auxiliary camera. I set it up to be Orthographic and sized it appropriately so that the sprite is appearing in the aux camera's preview window. It's just a white image on a black background.
5. The instructions say to create a cube, but since I'm working in 2D, I've created a Square sprite.
6. The instructions say to drag the RenderTexture onto the cube to create a material for it, but that doesn't work for me. It doesn't do anything to drag the RenderTexture onto the Square.

I guess this is point where I should stop. I went further, creating a material and stuff, but it didn't get me anywhere.

I just want to know why this doesn't work. What am I not understanding about this?

# Answer
> 4 votes
In the upper right corner is a 3D Quad (MeshRenderer) and in the lower right corner is a 2D Square (SpriteRenderer). Now let me explain the difference and how to create them.

Using the shortcut to create a mesh(dragging the Render Texture onto the mesh) will automatically create a material with a standard shader, and set the albedo as the dragged texture. So naturally this mesh will be affected by lighting.(I added a yellow direct light there). And creating a sprite renderer(creating a new material with a custom shader) directly displays the color of the texture, which depends on the shader and can be further extended.

Why can't you drag the texture to the spriteRenderer for shortcut operations? spriteRenderer requires a material to have a `_MainTex` parameter, the default shader(*Sprites/Default*) has only one texture channel (and is already used by spriteRenderer), so it is unreasonable to attach an extra material to SpriteRenderer's material. This is why the new version of unity sets `_MainTex` is inoperable. The sprite is designed to display an image only, and such a setup is reasonable.

Anyway, we can create a custom shader, provide a \_MainTex parameter but not use it, and create a new texture channel to place the RenderTexture, and use its color.

Create a new material, select the shader as the custom shader below, and set it as the material of the SpriteRenderer. set the RenderTexture to `_SubTex`.

```
Shader "Custom/NewShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _SubTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

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

            sampler2D _MainTex;
            float4 _MainTex_ST;

            sampler2D _SubTex;
            float4 _SubTex_ST;

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

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_SubTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

```

Some extra notes to clarify:

There are two ways to achieve *Displaying a RenderTexture*:

1. Plan A: Use a 3D Quad (MeshRenderer)

1. Drag the renderTexuture onto this mesh according to the tutorial instructions.
    2. **And add a light to your scene**. Because this texture is used as an albedo for the mesh. Its final color is affected by lighting, if there is no lighting it is black.
2. Plan B: Use a 2D Square (SpriteRenderer)

1. Create a `.shader` file in your `Assets` dir. And copy the code above into it.
    2. Create a new material and select the shader for it.(`Custom/NewShader`)
    3. Drag the renderTexuture file to the material(`_SubTex`).
    4. Drag the material to the 2D Square.

> the preview window displays my sprite fine, but my square is still white in the end.

Because the spriteRenderer is used to display a sprite, it will **overwrite** the texture of the sprite to the material at runtime. so `_MainTex` is already used by spriteRenderer. You can not use that.

So we could create a new shader with extra texture paramater(`_SubTex`) and just ignore `_MainTex`. It will be fine.

---
Tags: unity
---


# Question
Title: Preventing other animations from resetting when a new animation starts playing
I'm playing some animations through a C# script. In such script, I'm not using any other methods except `GetComponent<Animation>()` and `Play()`. The animations are of opening/closing car doors and are being played from separate, different functions.

When I open a new door, the last opened door goes back to its default state of being closed. How can I stop that from occurring? I want the doors to stay open until I close them again.

All doors and animations belong to a single object, which is a car model made by my coworker. It has one joint bone for each door. There's no skinned mesh renderer component.

Here's one of the functions:

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

public class handle : MonoBehaviour
{
    public GameObject Car;
    private Animation anima;
    public bool bootspaceAnim = false;

    void Start()
    {
        anima = Car.GetComponent<Animation>();
    }

    public void bootspaceHandle()
    {
        if (bootspaceAnim == false)
        {
            anima.Play("Bootspace_Anim");
            anima["Bootspace_Anim"].speed = 1.0f;
            anima["Bootspace_Anim"].time = 0;

            bootspaceAnim = true;
        }
        else
        {
            anima.Play("Bootspace_Anim");
            anima["Bootspace_Anim"].speed = -1.0f;
            anima["Bootspace_Anim"].time = anima["Bootspace_Anim"].length;

            bootspaceAnim = false;
        }
    }
}

```

# Answer
> 1 votes
This is what animation layers in the animator controller are for. Each animation layer is a separate state-machine. So it is possible for each layer to play a different animation at the same time. The controlled object will then play all the animations simultaneously.

Put the animations of each door (or any other sub-part of the object you want to animate independently) on an own animation layer. Then use `animator.Play(state, layerNumber)` to play a specific animation state on a specific layer.

# Answer
> 0 votes
Separating the scripts/controllers for all animations finally resolved the bugs. It seems that the animations interfere with each-other when they're manipulated using a shared script/controller.

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


title: SVG Image in UI

text:
# Question
Title: SVG Image in UI
I'm using Vector Graphics for my SVG Images, though when I try to use it as a UI image (for a button) The image doesn't look as I expect, unless I use a Sprite Renderer. But unfortunately I can't do that because I need it to be a canvas button. In the image below: Left: SVG Image Right: Sprite Renderer.

# Answer
> 2 votes
Are you using a Gradient SVG?
(I'm not very familar with SVG, so I'm not sure. But it looks like you are using a Gradient SVG.)

I'm using a Gradient SVG, and the solution here solves my problem.

> For a Gradient SVG Image you will need to create a "Gradient" material which has the "Unlit/GradientVector" shader assigned. You can then assign the material to the SVG Image component. You will also have to change the Canvas "Additional Shader Channel" to include "TextCoord2" otherwise the UI system will ignore that data.

It is mainly 2 steps:

1. Create a Gradient Material and assign it to Component\<SVG Image\>.
(In url above, the Gradient material shader is "Unlit/GradientVector". The post is in 2018, as time past, the shader is a bit different now. I'm using Unity2020.3 today, the shader is "Unlit/VectorGradientUI".)
2. Change the Canvas "Additional Shader Channel" to include "TextCoord2".

---
Tags: unity, unity-ui, svg
---


# Question
Title: How can I rotate my BoxCollider2D 360 degrees around other colliders while maintaining a constant forward direction?
I'm trying to get my 2D character to rotate around colliders based on the current ground normal (sort of like in Mario Galaxy) detected by `Physics2D.CircleCast`, which I believe automatically interpolates the normals between two surfaces sharing a convex edge (e.g. the sharp edges of a `BoxCollider2D`). I also want my character to maintain a constant forward direction, in this case, `transform.right`.

To achieve this I'm setting my `transform.eulerAngles.z` to the value created by `Vector2.Angle(hit.normal, Vector2.up)`, but the problem is that this value is only accurate half of the time. If my character is moving around a circle, for example, only one half of the circle will provide an accurate rotation; the second half of the circle rotates me in the opposite direction. I'm not very comfortable with rotations or quaternions, but I've noticed that my z rotation will go from 0 to -180 on the "correct" half of the circle, and then start going in reverse again (-179, -178, etc.) on the other half. I've also noticed that the value shown in the inspector for my z rotation is not the same as the value I get when logging it to the console (console says 270, inspector shows -90).

```
using UnityEngine;
using DG.Tweening;

[RequireComponent(typeof(BoxCollider2D))]
public class RotationTest : MonoBehaviour
{
    [SerializeField]
    private float speed = 5;
    [SerializeField]
    private LayerMask rayMask;

    private BoxCollider2D boxCollider;

    private void Awake()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    void Update()
    {
        CheckForTerrainAndRotate();
    }

    private void CheckForTerrainAndRotate()
    {
        Vector2 direction = transform.right;
        transform.Translate(speed * direction * Time.deltaTime, Space.World);

        float circleCastRadius = boxCollider.bounds.extents.x + 0.05f;
        RaycastHit2D hit = Physics2D.CircleCast(transform.position, circleCastRadius, -transform.up, 5, rayMask);

        if (!hit)
        {
            transform.eulerAngles = Vector3.zero;
            return;
        }

        // Sets rotation using transform's euler angles
        transform.DORotate(new Vector3(0, 0, -Vector2.Angle(hit.normal, Vector2.up)), 0.1f, RotateMode.Fast);
    }
}

```

I'm using the `DOTween` library to handle lerping between two rotations, but am also having the same issue without it.

# Answer
> 1 votes
Vector2.Angle:

> Note: The angle returned will always be **between 0 and 180 degrees**, because the method returns the smallest angle between the vectors.

Maybe you need Vector2.SignedAngle:

> Note: The angle returned will always be **between -180 and 180 degrees**, because the method returns the smallest angle between the vectors.

Why *the value shown in the inspector for my z rotation is not the same as the value I get when logging it to the console*?

Because the values in inspector are euler angles. The actual rotation of transform is a quaternion. They are *different* values in memery, and they affect each other. Euler angles are "normalized" when generated from quaternions so that each value is in \[0,360). So `270` and `-90` are *same* actually.

---
Tags: unity, rotation, dotween
---


# Question
Title: Converting local rotation data from one rig onto another of a different orientation
I have an animated object which consists of a set of linked transforms. Think of them as bones. This object is animated - external to my software - and an API streams the local rotations - as quaternions - for every bone.

I want to map this onto another target object. The issue is that this object has a different setup where its root has a different default orientation and the child "bones" do as well. I can't modify the target bone structure, and the goal is to have it map onto any arbitrary bone structure. To give a simplified illustration, here are the first two bones in the hierarchy.

As you can see, if the root in the original (O\_Root) rotates around the z axis, to match that on the target, its root should rotate around its -x axis. Similarly, if the child in the original (O\_Child) rotates around the x axis, that should result in a rotation around y for the target's child.

I have this working for the root, by computing the quaternion transform needed to take me from original root to target root, with which I then multiply the incoming data. But for some reason I can't wrap my head around how to go down the hierarchy and correctly transform the local rotation data I receive to something which correctly applies to the target.

How would I approach this data conversion, assuming I know the default orientations in either hierarchy?

# Answer
First, we need to convert the animated local rotation quaternion `q` into the coordinate space of the new parent. We do that by remapping each axis individually. If changing handedness, we would also apply an extra negation to x,y,z, but that doesn't appear to apply here according to your diagrams.

```
var converted = new Quaternion(
    -q.z, // T_Parent.x = -O_Parent.z
    -q.x, // T_Parent.y = -O_Parent.x
    -q.y, // T_Parent.z = -O_Parent.y
     q.w  // angle identical
);

```

Applying this `converted` local rotation to a child under a parent with orientation `T_Parent` will yield a net orientation equivalent to `O_Child` (ie. its z+ axis points in the direction indicated by `O_Child.z`), which is not yet quite what we want.

So then we need to apply an extra twist to account for the difference between `O_Child` and `T_Child`:

```
var adapter = Quaternion.LookRotation(
    Vector3.up,   // T_Child.z+ = O_Child.y+
    Vector3.right // T_Child.y+ = O_Child.x+
);

```

Then we can chain these two effects:

```
var result = converted * adapter;

```

It's still early morning so there's a risk I've inverted one of these operations, but a solution following that rough outline should get you going in the right direction.
> 1 votes

---
Tags: unity, transformation, quaternion
---


# Question
Title: Trouble adding to a dictionary using a for loop
I'm trying to create a hotbar system where you can press 1 through 0 to activate abilities placed in the hotbar slots. Instead of a giant block of if/else statements I want to make a single check that can match the GameObjects in the array "Slots" with an associated KeyCode. To do that I made a simple for loop that adds a pair.

When I try to run the following code, I get the error **NullReferenceException: Object reference not set to an instance of an object.** I would assume this means that the object Slots\[i\] doesn't exist, but it definitely does for every iteration of the loop; I made 10 empty "slot" objects that are children of the Hotbar Object that runs this script.

Here's the code:

```
[SerializeField]GameObject[] Slots;
Dictionary<GameObject, KeyCode> SlotKey;

void Start()
{
    for (int i = 0; i < 10; ++i)
    {
        print(Slots[i].name);
        SlotKey.Add(Slots[i], (KeyCode)i + 48);
    }
}

```

When this code runs, it prints only the name of the first object in Slots (slot 0) and then gives me the error message. Running this loop with only the print works correctly, printing the names of slots 0 through 9. I also tried a foreach version:

```
    int i = 0;
    foreach (GameObject s in Slots)
    {
        print(s.name + (KeyCode)(i + 48));
        SlotKey.Add(s, (KeyCode)(i + 48));

        i++;
    }

```

This resulted in the exact same issue where every part of this loop works correctly except for SlotKey.Add.

Why does my dictionary seem unable to find the gameobjects in my array when the for loop itself seems to have no trouble with it?

# Answer
> 2 votes
You forgot to assign a value to your dictionary.

```
Dictionary<GameObject, KeyCode> SlotKey = new Dictionary<GameObject, KeyCode>();

```

Until you assign a value to a reference type variable, it holds the value `null`. Attempting to use any member of a null reference, such as calling `SlotKey.Add()`, will throw a null reference exception, because there's no dictionary there to call the function on, just an empty space for one.

You might have fallen out of the habit of doing this for value type fields, which have a non-null default assigned automatically, and serialized fields, which the serializer assigns for you based on the values in the inspector. But the serializer won't touch dictionaries, so that's up to you to initialize.

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


# Question
Title: When should I store a reference to a component instead of searching for it?
In the code I'm doing, I usually use global and local variables, as recommended.

If the variable is not going to be used in more than any method, I make it local, otherwise, I make it global.

In addition to using local variables with things that don't happen all the time, but every now and then. The player's shot for example: receives the value of a script that contains the player's data.

But I know that this isn't always clear, especially since I'm working on Unity.

**Suppose the following situation:**

I usually separate scripts by function, so I know exactly where to look when I want to modify something and also to completely replace it if I want to.

* script\_admGame - in this script will be the player's health, damage and movement speed;
* script\_playerMovement - in this script is that the character's movement will be programmed, taking the variable from the other script (script\_admGame);

```
void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        GameObject obj_adm = GameObject.Find("obj_adm");
        int moveSpeed = obj_adm.GetComponent<script_admGameControl>().moveSpeed;

        //any example
        transform.position += new Vector3(0,0,moveSpeed * Time.DeltaTime);
    }
}
```

**I have two fears:**

* be making minimal and irrelevant optimization savings;
* be saving memory, but overloading the processor/cpu;

That's because some functions are expensive to process (I don't know how interesting it is to run a function every frame instead of having one more variable in the script in question).

**Another important thing is that this speed can change if the player collects certain items, so it doesn't have a fixed value.**

As an alternative to the code shown above, I thought of making the character movement public in the script. Which would initially receive the value of script\_admGame and would sporadically undergo modifications when colliding with items, receiving a certain type of attack, etc.

In short, I would like to know precisely when to use each type of variable in unusual situations. Something like a general rule or convention. Or a way to check and compare two different applications.

**Link I read about but didn't give a clear picture of the situation I'm in doubt (pt-br):**

https://bookdown.org/jessicakubrusly/programacao-estatistica/funcoes-e-var-local.html

https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables

# Answer
Don't search for something every frame if you can store it.

```
// Make a member variable (NOT a "global") to cache a reference to your dependencies.
script_admGameControl _gameControl;

// Pay the search cost only once.
void Start() {
    _gameControl = FindObjectOfType<script_admGameControl>();
}

void Update() {
    if (Input.GetKey(KeyCode.W))
    {
        // Don't forget to scale by time when trying to move at a consistent speed.
        transform.position += new Vector3(0,0,_gameControl.moveSpeed * Time.deltaTime);
    }
}

```

The memory it costs to store one reference is trivial - a matter of bytes. The cost to search your entire scene for an object with a matching name, and to search that object for a matching component, grows with the number of objects in your scene and the number of components on that object. It's ridiculous to pay that cost every frame when you don't expect the answer to change frequently.
> 10 votes

# Answer
If you can have a reference, use the reference. *Never** search. If you cannot maintain a reference, something usually smells.

\*There are situations where searching is the best path forward. An example of when you should use search is if you are adding the components at runtime, and don't want to create unnecessary dependencies. Another example is when you are just hacking something together. But both of these examples smell.
> 3 votes

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


title: Unity reference randomly becomes null

text:
# Question
Title: Unity reference randomly becomes null
This issue has stumped be for 2 days and I still can't figure it out. I have a leveling script that references and image and subscribes to a global event.

```
public class LevelSystem : MonoBehaviour
{
    [SerializeField] Image _levelProgressBar;

    void Start()
    {
        GameEvents.OnPickUpExp += AddExp;
    }

    public void AddExp(int amount)
    {
        // Here _levelProgressBar becomes null on random playthroughs
        _levelProgressBar.fillAmount = (float)_experience / _experienceToNextLevel;
    }
}

```

and an item pickup script that triggers the events before destroying itself

```
public class ItemPickup : MonoBehaviour
{
    [SerializeField] int amount;

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            GameEvents.TriggerPickUpExp(amount);
            Destroy(gameObject);
        }
    }
}

```

Pretty simple stuff. But I can't for the life of me figure out why the image reference becomes null randomly. What I've tried

* Double check that I didn't have more than one instance of the LevelSystem component
* Checking that my division never results in a division by zero error

# Answer
I've found the issue! Basically I was making use of Unity's 'Enter play mode settings' and disabling the reload domain. Since I was using static events this causes the reference to remain in-between playthroughs. There are two options to fix this:

* Disable 'Enter play mode settings' in Project Settings/Editor.
* Unsubscribe to the events in `OnDisable`.
> 1 votes

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


title: Using collision with classes in pygame

text:
# Question
Title: Using collision with classes in pygame
I am trying to make some games using classes. But I got a problem when trying to make the ping pong game. I made 2 paddles and a ball but I just do not understand how should I make the collision between the paddles and the ball using classes. Sorry if my code is kind of unorganized and thank you for your help and patience

```
import pygame
from sys import exit

pygame.init()

#Screen details
screen_width=1000
screen_height=700
screen=pygame.display.set_mode((screen_width,screen_height))

class Paddle():

    def __init__(self, x,y,width,height,color):
        self.x=x
        self.y=y
        self.width=width
        self.height=height
        self.color=color

    def drawing(self):
        display=pygame.display.get_surface()
        pygame.draw.rect(display,(self.color),(self.x,self.y,self.width,self.height),0)

    def moving1(self):
        self.k=pygame.key.get_pressed()
        if self.k[pygame.K_UP]:
            self.y-=1
        if self.k[pygame.K_DOWN]:
            self.y+=1

    def moving2(self):
        self.k=pygame.key.get_pressed()
        if self.k[pygame.K_p]:
            self.y-=1
        if self.k[pygame.K_u]:
            self.y+=1

class Ball():

    def __init__(self,posx,posy,radius,color,speed):
        self.posx=posx
        self.posy=posy
        self.radius=radius
        self.color=color
        self.speed=speed

    def drawing(self):
        display=pygame.display.get_surface()
        pygame.draw.circle(display,(self.color),(self.posx,self.posy),self.radius,0)

    def moving(self):
        self.posx-=self.speed

        #I have to continue here. Not finished

paddle1=Paddle(0,130,50,100,(255,255,255))
paddle2=Paddle(980,350,50,100,(255,255,255))
ball=Ball(500,350,10,(255,255,255),1)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    screen.fill((0,0,0))

    paddle1.drawing()
    paddle2.drawing()
    paddle1.moving1()
    paddle2.moving2()
    ball.drawing()
    ball.moving()

    pygame.display.update()

```

# Answer
There are a couple of ways you can detect collisions in Pygame, the easiest in this case, I think, is to use `Rect.colliderect()`.

To use `.colliderect()` you first need some rects. In the case of the paddles that's easy, because your initialization parameters of `x, y, width, height` is a rect. To get the rect for the circle you can use a line similar to:

```
ballRect = pygame.draw.circle(display,(self.color),(self.posx,self.posy),self.radius,0)

```

Now that you have the three rects, in your ball class test for collisions:

```
def collideTest(self):
    bump = self.ballRect.colliderectlist([paddle1.rect, paddle2.rect])
    if bump >= 0:
        #bump holds either 0 or 1 indicating which paddle was collided with

```

So, now a couple of tips.

Classes should only handle the things which pertain to the class itself. They shouldn't be checking for keypresses, for example. Keypresses and other input should be checked for in your main game loop. The objects should keep track of things like their own position, appearance, movement, etc.

A class's methods should, again, pertain to the class. Your paddles and your ball, for example, should know how to draw themselves, so yeah, you should have a "drawing" method. (I usually call mine either `.draw()` or `.show()`.)

As I already indicated above, it should be your ball object which test for the collision, the reason being that it is the ball which must react to the collision. You should also add a couple of rects at the sides of the display which represent the goals. The ball object should determine whether it has collided with a paddle or a goal and react appropriately, either by reflecting off the paddle or by updating the appropriate score.

You can add a scoreboard class which keeps track of and displays the score for both players.

Good luck with it.
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Performance for range of effect in city builder
I am working on a city building game where all buildings are axis aligned rectangles. Currently I am using spatial hashing to detect if the insertion of a building intersects a building in the board.

Now I am implementing an effect system where every building placed has some effects that they can give to other buildings within a specific range. This happens during placement of a new building into the board.

Basically how it should work is, if I place a building within the range of another building in the board, the building in the board should receive the effects that the building I just placed has, and the building that I am placing should also receive the effects that the building in the board has. Basically like a handshake. This should happen with every building that is in the range of another building and will only take place and be calculated when a new building is inserted into the board.

Another thing to keep in mind is that if a building is already in the board and a new building is placed within its range, that new building should receive the effects of the building already in the board even if the other building does not have this building in its range. Thus this would be a one way transfer of effects and not a "handshake".

I currently have the exchange of effects working as it should, but its slow because I am checking every building range against every building. Thus the more buildings you place, the slower it gets.

I am looking for a way to make this faster whether it means changing from spatial hashing to some other spatial partitioning. I am currently reading Hierarchical Hash Grids but I don't know if this will benefit me at all.

# Answer
> 3 votes
Sounds like a use-case for influence maps.

1. For every kind of building effect you have, you create a two-dimensional array of integers with the size of your map. These are "influence maps" which represent the strength of each effect per map tile.
2. When you place a building emitting that effect, add 1 to every tile on the corresponding influence map which is within the area of effect range of the building. (If you don't want a building to benefit from its own effect, skip the tile(s) occupied by the building itself).
3. When you remove a building emitting an effect, subtract 1 from every tile within range.
4. When you want to check if a building is affected by a certain effect, check the corresponding influence map at its coordinate(s). It represents the number of overlapping buildings affecting it.

When the effect is a simple on/off thing, you can simply give the bonus when the value in that influence map is \> 0. You might wonder why not use a bool array then. Well, when the player places 3 buildings nearby and then removes 2, you still want to know that there is 1 building left covering the tile. So you need to keep accurate count of how many buildings cover each tile, even if you don't care if it's more than one. But you can also use this for more complex mechanics. Like measuring cumulative effects of multiple buildings in range and model effects which become weaker with distance.

Performance-wise, this is pretty cheap. Sampling the influence map is a constant-time operation. And you only need to change it when a building is added or removed, in which case the performance cost depends on the area covered by the building that was added / removed.

For some more inspiration on what you can do with influence maps, check out this GDC talk: Spatial Knowledge Representation through Modular Scalable Influence Maps

# Answer
> 0 votes
> Currently I am using spatial hashing to detect if the insertion of a building intersects a building in the board.

\[...\]

> \[I have the\] effects working as it should, but its slow because I am checking every building range against every building. Thus the more buildings you place, the slower it gets.

The spatial hash organizes objects by how close they are to each other. You're already using it for collision-detection, so also use it to get a list of buildings within a maximum area of effect of the building you have just placed (or are about to place or whatever).

---
Tags: 2d, spatial-partitioning, city-builder
---


# Question
Title: Why doesn't MeshCollider work in a build?
I have `MeshCollider`s in my scene that are shaped like an hourglass and it works perfectly fine in the editor. However, once I build on XCode and test on my iPhone, the `MeshCollider`s don't respond at all as if they weren't there.

Why is this happening and what are the reliable alternatives for creating this functionality besides creating a bunch of box and sphere colliders to make a cohesive pseudo-hourglass shape?

# Answer
First, try checking the "Convex" box in the mesh collider options just to see if the issue is related to that. If it is, you don't need a "bunch of box and sphere colliders", you can just use two convex cones arranged like an hourglass.

You should also read the documentation about Mesh Colliders because it notes some important quirks:

> * GameObjects that have a Rigidbody component only support Mesh Colliders that have Convex option enabled: the physics engine can only simulate convex mesh colliders.
> * For a Mesh Collider to work properly, the Mesh must be read/write enabled in any of these circumstances:
>     + The Mesh Collider’s Transform has negative scaling (for example, (–1, 1, 1)) and the Mesh is convex.
>     + The Mesh Collider’s transform is skewed or sheared (for example, when a rotated transform has a scaled parent transform).
>     + The Mesh Collider’s Cooking Options flags are set to any value other than the default.

As for why it's behaving differently on iOS than in the Editor, this could be due to a bug in Unity, or it could be related to your project settings (e.g. if you are using lower-detail meshes on iOS, or have code that is wrapped in `#if UNITY_IOS` directives).
> 1 votes

---
Tags: unity, collider, meshcollider
---


title: Collision callbacks not working

text:
# Question
Title: Collision callbacks not working
I'm a beginner at coding and wanted to make a quick little program to test my googling skills so far. I'm trying to make the player GameObject be given a speed boost when it collides with the "speed" GameObject and it doesn't work (the cube can still move but it isn't affected when colliding with the speed). Below is my player movement script:

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

public class Player : MonoBehaviour
{
    public float moveSpeed = 10f;
    void Update()
    {
        Vector3 position = transform.position;
        if (Input.GetKey("w")){
            position.y += moveSpeed * Time.deltaTime;
        }
        if (Input.GetKey("s")){
            position.y -= moveSpeed * Time.deltaTime;
        }
        if (Input.GetKey("d")){
            position.x += moveSpeed * Time.deltaTime;
        }
        if (Input.GetKey("a")){
            position.x -= moveSpeed * Time.deltaTime;
        }
        transform.position=position;
    }
}

```

And here is the power-up script. I used a `Debug.Log()` to figure out where the problem is at the line under the `private void`:

```
using UnityEngine;

public class Speed : MonoBehaviour
{
    public float speedIncrease = 5f;

    private void OnTriggerEnter2D(Collider2D collision){
        if (collision.tag == "Player"){
            GameObject player = collision.gameObject;
            Player playerScript = player.GetComponent<Player>();
            if (playerScript){
                playerScript.moveSpeed += speedIncrease;
            }
        }
    }
}

```

I come from Blender Stack Exchange where we provide all pieces of info we feel are relevant. Please let me know if that's not the case here or if I left something out.

**EDIT** here is what the objects look like in the inspector

the first one is player and the second one is the power up

# Answer
> 1 votes
Your scripts are okay, your issue is due to scene setup rather than coding.

In order to detect a trigger collision, OnTriggerEnter2D() has some requirements:

* Both objects must have one `Collider2D` Component.
* At least one `Collider2D` Component must be a trigger (**Is Trigger** field in the Inspector, or `isTrigger` property via code).
* At least one of the (two) objects must have a `RigidBody2D` Component attached to it.

The reason you need a `RigidBody2D` is, trigger collisions are computer during the Fixed Update when the physics update is run as well.

Then, you must add a `RigidBody2D` to either object before being able to detect the collision. If you don't need actual physics for your GameObjects, you can simply tick the **Is Kinematic** field of the `RigidBody2D` Component in the Inspector: this will prevent your object from moving due to gravity, forces and impulses

Moreover, don't worry about additional undesired physics behaviour: `RigidBody2D` \+ `Collider2D` behaves like a "solid" object; whereas `RigidBody2D` \+ trigger `Collider2D` detects collisions but doesn't affect self or others' movement (unless coded otherwise by yourself).

---

**Edit**

As stated in the documentation:

> A Kinematic Rigidbody 2D does not collide with other Kinematic Rigidbody 2Ds or with Static Rigidbody 2Ds; it only collides with Dynamic Rigidbody 2Ds.

This means that you can't use the current setup in your scene, as both objects are kinematic. You need to remove the `RigidBody` Component or make it not kinematic for (at least) one of the objects.

A different approach is discussed in this Unity Forum thread. You can enable additional collision pairs (e.g. Kinematic-Kinematic) by configuring *Project Settings \> Physics \> Contacts Pair Mode* to "Enable All Contacts". It is also recommended moving your kinematic bodies using `Rigidbody.MovePosition()` and `Rigidbody.MoveRotation()` from `FixedUpdate`.

# Answer
> 0 votes
I fixed the issue. I needed to give my player object a new tag called "Player"

---
Tags: unity, c#, 2d, collision-detection
---


title: How to animate a 2D top-down fish?

text:
# Question
Title: How to animate a 2D top-down fish?
Recently I've been trying to create a controllable fish character. The game is 2D and top-down.

My two approaches are:

* Skeletal Animation, which is versatile but looks too robotic. For example, no matter how hard I turn, the fish has the same turning animation.
* Procedural Animation, which I implemented using a line renderer following a tutorial from the channel Blackthornprod. It is very close to what I want, the fish is dynamic. The problem is that the fish loses all form when turning, some parts get thinner while some parts get thicker. The other thing is that it's hard to make it work with different types of fish sprites.

Here is an example, the black fish is animated using bones and the animator. The white fish is procedurally animated using a line renderer and the material with the sprite as a texture: \[

I want to be able to move the upper part of the fish, while the tail follows in a chain-like manner. Preferably avoiding line renderer as I'm not too comfortable with the pixelated edges and needing to loop through hundreds of positions to animate only one fish.

I would love any suggestions and I'm thankful to anyone who takes the time to help me!

# Answer
A solution was using the skeletal animation approach and adding inverse kinematics (let's call this IK) to the tail.

I made it so the tail IK wouldn't rotate with the body which meant that the tail IK wouldn't be affected by the rotation of the body. Then during the movement, I simply rotated the tail IK slowly towards the body.

```
tailSolver.rotation = Quaternion.RotateTowards(tailSolver.rotation, upperBody.rotation, lerpSpeed);

```

Here is an example of the animation using this approach:
> 2 votes

---
Tags: unity, 2d, animation, sprites, top-down
---


title: Graphical bug when changing room

text:
# Question
Title: Graphical bug when changing room
Here is a video showing the problem I'm encountering.

And here's my room change code:

```
if(room_exists(room_previous(room))) room_goto_previous();

```

# Answer
This behaviour happens because the game is rendering any frame without "cleaning" the previous one first, *and* your level view doesn't cover the whole screen (there are some transparent/translucent parts).

To solve this problem, you can either set a background or tell the game to clear the display buffer before drawing:

Clearing the buffer will fill it with a tint, after which object rendering takes place.
> 0 votes

---
Tags: game-maker, game-maker-studio-2
---


# Question
Title: Understanding User Input Behind the Scenes?
I am a bit confused on how user input is actually received and processed behind the scenes in a game engine. Let's say I have a simplistic game loop as follows...

```
while (true)
{
  processInput();
  updateEntities();
  renderGameWorld();
}

```
1. How is the engine able to access input in the processInput() function (for example a key press), if the key is both pressed and released very quickly while the program is executing a different function. By the time processInput() executes on the next cycle, it seems to me like the program would be "unaware" that this input ever happened.
2. Just from intuition (and I could be very wrong here), I'm guessing that things like keyboard input force a hardware interrupt, store the key value into some kind of device specific storage buffer queue, and then can be accessed and flushed at the correct time (next processInput() call) by a program?
3. If this is true, how does the engine handle stuff like multiple key presses. If I had a buffer queue that looked something like...

```
----> dequeue (front) [W, W, W, W ,W, Space, C] enqueue (back) <-------

```

If...

* "W" moves my player avatar forward
* "Space" is jump
* "C" is swing sword

Clearly my engine wouldn't care about the identical "W"'s, so would it just flush those until it reached the next unique input? Furthermore, can the engine even check more than one input in the queue per cycle of the game loop (most examples I've seen of processInput() use either a bunch of conditionals or a switch statement to check for a single input variable)? Any insight into this stuff is greatly appreciated.

# Answer
> 1 votes
> How is the engine able to access input in the processInput() function (for example a key press), if the key is both pressed and released very quickly while the program is executing a different function. By the time processInput() executes on the next cycle, it seems to me like the program would be "unaware" that this input ever happened.

This is assuming the user is able to press a button and release it in 1/30 of a second, which is quite fast, but it is still a valid point. What some games have done before to solve this, is add all input in a queue, and when the game reaches the part where it handles input, it handles all input in the queue.

This is why when some games start to lag, you suddenly see all your input be activated at the same time. Although not every game does it this way.

> Just from intuition (and I could be very wrong here), I'm guessing that things like keyboard input force a hardware interrupt, store the key value into some kind of device specific storage buffer queue, and then can be accessed and flushed at the correct time (next processInput() call) by a program?

This is mostly done in the framework/library you'd be using, as far as I'm aware it's not done in the hardware. A lot of frameworks/libraries also give you the power to implement this yourself, that way you have more control over how it works.

> If this is true, how does the engine handle stuff like multiple key presses. If I had a buffer queue that looked something like...

Usually when creating a queue of input, on top of storing which key was triggered, you also record its state. For example your queue can look something like `[{'W', "pressed"}, {'C', "presssed"}]`, this would tell you that on that frame, the `W` key was pressed (the character has to start moving until `W` is released) and the `C` key was pressed (the character attacks).

On a future frame you might receive something like `[{'W', "released"}]`, which is your signal to make the character stop walking.

If you do it this way, you only have to record when a key is pressed, and when it's released, and in between just assumed that the key is being held.

# Answer
> 0 votes
> How is the engine able to access input in the processInput() function (for example a key press), if the key is both pressed and released very quickly while the program is executing a different function. By the time processInput() executes on the next cycle, it seems to me like the program would be "unaware" that this input ever happened.

Back in the day, like on Commodore C\>64s or the TRS-80, the keyboard was a bunch of memory-mapped switches and to get keypresses without going through the operating system you had to grab that memory and figure out which keys were currently pressed.

On PCs, however, the keyboard is an actual I/O device. You press a key, the keyboard hardware debounces it, and queues up a "make" message. You release the key and the keyboard queues up a "break" message. Neither the operating system nor the processor is involved with detecting physical key presses or releases, and there isn't really any way that you could possibly hit and release a key so quickly that the device misses it.

> Just from intuition (and I could be very wrong here), I'm guessing that things like keyboard input force a hardware interrupt, store the key value into some kind of device specific storage buffer queue, and then can be accessed and flushed at the correct time (next processInput() call) by a program?

The quick answer is that modern USB and Bluetooth keyboards are polled, and the keyboard driver handles the message packets from the keyboard which are then made available to the operating system. Your programming language generally translates the keyboard data and puts it into a queue for easy "get next key" type usage, but you can bypass your programming language's `input()`, `inkey()`, `readkey()`, or `get_char()` statements and, instead, go through the operating system to interact with the driver more directly in order to get raw, or at least less-cooked, information.

> If this is true, how does the engine handle stuff like multiple key presses. If I had a buffer queue that looked something like...

I'm extemporizing a bit here, but the engine will get the make and break codes from the operating system's keyboard driver and will make a map of keys so that you can query the engine in the form of something like `key.ispressed(KEYW + KEYSPACE + KEYC)` to determine whether a particular key combination is currently being held down.

You indicated that your program would get a string of `w`s, for example, because the `w` key is being held down, but this isn't how it would work. If the engine were using a call like getkey() or something like that then yes, you'd get a buffered string of repeated `w`s when that key is held down, but that's why the engine wouldn't do it that way. The engine would get the raw make and break codes and manage the keyboard map itself.

DMGregory's suggestion to take a look at the keyboard functions from a few game engine APIs is a good one.

---
Tags: input, game-loop, hardware, operating-system
---


# Question
Title: 3D CharacterController ride moving platforms in Unity?
I have a **player controller script** that I'm writing that **uses the `CharacterController` component** to move around and handle collisions. I've been able to implement basically every feature that I want **except for moving platforms**.

**Some things to note:**

-For testing purposes, the **platform moves via the `Update()` function and does not have a `Rigidbody` component** attached to it. I don't think that rigidbodies would make a difference in the first place, but I could be wrong.

-Currently, when my player stands on the platform, it *kind of* does what it's supposed to do, but **it moves with a large amount of jitter.** In other words, the player isn't able to depenetrate itself as fast as the platform moves, therefore causing the jitter.

**Here's what I've tried:**

My initial thought was to create a **script on the moving platform that keeps track of its own velocity.** Then, on the player's `OnControllerColliderHit(...)` function, I would get the platform's velocity and add it to the player's velocity. **This caused the same jittery effect as before.**

My next idea was to **parent the player to the platform** whenever the player collided with it. This solution also did not work because **apparently `CharacterController`s do NOT like it when they are a child of a moving object.** The platform's transformations had little to no effect on the player, regardless of its speed. So once again, **the jitteriness continued.**

Just to test out possible solutions, I also tried combining the two previous fixes and still, the jitteriness lives among us.

**Closing thoughts:**

I'm beginning to think that it's not entirely possible, but I'm still holding out hope. I would also prefer to not to purchase an existing asset or switch to a `Rigidbody` component because neither would fit the style of my game.

Feel free to ask questions for more details and thank you in advance!

# Answer
I am not very familiar with the built-in CharacterController, but I can tell you how I have implemented this for my own character controller (although, I should warn you it is almost definitely more convoluted than necessary).

I made this class

```
using UnityEngine;
public class CopyMovement : MonoBehaviour
{
   [SerializeField] public GameObject target;
    Transform target_transform;
    Transform common_ancestor;

    Quaternion previousAncestorRotation;
    Vector3 previousAncestorPosition;

    Matrix4x4 previousTargetWorldToLocal;
    Quaternion previousTargetRotation;

    void Start(){
        if(target!=null)
            Initialize();
    }

    public void Initialize(){
        target_transform = target.transform;
        common_ancestor = Utils.FindCommonAncestor(transform, target_transform);
        if(common_ancestor!=null){
            previousAncestorPosition= common_ancestor.position;
            previousAncestorRotation = common_ancestor.rotation;
        }

        previousTargetWorldToLocal = target_transform.worldToLocalMatrix;
        previousTargetRotation = target_transform.rotation;
    }

    void LateUpdate()
    {
        //if the objects do not share ancestors, it's fairly straightforward: calculate the position and rotation of the constrained object in the local space of the previous parent pose, and
        //move it to the same pose in the _current_ local space

        //if they are part of the same hierarchy, however, the transformations of the common ancestors get applied twice to the constrained object (once naturally, once because of this script)
        //so, we just apply the inverse of the movement of the common ancestors to correct it. Simple, right?
        if(target!=null){

            Vector3 pointInPreviousLocalSpace = previousTargetWorldToLocal.MultiplyPoint(transform.position);
            Quaternion rotationInPreviousLocalSpace =  Quaternion.Inverse(previousTargetRotation) * transform.rotation;

            //set up the whole common-ancestor thing
            Quaternion offsetAncestorRotation = Quaternion.identity;
            Matrix4x4 ancestorMatrix = Matrix4x4.identity;
            if(common_ancestor!=null){
                offsetAncestorRotation = Quaternion.Inverse(previousAncestorRotation) * common_ancestor.rotation;
                ancestorMatrix = Matrix4x4.TRS(
                    common_ancestor.worldToLocalMatrix.MultiplyVector(previousAncestorPosition-common_ancestor.position),
                    Quaternion.Inverse(offsetAncestorRotation),
                    Vector3.one
                );
            }

            //the thing happens!
            Matrix4x4 theMatrix;
            if(common_ancestor!=null)
                theMatrix = common_ancestor.localToWorldMatrix* ancestorMatrix * common_ancestor.worldToLocalMatrix * target_transform.localToWorldMatrix;
            else
                theMatrix = target_transform.localToWorldMatrix;

            transform.SetPositionAndRotation( theMatrix.MultiplyPoint(pointInPreviousLocalSpace),
                Quaternion.Inverse(offsetAncestorRotation) * target_transform.rotation * rotationInPreviousLocalSpace);

            //store the current local space information for next time
            previousTargetWorldToLocal = target_transform.worldToLocalMatrix;
            previousTargetRotation = target_transform.rotation;

            if(common_ancestor!=null){
                previousAncestorRotation = common_ancestor.rotation;
                previousAncestorPosition = common_ancestor.position;
            }

        }
    }
}

```

And added a component of this type to the character. Then, inside of the character controller, when checking the ground that it is standing on, I change the settings of the CopyMovement. The abridged version of that code is something like this:

```
CopyMovement groundParentConstraint;

bool checkGround(){
    if(castRayDownwards()){
        if(groundParentConstraint.target != hit.collider.gameObject){
            groundParentConstraint.target = hit.collider.gameObject;
            groundParentConstraint.Initialize();
        }
        return true;
    }
    else{
        groundParentConstraint.target = null;
        return false;
    }
}

```

On top of this being a bit convoluted, it also does not work when the "parent" (the platform, in this case) has root motion animation, but do not ask me why, because I have no clue. But still, it's better than nothing.

Edit: The "find common ancestor" function:

```
public static Transform FindCommonAncestor(Transform tr1, Transform tr2){
    HashSet<Transform> ancestors1 = new HashSet<Transform>();
    Transform p = tr1;
    while(p!=null){
        ancestors1.Add(p);
        p=p.parent;
    }
    p=tr2;

    while(p!=null){
        if(ancestors1.Contains(p))
            return p;
        p=p.parent;
    }

    return null;
}

```
> 0 votes

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


# Question
Title: How do I implement this distortion ripple effect?
I would like to implement the following running effect in Unity. When the player character moves, it creates some sort of rings around it to give the impression of high speed.

I have searched for shockwave effects, ripple effects, water-drop effects but I either (1) could not get them to work on a specific region of the screen (most were post-processing effects that work on the whole screen), or (2) they did not look like this one.

I then tried to reverse-engineer this effect -- visually that is. I grabbed a screenshot of the player movement and it shows the following.

So basically I noticed a ring around the player where the terrain image is distorted. I have constrained that ring within the red ring to show it better. I have also added the red box to bring your attention to the image distortion I am talking about.

So my naïve interpretation of this effect is that it creates few rings of increasing size around the player, and it shows them one by one over time.

This kind of reduces my problem to creating one ring that blurs the terrain image like shown in the screenshot: some sort of elongated blurred pixels.

Now, I know next to nothing about shaders. I found this page (How to apply Image effect only on specific part of objects?) that implements a pixelating shader that can be applied to an object. So I used it as a starting point. I now have this ring:

and I need help changing the following shader function (taken from the previous link) to show the kind of distortion I want.

```
float4 frag(v2f IN) : COLOR
{
    float2 steppedUV = IN.grabPos.xy / IN.grabPos.w;
    steppedUV /= _PixelSize / _ScreenParams.xy;
    steppedUV = round(steppedUV);
    steppedUV *= _PixelSize / _ScreenParams.xy;
    //Sampling GrabTexture according to screen capture positon, tex2DProj is equivalent to tex2D (grabPos.xy / grabpos.w)
    return tex2D(_GrabTexture, steppedUV);
}

```

Any help is very much appreciated.

# Answer
> 1 votes
You normally do these things as a screen-space effect, by sampling the camera's opaque texture (if you use shadergraph, that would be the scene color node).

If you'll forgive me the lack of actual code, the general idea is to create a transparent mesh for the effect which is colored by sampling the opaque texture, using the screen-space coordinates of the fragment plus some offset. The offset is what creates the distortion.

In order to find the offset you could use the UV coordinates of the fragment. In this case, where the distortion is radial, the offset could be something like

```
offset = normalize( uv-float2(0.5,0.5) )

```

assuming, of course, that the center point of the mesh has UV=(0.5, 0.5)

To fully recreate the effect you show you also need to animate this, but I think this should be enough to get you started.

Edit:

Okay, so here's my shadergraph version of a very similar thing.

The most important part is this:

That is where the opaque texture (the scene color) is sampled. Basically, you want to figure out which pixel this fragment would be rendered to, and sample the color of a *different* pixel, with a relative offset. The offset, in this case, is calculated from the UVs. For that to work, you need a mesh that really has UVs (0.5, 0.5) at the center. Kind of like this:

Other than that, what the shader is doing is calculating a donut-like mask by combining multiple sphere masks (well, circles, really, but whatever), so that the entire thing is not getting distorted at the same time. By changing the parameter **t**, you can make it flow from the center outward.

Don't be scared by the fact that this uses a custom sphere mask node. The built-in one would work just fine, it's just that I'm insufferable and I needed to make it so that the effect starts exactly at t=0 and ends exactly at t=1.

The other thing you might see is a billboarding node in the vertex shader, but that **really** is beyond the scope of this question, I think.

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


title: Bottom-left cell position is incorrect?

text:
# Question
Title: Bottom-left cell position is incorrect?
I need to get the position of the bottom-left cell on my tilemap. I used `Floor.CellToWorld(Floor.cellBounds.min)` (Floor is the name of my tilemap) and I used Gizmos to see if it was working but it turned out to be in a weird place, the Rect Tool Also shows a wrong rect. Here's the image so I can explain better:

As you can see the yellow-ish part is the bottom-left part of my tilemap, the green circle (which is a wired sphere) is `Floor.CellToWorld(Floor.cellBounds.min)`, and those two thick white lines are shown by using the Rect Tool. So judging by this info, I think it's not a programming-related issue. Does anyone know how I can fix this?

# Answer
The root cause is that removing the tiles doesn't actually make the `cellBounds` shrink.

For the reason of saving memory resources, the memory allocation of tilemap is progressive, only when a tile is used for the first time, cellBounds will expand to include this tile. When the tile is deleted with the eraser, cellBounds will not shrink (avoid frequent application/reclaim memory). Unity provides a button to manually reset cellBounds named `Compress Tilemap Bounds`.
> 2 votes

---
Tags: unity, tilemap, coordinates, position
---