# Question
Title: Adding some new velocity to player in FixedUpdate. Should I use FixedDeltaTime or nothing?
I am trying to learn how to move objects in Unity without using the built in features like AddForce etc. Some tutorials on Unity website (and other places) is where I have got most of my 'knowledge' so far from.

This script for moving players (in topdown Space SHMUP) has been working fine for me and includes acceleration and artificial drag (basically 'smooth' movement, or like being on ice).

I'm sure this code is overly long, bloated, inefficient and in most cases downright wrong, but it is written for me to understand it, rather than simply using Unity Prefabs and AssetPackages i download from Store.

**QUESTION: Do I need the Time.fixedDeltaTime mutlipiers when calculating my 'delta\_v' values here. And also what about on the drag part at the bottom.**

As usual all help and comments are greatly appreciated. Thanks!

```
public class Player_Movement_SpaceShooter_TopDown : MonoBehaviour
{
public Vector2 maxVelocity;
public float drag;
public float moveForce;
private Rect moveBounds;

private Rigidbody2D rb;

private void Start()
{
    rb = GetComponent<Rigidbody2D>();
    moveBounds = Game_Manager.instance.ScreenBounds;
}

private void FixedUpdate()
{
    float input_h = Input.GetAxis("Horizontal");
    float input_v = Input.GetAxis("Vertical");
    Vector2 delta_v = Vector2.zero;

    delta_v.x += input_h * moveForce * Time.fixedDeltaTime;
    delta_v.x = Mathf.Clamp(delta_v.x, -maxVelocity.x, maxVelocity.x);
    delta_v.y += input_v * moveForce * Time.fixedDeltaTime;
    delta_v.y = Mathf.Clamp(delta_v.y, -maxVelocity.y, maxVelocity.y);

    Vector2 pos = rb.position;
    Vector2 vel = rb.velocity;
    if (pos.x < moveBounds.xMin)
    {
        pos.x = moveBounds.xMin;
        vel.x = 0f;
    }
    if (pos.x > moveBounds.xMax)
    {
        pos.x = moveBounds.xMax;
        vel.x = 0f;
    }
    if (pos.y < moveBounds.yMin)
    {
        pos.y = moveBounds.yMin;
        vel.y = 0f;
    }
    if (pos.y > moveBounds.yMax)
    {
        pos.y = moveBounds.yMax;
        vel.y = 0f;
    }

    rb.position = pos;

    rb.velocity = vel + delta_v;
    rb.velocity = rb.velocity * (1 - Time.fixedDeltaTime * drag);

}

}

```

It appears to me that if FixedUpdate was somehow slowed down, the velocity would get changed slower, the same with the enemy movement but I don't know how that would effect the gameplay and if/how the slowing-down would occur

# Answer
> 2 votes
It is important to use a delta time (like Time.fixedDeltaTime) because it will make your movement be consistent. If fixedUpdate is slower, fixedDeltaTime is bigger so the increase in delta\_v will be bigger.

# Answer
> 0 votes
You use Time.FixedDeltaTime when writing MonoBehaviours that you expect to use across multiple project or to share with others, that may use a different FixedDeltaTime and you want a consistent speed based on real time.

Personally, for most cases, I would just add a comment that speed is based on game updates. In fact, that what I like to do.

Example:

```
public class PlayerSpriteBehaviour: MonoBehaviour {
    public float speed = 1.0f; // In pixels per frame
}

```

Then if I use 30 updates per second in a project and 60 in another, I have to adjust speed in my `PlayerSpriteBehaviour`. But I'm happy with it.

Note that to have the following formula:

```
position.x += speed * Time.FixedDeltaTime;

```

I would have to use a different comment here:

```
public class PlayerSpriteBehaviour: MonoBehaviour {
    public float speed = 60.0f; // In pixels per second
}

```

Answer: You can use it or not as long as you understand the implications.

---
Tags: unity, physics, timestep, fixed-timestep
---


# Question
Title: 3D models budget. What matters more number of triangles or vertices
When I am making a model for a 3D game what should I take as a measure in my budget Polygons (triangles) or vertices? I have made an experiment with two sets 40000 cubes one with 8 vertices and 12 triangles, another with 24 vertices and 12 triangles. All was done in Unity and both of those were generated procedurally. To my surprise, both sets performed almost the same there was a very small difference between them.

Does it mean I should not worry about vertices count and only look at triangles count?

EDIT: I have made another experiment I have created a plane with 19602 triangles and 10000 vertices and another one with same ammount of tirangles but 39204 vertices. I have generated 4000 of both. Now less vertices won 14 fps to 19 fps. So I guess generally less is better, but only in large differences.

# Answer
> 17 votes
Let's imagine a big grid mesh, like one we might use for terrain. We'll render `n` triangles worth of it, covering say half our 1080p screen, in a single draw call.

If we weld all of our vertices and have no smoothing/texturing seams, then each triangle has 3 vertices and each vertex is shared by 6 triangles, so we have `n/2` vertices.

To render this we need to:

* Run the vertex shader at least `n/2` times

("at least" because our cache for vertex results is only so big. Sometimes we'll end up evicting a vertex we already transformed, then need it again for a later triangle that shares it and so re-run the vertex shader on it. So we don't get quite as much savings as it looks like on paper)
* Clip & cull `n` triangles.
* Rasterize & interpolate over at least 1920x1080/2 or about 1 million pixels of the frame buffer (since we said our terrain covers about half the screen).

("at least" because of the way GPUs work on quads of pixels, some fragments just outside the edges of polygons still get rasterized but then masked, meaning we process fragments twice. For a bumpy mesh we'll also get overdraw anywhere the mesh occludes itself, if we're not lucky enough to draw the frontmost polygon into the depth buffer first)
* Run the fragment shader for all those \>= 1 million fragments.
* Blend ~ 1 million results into the frame & depth buffers.

Okay, now let's unweld all of our vertices so now we have `3n` vertices to render, **six times more** than before! Our steps are...

* Run the vertex shader `3n` times.

(No asterisks due to caching since every vertex is used only once, though this means the cache can't save us any time)
* Clip & cull `n` triangles.
* Rasterize & interpolate over at least 1920x1080/2 or about 1 million pixels of the frame buffer.
* Run the fragment shader for all those \>= 1 million fragments.
* Blend ~ 1 million results into the frame & depth buffers.

...wait, *every step* except the first one is the same! So most of the work that the GPU does in a typical draw call is not directly related to the number of vertices used. The amount of screen coverage, overdraw, and total triangle count make up much more of the cost.

That doesn't mean vertices are completely free. If you share vertices when you can you get some modest savings from caching, especially if your vertex shaders are complicated or your hardware's vertex pipeline is weak (as was the case on some older consoles). But given that vertex count tracks proportional to triangle count plus or minus a constant factor, it's usually not as interesting a metric of overall mesh cost.

# Answer
> 2 votes
Neither.

Unless you're talking truly massive numbers of tris (millions), what you care about is:

* Number of rendered pixels
* Cost of fragment shader
* Number of draw calls (with the limit strongly depending on the device).

24 vertices times 4000 cubes gives 96'000 vertices.

640x380 pixels gives 243'200 fragments, and most devices support considerably larger resolutions.

You could re-run your experiment with 1'000'000 cubes, batched to avoid the draw call bottleneck(1 single model for 1'000 cubes).

# Answer
> 1 votes
Worth noting that if you're doing a WebGL application, vertex count quickly becomes a bottleneck in terms of file size for users to download. Same number of triangles but often 2-3 times more vertices than shown in DCC software. Better unwrapping can help a lot in this case by having less seams.

---
Tags: performance, vertex
---


# Question
Title: Unity baked lighting - blotchy shadows, bleeding and/or stiching
I have spent days trying to get baked lighting to look good. I use a simple low-poly style. No matter what I do, I get this type of effect (blotchy shadows and odd dark lines):

Here are my settings:

Baking a scene already takes around 4 hours, not sure I can increase the resolution any more without Unity crashing during the bake. Am I doing something wrong? Feel like Ive tried everything.

# Answer
> 0 votes
In my opinion, ambient occlusion is your culprit. In general, baking usually takes quite a long time; this is why render farms exist.

---
Tags: unity
---


# Question
Title: How do I get pixel to hex coordinates on an array based hex map?
I'm trying to make a pixel to coord function for a hex map but I'm not getting the math correctly, everything I try seems to be a little off, and the examples I've found were based on circled centered maps.

By 'array based' I mean the way the hexes are ordered, see pic.

The most accurate result I got was with the following code, but it is still off, and gets worse the more the values raise:

```
public HexCell<T> coordsToHexCell(float x, float y){
    final float size = this.size; // cell size
    float q = (float) ((1f/3f* Math.sqrt(3) * x - 1f/3f * y) / size);
    float r = 2f/3f * y / size;
    return getHexCell((int) r, (int) q);
}

```

Screen starts with 0,0 on top left, each cell knows its center.

All I need is a way to translate screen coordinates into hex coordinates. How could I do that?

# Answer
There are many hex coordinate systems. The “offset” approaches are nice for storing a rectangular map but the hex algorithms tend to be trickier.

In my hex grid guide (which I believe you've already found), your coordinate system is called “even-r”, except you're labeling them `r,q` instead of `q,r`. You can convert pixel locations to hex coordinates with these steps:

1. Convert pixel locations to *axial* hex coordinates using the algorithm described in this section. This is what your function does. However, you need to take one more step.
2. Those *axial* coordinates are fractional. They need to be rounded off to the nearest hex. In your code you use `(int)r, (int)q` but that only works for squares; for hexes we need a more complicated rounding approach. Convert the `r, q` to *cube* coordinates using the *axial to cube* formulas here. Then use the `hex_round` function here.
3. Now you have an integer set of *cube* coordinates. Your map uses “even-r”, not cube, so you need to convert back. Use the *cube to even-r offset* formulas from here.

I need to rewrite the pixel to hex coordinate section to make it much more clear. Sorry!

I know, this seems convoluted. I use this approach because it's the least error prone (no special cases!) and allows for reuse. Those conversion routines can be reused. The hex rounding can be reused. If you ever want to draw lines or rotate around a hex coordinate or do field of view or other algorithms, some of these routines will be useful there too.
> 13 votes

# Answer
There are two ways to handle this problem, in my opinion.

1. Use a better coordinate system. You can make the math much easier on yourself if you're clever about how you number the hexes. Amit Patel has the definitive reference on hexagonal grids. You'll want to look for **axial coordinates** on that page.
2. Borrow code from someone who has already solved it. I have some code that works, which I lifted from the Battle for Wesnoth source. Keep in mind that my version has the flat part of the hexes on top, so you'll have to swap x and y.
> 9 votes

# Answer
I think Michael Kristofik's answer is correct, especially for mentioning Amit Patel's website, but I wanted to share my novice approach to Hex grids.

This code was taken from a project that I lost interest in and abandoned written in JavaScript, but the mouse position to hex tile worked great. I used * **this GameDev article** * for my references. From that website the author had this image which showed how to mathematically represent all of the Hex sides and positions.

In my render class I had this defined in a method that allowed me to set any Hex side length that I wanted. Shown here because some of these values were referenced in the pixel to hex coordinate code.

```
                this.s = Side; //Side length
                this.h = Math.floor(Math.sin(30 * Math.PI / 180) * this.s);
                this.r = Math.floor(Math.cos(30 * Math.PI / 180) * this.s);
                this.HEXWIDTH = 2 * this.r;
                this.HEXHEIGHT = this.h + this.s;
                this.HEXHEIGHT_CENTER = this.h + Math.floor(this.s / 2);

```

In the mouse input class, I created a method that accepted a screen x and y coordinate, and returned an object with the Hex coordinate that pixel resides within. \*Note that i had a fake "camera" so offsets for render position are included as well.

```
    ConvertToHexCoords:function (xpixel, ypixel) {
        var xSection = Math.floor(xpixel / ( this.Renderer.HEXWIDTH )),
            ySection = Math.floor(ypixel / ( this.Renderer.HEXHEIGHT )),
            xSectionPixel = Math.floor(xpixel % ( this.Renderer.HEXWIDTH )),
            ySectionPixel = Math.floor(ypixel % ( this.Renderer.HEXHEIGHT )),
            m = this.Renderer.h / this.Renderer.r, //slope of Hex points
            ArrayX = xSection,
            ArrayY = ySection,
            SectionType = 'A';
        if (ySection % 2 == 0) {
            /******************
             * http://www.gamedev.net/page/resources/_/technical/game-programming/coordinates-in-hexagon-based-tile-maps-r1800
             * Type A Section
             *************
             *     *     *
             *   *   *   *
             * *       * *
             * *       * *
             *************
             * If the pixel position in question lies within the big bottom area the array coordinate of the
             *      tile is the same as the coordinate of our section.
             * If the position lies within the top left edge we have to subtract one from the horizontal (x)
             *      and the vertical (y) component of our section coordinate.
             * If the position lies within the top right edge we reduce only the vertical component.
             ******************/
            if (ySectionPixel < (this.Renderer.h - xSectionPixel * m)) {// left Edge
                ArrayY = ySection - 1;
                ArrayX = xSection - 1;
            } else if (ySectionPixel < (-this.Renderer.h + xSectionPixel * m)) {// right Edge
                ArrayY = ySection - 1;
                ArrayX = xSection;
            }
        } else {
            /******************
             * Type B section
             *********
             * *   * *
             *   *   *
             *   *   *
             *********
             * If the pixel position in question lies within the right area the array coordinate of the
             *      tile is the same as the coordinate of our section.
             * If the position lies within the left area we have to subtract one from the horizontal (x) component
             *      of our section coordinate.
             * If the position lies within the top area we have to subtract one from the vertical (y) component.
             ******************/
            SectionType = 'B';
            if (xSectionPixel >= this.Renderer.r) {//Right side
                if (ySectionPixel < (2 * this.Renderer.h - xSectionPixel * m)) {
                    ArrayY = ySection - 1;
                    ArrayX = xSection;
                } else {
                    ArrayY = ySection;
                    ArrayX = xSection;
                }
            } else {//Left side
                if (ySectionPixel < ( xSectionPixel * m)) {
                    ArrayY = ySection - 1;
                    ArrayX = xSection;
                } else {
                    ArrayY = ySection;
                    ArrayX = xSection - 1;
                }
            }
        }
        return {
            x:ArrayX + this.Main.DrawPosition.x, //Draw position is the "camera" offset
            y:ArrayY + this.Main.DrawPosition.y
        };
    },

```

Finally here is a screenshot of my project with the render's debug turned on. It shows the red lines where the code checks for TypeA vs TypeB cells along with the Hex coordinates and cell outlines
Hope this helps some.
> 6 votes

# Answer
I actually found a solution without hex math.
As I've mentioned in the question each cell saves it own center coords, by calculating the nearest hex center to the pixel coords I can determine the corresponding hex cell with pixel precision (or very close to it).
I don't think it is the best way to do it since I have to iterate to each cell and I can see how that could be taxing but will leave the code as an alternate solution:

```
public HexCell<T> coordsToHexCell(float x, float y){
    HexCell<T> cell;
    HexCell<T> result = null;
    float distance = Float.MAX_VALUE;
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            cell = getHexCell(r, c);

            final float dx = x - cell.getX();
            final float dy = y - cell.getY();
            final float newdistance = (float) Math.sqrt(dx*dx + dy*dy);

            if (newdistance < distance) {
                distance = newdistance;
                result = cell;
            }
        }
    }
    return result;
}

```
> 4 votes

# Answer
Here is the guts of a C# implementation of one of the techniques posted on Amit Patel's web-site (I am sure translating to Java won't be a challenge):

```
public class Hexgrid : IHexgrid {
  /// <summary>Return a new instance of <c>Hexgrid</c>.</summary>
  public Hexgrid(IHexgridHost host) { Host = host; }

  /// <inheritdoc/>
  public virtual Point ScrollPosition { get { return Host.ScrollPosition; } }

/// <inheritdoc/>
public virtual Size  Size           { get { return Size.Ceiling(Host.MapSizePixels.Scale(Host.MapScale)); } }

/// <inheritdoc/>
public virtual HexCoords GetHexCoords(Point point, Size autoScroll) {
  if( Host == null ) return HexCoords.EmptyCanon;

  // Adjust for origin not as assumed by GetCoordinate().
  var grid    = new Size((int)(Host.GridSizeF.Width*2F/3F), (int)Host.GridSizeF.Height);
  var margin  = new Size((int)(Host.MapMargin.Width  * Host.MapScale),
                         (int)(Host.MapMargin.Height * Host.MapScale));
  point      -= autoScroll + margin + grid;

  return HexCoords.NewCanonCoords( GetCoordinate(matrixX, point),
                                   GetCoordinate(matrixY, point) );
}

/// <inheritdoc/>
public virtual Point   ScrollPositionToCenterOnHex(HexCoords coordsNewCenterHex) {
  return HexCenterPoint(HexCoords.NewUserCoords(
          coordsNewCenterHex.User - ( new IntVector2D(Host.VisibleRectangle.Size.User) / 2 )
  ));
}

/// <summary>Scrolling control hosting this HexGrid.</summary>
protected IHexgridHost Host { get; private set; }

/// <summary>Matrix2D for 'picking' the <B>X</B> hex coordinate</summary>
Matrix matrixX {
  get { return new Matrix(
      (3.0F/2.0F)/Host.GridSizeF.Width,  (3.0F/2.0F)/Host.GridSizeF.Width,
             1.0F/Host.GridSizeF.Height,       -1.0F/Host.GridSizeF.Height,  -0.5F,-0.5F); }
}
/// <summary>Matrix2D for 'picking' the <B>Y</B> hex coordinate</summary>
Matrix matrixY {
  get { return new Matrix(
            0.0F,                        (3.0F/2.0F)/Host.GridSizeF.Width,
            2.0F/Host.GridSizeF.Height,         1.0F/Host.GridSizeF.Height,  -0.5F,-0.5F); }
}

/// <summary>Calculates a (canonical X or Y) grid-coordinate for a point, from the supplied 'picking' matrix.</summary>
/// <param name="matrix">The 'picking' matrix</param>
/// <param name="point">The screen point identifying the hex to be 'picked'.</param>
/// <returns>A (canonical X or Y) grid coordinate of the 'picked' hex.</returns>
  static int GetCoordinate (Matrix matrix, Point point){
  var pts = new Point[] {point};
  matrix.TransformPoints(pts);
      return (int) Math.Floor( (pts[0].X + pts[0].Y + 2F) / 3F );
  }

```

The rest of the Hex Grid Utilities For Games projectis available as Open Source, including the `MatrixInt2D` and `VectorInt2D` classes referenced above.

Although the implementation above is for flat-topped hexes, the Hex Grid Utilities library includes the option of transposing the grid.
> 3 votes

# Answer
I found a simple, alternative approach that uses the same logic as a regular checkerboard. It creates a snap-to-grid effect with points at the center of every tile and at every vertex (by creating a tighter grid and ignoring alternating points).

This approach works well for games like Catan, where players interact with tiles and vertices, but is not suited to games where players only interact with tiles, as it returns which center point or vertex the coordinates are closest to, rather than which hexagonal tile the coordinates are within.

## The Geometry

If you place points in a grid with columns that are quarter the width of a tile, and rows that are half the height of a tile, you get this pattern:

If you then modify the code to skip over every second dot in a checkerboard pattern (skip `if column % 2 + row % 2 == 1`), you end up with this pattern:

## Implementation

With that geometry in mind, you can create a 2D array (just like you would with a square grid), storing the `x, y` coordinates for each point in the grid (from the first diagram) - something like this:

```
points = []
for x in numberOfColumns
    points.push([])
    for y in numberOfRows
        points[x].push({x: x * widthOfColumn, y: y * heightOfRow})

```

Note: As normal, when you are creating a grid *around* the points (rather than placing dots *at* the points themselves), you need to offset the origin (subtracting half the width of a column from `x` and half the height of a row from `y`).

Now that you have your 2D array (`points`) initialized, you can find the nearest point to the mouse just like you would on a square grid, only having to ignore every other point to produce the pattern in the second diagram:

```
column, row = floor(mouse.x / columnWidth), floor(mouse.y / rowHeight)
point = null if column % 2 + row % 2 != 1 else points[column][row]

```

That will work, but the coordinates are being rounded to the nearest point (or no point) based on which invisible rectangle the pointer is within. You really want a circular zone around the point (so the snap-range is equal in every direction). Now that you know which point to check, you can easily find the distance (using Pythagoras' Theorem). The implied circle would still have to fit inside the original bounding rectangle, limiting its maximum diameter to the width of a column (quarter the width of a tile), but that is still large enough to work well in practice.
> 1 votes

---
Tags: java, hexagonal-grid
---


# Question
Title: Is passing big objects in parameters not performant?
let's say that I have a big main class with a lot of variables, subclasses, etc... in it. Like "IngameScreen"

What if this class is passed as a parameter very often for each frames ? For example there is a "playSound" function in it so every entity need to have this class injected to make a sound.

Does that affects performance ? Or is it something like "it's just a pointer so it costs pretty much nothing" ?

The language is Kotlin

# Answer
In Kotlin the size of the object passed via parameter does not impacted performance.

Here's why:

* Kotlin is designed to be fully interoperable fully with Java.
* Java alway uses pass-by-value.
* In Java the value of an object is always a reference to the object.
> 2 votes

# Answer
If you're passing by value it will involve allocating memory on the stack, copying over data, invoking the copy constructor, potentially creating more objects (which will have their own performance implications) and then undoing all of that on return.

If you're passing by reference it is just a pointer.

Is passing by value always slower? Depends on the object. If it's a simple object, like - say - a vec3, you're probably not going to even notice. If it's a complex object like a mesh with vertex buffers that needs to hit the disk during creation, then - ouch.

Sometimes passing by value is what you want, but that's going into more general programming territory which is maybe out of scope here.

So be sure that you know the characteristics of your objects and define an appropriate copy constructor if required.
> -1 votes

---
Tags: performance, kotlin
---


title: Gradle Build Error Unity 2019.1.6

text:
# Question
Title: Gradle Build Error Unity 2019.1.6
I found out that unity has deprecated the internal build system and has defaulted to gradle. I've not built with the gradle build system before, and now after upgrading to unity 2019.1 full version, I can't build an android project. And, I installed the android module using unity hub, what can I do to fix this? Screenshot1 Screenshot2 Screenshot3 Screenshot4 Screenshot5 Screenshot6

# Answer
> 2 votes
If anyone has the same problem, here's how I fixed it: At first, I didn't know what to do or if I was doing the right thing but I decided to try a bunch of different things:

* I had to update the JDK and SDK used by android studio, and set the path on unity instead of using the default that was installed by unity hub.
* Through the SDK manager, I installed SDK build tools for all API versions from 21 to the latest, then installed all sub files on Android 5.0.1(API 21).
* After that, I began to have a Daemon startup failed error and still couldn't build, then I thought that the problem couldn't be coming from the SDK, and my JDK functions correctly, so I thought of gradle files, then I downloaded full files of the latest gradle from the gradle website, unpacked it on a different folder and set the path on unity.
* The effort made no difference, then I searched my PC for cached gradle files or something similar, then I found a .gradle folder on C:\Users\name\
* I made a backup copy of the .gradle folder on a desktop folder, then deleted the original. Then built again, it took longer than usual, but unity successfully built the app, I built it again this time, while offline, and it was faster and built successfully.

---
Tags: unity, android, build-process
---


title: Rotation of sprite is not smooth

text:
# Question
Title: Rotation of sprite is not smooth
I am making a speed meter of car. Its pretty simple when ever speed increases or decreases the meter pin moves accordingly. I have done the movement part of pin but I am unable to get a smooth movement.

```
    public Image meterPin;

    const float maxPinAngle = -116f;
    const float minPinAngle = 16f;

    float meterMinSpeed = 10f;
    float meterMaxSpeed = 210f;

    void Update()
    {
        changeMeterSpeed();
    }
    void changeMeterSpeed()
    {
        meterMinSpeed = userSpeed;
        meterMinSpeed = Mathf.Clamp(meterMinSpeed, 0f, meterMaxSpeed);

        meterPin.transform.eulerAngles = new Vector3(0, 0, getTransformRotation());
    }

    float getTransformRotation()
    {
        float totalAngle = minPinAngle - maxPinAngle;

        float speedNormalized = meterMinSpeed / meterMaxSpeed;

        return minPinAngle - speedNormalized * totalAngle;
    }

```

The `userSpeed` value is calculated in another function in this script. The only issue is that the movement is not smooth. Any ideas if I can fix the smoothness issue in this script.

EDIT:

Here is a gif to explain whats happening.

Thanks

# Answer
You change the arrow rotation immediately when speed changes. To make the transition smooth, you have to store the arrow current state and change it slowly towards the target state.

```
// arrow shows a car's speed. These are bounds for what it can display
const float meterMinSpeed =  10f;
const float meterMaxSpeed = 210f;

const float minPinAngle =   16f; // rotation for  10 units of speed, degrees
const float maxPinAngle = -116f; //          for 210

// arrow's current rotation in degrees (z component of euler angles)
float currentArrowEulerZ;

void Update() {
    // find relative arrow position between min and max, it will be from 0 to 1
    float targetState = Mathf.InverseLerp (meterMinSpeed, meterMaxSpeed, userSpeed);
    // no need to clamp, it's already in Lerp

    // find arrow rotation which it will try to reach
    float targetEulerZ = Mathf.Lerp (minPinAngle, maxPinAngle, targetState);

    // move the arrow towards target, but only 20% this frame
    // so it will move smoothly, first fast then slower
    currentArrowEulerZ = Mathf.Lerp (currentArrowEulerZ, targetEulerZ, 0.2f);
    // change that number to make arrow faster or slower

    // actually change rotation
    arrowTransform.eulerAngles = new Vector3 (0, 0, currentArrowEulerZ);
}

```
> 2 votes

# Answer
I understand that no smooth movement = some times it moves slower and some times it moves faster.

It is a case of `Update` vs `FixedUpdate`. Unity has both. In `Update` you need to get the delta time since last frame. In `FixedUpdate` you can forget about that.

https://unity3d.com/es/learn/tutorials/topics/scripting/update-and-fixedupdate

The answer is then: use `FixedUpdate` or calculate your transformation including Time.deltaTime.

My personal preference: `FixedUpdate`.
> 0 votes

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


# Question
Title: OpenGL: Shader using wrong layout location
It's actually taking the color vector instead of the vertex vector. I noticed because I set the colors to random(), and the triangle clusterfudge that is my cube keeps changing shape when I reload the program.

I'm in the process of updating my code to match OpenGL3/4 standards and use PyGLM instead of numpy. Unfortunately it looks like my pointers are getting scrambled by the VAO.

I checked my view, perspective, and model matricies and they appear to be correct. I have also tried transposing them to no avail. Here's the VBO:

```
   vector                               color (random)
 [[-0.25       -0.25        0.25        0.4582803   0.8329993   0.36713707]
 [-0.25        0.25        0.25        0.7530541   0.87386566  0.07133926]
 [ 0.25        0.25        0.25        0.2536045   0.34725097  0.5796058 ]
 [-0.25       -0.25        0.25        0.4582803   0.8329993   0.36713707]
 [ 0.25        0.25        0.25        0.2536045   0.34725097  0.5796058 ]
etc...

```

Here's my shader code:

```
#version 420
layout (location=0) in vec3 vertex_attrib;
// in vec3 texcoord_attrib;
// layout (location=1) in vec3 normal_attrib;
layout (location=2) in vec3 color_attrib;
out vec3 vertex;
// out vec3 normal;
out vec3 color;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main() {
    gl_Position = projection * view * model * vec4(vertex_attrib, 1.0f);
    vertex = gl_Position.xyz;
    // normal = normal_attrib;
    color = color_attrib;
}

```

Commenting/uncommenting the normal location appears to do nothing.

VAO code where it binds the pointers for the VBO:

```
    self.VBOs.append(VBO)
    try:
        VBO.bind()
        for args in self.vptr_args:
            print(args)
            glEnableVertexAttribArray(args[0])
            glVertexAttribPointer(*args)
    finally:
        VBO.unbind()

# args for the two calls of glVertexAttribPointer: (result of the print)
# index=0, size=3, typ=GL_FLOAT, normalized=GL_FALSE, stride=0, pointer=None
# index=2, size=3, typ=GL_FLOAT, normalized=GL_FALSE, stride=0, pointer=c_void_p(12)

```

I'm terribly confused. The only thing I can think of is that PyGLM says it's using high-precision floats which is messing up the offset?

Edit: GLGets

```
VertexPointer 0
Enabled:  1
Size:  3
Type:  5126
Stride:  0
Buffer binding:  1
Ptr: 0
//
VertexPointer 1
Enabled:  1
Size:  3
Type:  5126
Stride:  0
Buffer binding:  1
Ptr: 12

```

# Answer
> 1 votes
This is happening because you're using a `stride` parameter of 0.

In OpenGL stride 0 means that the data is tightly-packed and not interleaved; in your case this does not apply as your data layout is an interleaved vertex with the first 3 floats representing position and the second 3 representing colour.

The correct `stride` to use is 24, i.e. (and assuming a 4-byte float on your platform) sized for 6 floats.

---
Tags: opengl, vbo, vao
---


title: opengl shadow map peter panning effect

text:
# Question
Title: opengl shadow map peter panning effect
I am implementing the shadow map in opengl with opentk everything works fine except I have a peter panning effect that I can't solve it by changing the face culling to front then render to the depth buffer.

the model is large so I scale it to small value to render it to the shadow map.

what is the reason that may cause this problem?

# Answer
To fully answer this question, let's start with an explanation of relevant shadow mapping issues and solutions:

**Issue: Stippling**

Cause: limited resolution of shadow maps, leading to reduced depth accuracy, this creates an alternating "in/out of shadow" artefact.

Solution: Add a "shadow bias" term to your calculations, which will move the shadows slightly, and compensate for stippling, giving you a solid shadow.

**Issue: Peter Panning.**

Cause: As we know that the shadow bias term moves the shadows, we can therefore assert that too small a value will not have a noticeable effect, and too large a value will visibly detach the shadow from geometry, regardless of geometry culling settings.

Normally, the ratio of geometry scale and shadow bias will be sufficient to make the panning not very noticeable, but it is reliant on that ratio being maintained.

See the following image for a visual explanation of the issue:

In the left image, the geometry is un-scaled, with a normal bias value. There is a small amount of panning. In the right image (zoomed a little), the geometry has been reduced in scale by a factor of 0.5, but the bias value remains the same, and because of this, the panning artifact is far more noticeable.

Solution: If you scale down the geometry (which is your use case), then reduce the bias value accordingly, but be aware that reducing it below a threshold value will cause stippling to return. Thus, scaling down your geometry may not be the best option for rendering more geometry to your shadow map. Indeed, reducing scale will actually reduce the accuracy of your shadow map eventually, which would eventually bring back stippling.

Truthfully, I don't really see much benefit to scaling down your geometry. If you wish to render more geometry to the map, move the camera back along it's "eye" vector, and increase the draw distance.

This will be more computationally expensive, but will give more pleasing results. Besides, using frustum culling and other software optimizations, you can easily compensate for any performance losses in favor of render quality.
> 2 votes

---
Tags: opengl, shadow-mapping
---


# Question
Title: Is there a way to hardcode a JSON file into a Unity build?
I'm currently creating an external tool to generate dialogues that are exported as JSON files.

The idea is that after you create a dialogue (as a JSON), my main Unity project reads that file and generates a dialogue.

Right now it works just fine, but the JSON is an external file that you can modify even after compiling the game (of course).

Is there a way to actually "hardcode" that JSON file so that the game doesn't need to find and read the file every single time it plays?

# Answer
> 3 votes
Let's assume somewhere in your code you do something like this to open the external JSON file, read its text, and parse it into a structured `Dialogue` object representation in memory.

```
DialogueData dialogue = DialogueUtility.ParseJSONFromPath(filepath);

```

Since you already have the file I/O, parsing, and validation covered above, I'll elide those parts in this answer, and just focus on how we can cache the result of this call at edit time rather than doing it at runtime.

First we define a new asset type that can live in our project's `Assets/` folder:

```
using UnityEngine;

// This line makes the asset show up in the Create Asset menus:
[CreateAssetMenu(fileName = "NewDialogue.asset", menuName = "Custom Data/Dialogue")]
public class DialogueAsset : ScriptableObject {

    // Our asset is just a container for your existing dialogue data.
    // This type must be [Serializable] or a Unity type to save correctly.
    public DialogueData dialogue;

    // The remaining parts we'll do only in-editor, and strip from the built game:
#if UNITY_EDITOR
    // Provide a path to the source JSON file.
    public string sourcePath;

    // Populate the data from the source file.
    // (Assuming DialogueUtility handles any errors itself)
    public void Import() {
        dialogue = DialogueUtility.ParseJSONFromPath(sourcePath);
    }
#endif
}

```

Now inside a folder called `Editor/`, we'll define a custom editor for this type:

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(DialogueAsset))]
public class DialogueAssetEditor : Editor {

    public override void OnInspectorGUI()
    {
        // Show default inspector property editor,
        // so we don't need to draw the DialogueData field ourselves.
        DrawDefaultInspector ();

        // Get a typed reference to the DialogueAsset we're editing.
        var asset = (DialogueAsset)target;

        // Add a button we can click to fire the "Import" method.
        if(GUILayout.Button(asset.dialogue == null ? "Import" : "Reimport") {
            // Log the change we're about to make so it's saved/undoable correctly.
            Undo.RecordObject(asset, "Import JSON");

            // Import the data.
            asset.Import();
        }
    }
}

```

Now you can create a new `DialogueAsset` by right-clicking in your project window and selecting `Create --> Custom Data --> Dialogue`. You can put the path to the source file in its `sourcePath` field, then click the "Import" button to do your JSON parsing and store the deserialized result into the asset.

The rest of the game can just reference this asset to read out its pre-digested `DialogueData`, without keeping the original raw JSON in your released game or parsing it at runtime. We're piggybacking on the Unity serializer to encode this data into our asset files and deserialize it when we run the game, and it does this in binary rather than text so it should be smaller, faster, and more resistant to unwanted tampering (though you should still assume that any data in the game client can be read and modified by a sufficiently motivated individual, and not count on this for security).

Note that in order for this to save and survive into your running game, your `DialogueData` has to be something that Unity's serializer can understand and reproduce faithfully. Unity types (including your own custom `ScriptableObject` variants) will work, as will `[System.Serializable]` types as long as you're not relying on polymorphism or circular references between types.

If you need help adapting your `DialogueData` to something Unity can serialize, please feel free to post that as its own question.

# Answer
> 1 votes
Nothing is keeping you from encrypting the assets included in your game.

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


# Question
Title: Sprite button not triggering "On Click()" event -Unity
Hi have created some buttons from sprite and I added image and button components on it.

I am just using sprites because In my game the camera can be moved on x and y. But I don't want my button to move and since UI buttons move with camera that is why I am not using them.

Here is the GIF to explain the scene:

# Answer
It looks like you tried to attach a SpriteRenderer to your button to render its visual in your game scene rather than as part of the UI. This means that where the player sees the button, and where Unity thinks the clickable UI is, have no relationship to one another.

The UI Button On Click event fires only on clicks **on the UI Button itself**.

If you click the SpriteRenderer, that is not part of the UI system, it is not the same as clicking on the UI button.

To detect a click on a Sprite, add a Collider to it, and use a script to listen for clicks:

```
void OnMouseDown() {
    // Do the thing.
}

```

Note that the presence of this method forces Unity to fire a ray into your scene every frame to track mouse interaction with colliders in your scene, so it does have a performance cost.

Or, you can click the button itself, by getting rid of your SpriteRenderer and instead using a World Space Canvas to draw your actual UI button where you want it in the scene. Then you have all the power of the normal UI system, and the freedom to position it anywhere in your world that you want it to go.
> 3 votes

---
Tags: unity, c#, 2d, sprites
---


# Question
Title: Intellisence doesn't show the ECS API Summaries
I am not sure if this is more of an ECS topic problem or packages in general. but it would be really helpful for ECS programming with all the summaries the Unity has provided. For unity engine methods, intelligence show me descriptions and summary of classes and methods, but it doesn't work on packages I guess.

I have tested this with all IDEs, AutoComplete doesn't show the description for methods and classes. However, I can go to the declaration of packages source code and see the summary. for example, Below you can see a screenshot in the `Jetbrain Rider` IDE, as you see when I mouse over `OnCreate` method it doesn't show the description.

# Answer
Apparently, this is not something that Unity supports at this time. However, there's a workaround by one of the Unity users in the forum.

**Turning this**:

**into this:**

**1)** Go to: `Library\PackageCache\com.unity.entities@0.0.12-preview.32\Unity.Entities\`

**2)** Create new file: `csc.rsp`

**3)** Paste this:

```
-doc:Library\ScriptAssemblies\Unity.Entities.xml -nowarn:1570 -nowarn:1591 -nowarn:1584 -nowarn:1658 -nowarn:419 -nowarn:1574 -nowarn:1572 -nowarn:1573 -nowarn:1587

```

Let Unity recompile the package, switch to Visual Studio and enjoy the documentation. \- long nowarn list ignores warnings about missing/broken XML comments in packages Ofc, downside of this solution is that you have to do it manually for every asmfile in every package. And again when you upgrade any package.

**Note:**

* You need to add the metadata next to the `csc` file as well. you can create a dummy metadata using Unity Editor.
* Sometimes reimporting cause the documentation to not show in the IDE. I don't know why, but reimporting the package folder that contains the `csc` can fix it.
> 2 votes

---
Tags: unity, visual-studio, ide, entity-component-system, visual-studio-code
---


# Question
Title: Digital Speedometer wrong update - Unity
Hi I am making a digital speedometer and I want it to change like a normal meter like: if speed is 10 on meter and the new speed is 50 it does not just show 50 on text instead gradually increase it.

here is what I have done:

```
    int speed;
    int textSpeed;
    int speedfinal;

    public Text text;

    // Update is called once per frame
    void Update()
    {
        speed = GameObject.Find("gamePlayManager").GetComponent<gamePlayManagerScript>().userSpeed;
        textSpeed = int.Parse(text.text);

        speedfinal = (int)Mathf.Lerp(textSpeed, speed, 0.1f);

        text.text = speedfinal.ToString();
    }

```

I am not sure if lerp is a good choice here to change text but that is what I know but it is adding 9 less then the orignal speed. Any idea how to do this. thanks.

# Answer
If you use `Lerp` with a constant interpolation value of `0.1f`, you are reducing the difference between current value and end value in increments of 10% per update, but you will never reach it. Add the precision loss due to rounding it to an integer, and you have no change anymore when you are 9.0 away from the end value.

A simple solution to this problem is to forget about `Lerp` and simply move the current value one closer to the destination value with each update:

```
  if (textSpeed < speed) {
       textSpeed++;
  } else if (textSpeed > speed) {
       textSpeed--;
  }

```

This solution might be sufficient, but has two cosmetic shortcommings:

* It might take a while to process really large changes in speed
* It isn't deltaTime-adjusted

If you want to fix these problems, then integer-arithmetic won't do. Stop keeping track of the currently displayed value by parsing the text. Use a `private float` variable to keep track of the value you want to display and don't convert it to an integer until you pass it to the text field on the UI.

Instead of adding or subtracting 1 to `textSpeed`, add or subtract the difference between `speed` and `textSpeed` multiplied with `Time.deltaTime` and a desired speed factor, but if the change is too small, change it by a fixed minimum value instead.
> 2 votes

# Answer
The improvement achieved with the solution below are:

1. You avoid calling `GameObject.Find` and `int.Parse` in the `Update` loop.
2. You use Late Update instead of Update. Not a big deal, but I see this more as a graphical feature, so it's better `LateUpdate` (it works also if you want to use `Update`)
3. I see you are trying to Lerp but I do not see this as the best approach, as you need still to have some kind of counter for the interpolation parameter. To make it simple you might just do the counting directly.
4. In the answer I increment it 1 by 1. If you want to see something different (similar to lerp) you may just change the increment to a different formula, to have a different gradual change.
5. With the `_changeIntervalInSecond` you may directly decide how fast you want the change to happen (`_changeIntervalInSecond` requires to be \> than 0, otherwise you will change it at each loop)

**Code solution**

```
public Text text;
//define a speed for the change
public float _changeIntervalInSecond;

//used to store the previous speed instead of taking it from the text
int _speedOnText = 0;
float _lastCountedTime = 0f;

//cache manager at awake
private void Awake()
=> _manager = GameObject.Find("gamePlayManager").GetComponent<gamePlayManagerScript>();

// this is more a graphical feature, so you may use Late Update
void LateUpdate()
{
    //get the current speed
    var currentSpeed = _manager.userSpeed;

    //ignore if we have no changes
    if(_speedOnText == currentSpeed) return;

    _lastCountedTime += Time.deltaTime;
    //if your interval has passed change the speed
    if(_lastCountedTime > _changeIntervalInSecond)
    {
        if(_speedOnText< currentSpeed) _speedOnText++;
        else _speedOnText--;
        text.text = _speedOnText.ToString();
        _lastCountedTime = 0;
    }
}

```
> 3 votes

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


title: Rotate mesh to normal

text:
# Question
Title: Rotate mesh to normal
I have some instanced geometry (basic tube meshes) laid out in a grid, and I have a noise texture (normal map) that I want to use to rotate my instances with. So head pixel in my texture is a normal and I want to rotate each instance with the corresponding normal in a shader. How can I achieve that in a shader only? Unless I am mistaking, there should only be a rotation around the X and Z axes.

# Answer
> 1 votes
You can get a rotation matrix from a a direction (\\$\vec d\\$) and an up vector (\\$\vec u\\$) (direction is the normal here).

First you need to get 2 perpendicular vectors, one pointing to the right (\\$\vec r\\$) and one pointing up (\\$\vec t\\$) when looking in the direction of the normal vector.

You can get \\$\vec r\\$ by getting the cross product of \\$\vec d\\$ and \\$\vec u\\$:

$$\vec r = \vec d \times \vec u$$

Then you can get \\$\vec t\\$ by doing the same to \\$\vec r\\$ and \\$\vec d\\$:

$$\vec t = \vec r \times \vec d$$

The rotation matrix can be defined by these three vectors in the following way:

$$\begin{bmatrix} \vec r\_x & \vec r\_y & \vec r\_z & 0 \\ \vec t\_x & \vec t\_y & \vec t\_z & 0 \\ \vec d\_x & \vec d\_y & \vec d\_z & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$$

Use it as a model matrix

---
Tags: shaders, rotation, glsl, hlsl, mesh
---


title: Action never fires

text:
# Question
Title: Action never fires
I have a method, which runs the action `MenuScreen` at the very end. It never fires. Why is that?

```
fun method() {
     scene.addSegment(SceneSegment(theEnd, Actions.fadeIn(4f)))

     scene.addSegment(SceneSegment(background, Actions.delay(10f)))
     scene.addSegment(SceneSegment(background, Actions.run { MenuScreen() }))

     scene.start()
}

```

`theEnd` fades in properly, but the `MenuScreen` is never called.

# Answer
> 1 votes
You're passing the result of calling MenuScreen() as your call back. What does that function return? Perhaps you meant simply MenuScreen, which is a function. Other than that I can't tell what's wrong.

---
Tags: libgdx, kotlin
---


# Question
Title: Framerate limited by lack of mouse movement?
Using Torque, it appears that the program is running at around 25fps when the mouse is still, but as long as I keep the mouse moving, the framerate can hit well over 300fps. What in the world would cause the framerate to be tied to mouse movement?

# Answer
Without seeing code I would say it's an issue of updating for every event including mouse axes events, which shouldn't cause an update. They should trigger a redraw flag which is handled by your timer event and redraw.
> 0 votes

---
Tags: opengl, mouse, frame-rate, torque
---


# Question
Title: Libgdx - Screen tearing (or artifacts) while in fullscreen
I have a problem with libgdx, fullscreen and what I believe is screen tearing or any other sort of artifact.

In windowed mode, everything works fine, but when i switch to fullscreen, moving sprites create some sort of screen tearing effect:

Had to take a photo with my phone, because using the print button does not work in fullscreen, and I could not capture the screen tearing effect using a libgdx "TakeScreenshot" Function.

I am using a TexturePacker and I tried changing the Filtering (Nearest, Linear) as well as edgePadding and duplicatePadding with no positive result.

I enabled vSync which also did not fix the problem.

Maybe anyone has encountered such a problem and can lend a helping hand.

Thanks in advance.

*Edit:*

This is how i enabled vSync:

```
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.vSyncEnabled = true;
//some other config stuff
new LwjglApplication(new MyGame(), config);

```

# Answer
I figured it out. Following Ocelots hint, I checked whether my framerate was really running at my monitors refresh rate, which it did not (so vSync was disabled).

Somehow the LwjglApplicationConfiguration applies all the settings I hand over, except for vsync. Not really sure why.

I fixed the whole thing with a

```
Gdx.graphics.setVsync(true);

```

call in the core project.

This correctly applies vSync and removes any artifacts or jittering.
> 0 votes

---
Tags: java, libgdx, sprites, image
---


title: How do I fix a "missing mcp.cfg" error?

text:
# Question
Title: How do I fix a "missing mcp.cfg" error?
I am trying to use mod coder pack (MCP) to create mods of my own. I have downloaded MCP 9.4 version from www.modcoderpack.com. The error that I have encountered is that when I try to run a file called `decompile.sh` in the mac terminal, the terminal responds with an error: `ERROR:root:!! Missing mcp.cfg`. I have checked my MCP folder and made sure that it contained the file `mcp.cfg`. The file is in my folder.

I am currently running on a Macbook Pro with MacOS Mojave Version 10.14.4.

# Answer
> 1 votes
It's hard to tell without seeing the content of `decompile.sh` but chances are good that that script simply assumes `mcp.cfg` will be in particular location. The file is probably references as a path relative to the working directory, which is *probably* the directory you're running the script from (unless the script itself changes it).

Try `cd`ing to the directory containing `mcp.cfg` and running it from there. Failing that, you may want to edit your post to include the contents of `decompile.sh` as it will help with further diagnostics if my guess here is wrong.

---
Tags: minecraft-modding
---


# Question
Title: Changing gameobject initialization order
Edit: Here is some important update:

I have found out that the script's Start and Awake voids are called, but AFTER the script is used by some other script. So the problem here is that the gameobject that hosts "OtherScript" is initialized after the gameobject which has a "MainScript" attached and which holds a reference to "OtherScript".

I hope I could explain it well.

If just the one gameobject was initialized before the other, everything would be fine. I will investigate now if I can change the intialization order.

Original post:

I have a complex scenario which I have reduced to the following problem:

I have a Cube in my Unity scene. This cube has the following script on it:

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

public class MainScript : MonoBehaviour
{
    public OtherScript TheOtherScript;

    public void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 50, 50), "Load something"))
        {
            this.TheOtherScript.LoadFile();
        }
    }
}

```

The script "OtherScript" looks like this:

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

public class OtherScript : MonoBehaviour
{
    private string _sPath;

    public bool HasBeenInitialized = false;

    public void Awake()
    {
        _sPath = Application.persistentDataPath + "/somefilename.dat";
        this.HasBeenInitialized = true;//indicator that Awake or Start have occured
    }
    public void Start()
    {
        _sPath = Application.persistentDataPath + "/somefilename.dat";
        this.HasBeenInitialized = true;//indicator that Awake or Start have occured
    }

    public void LoadFile()
    {
        if (_sPath == null)
        {
            Debug.Break();
        }
        //do something with _sPath
    }
}

```

I have created an empty GameObject to my scene, and I have added such a script to it:

I have then put a reference to empty GameObject to the Cube's "OtherScript" slot:

The problem that I'm experiencing is that "TheOtherScript"'s start / awake has not been called when this button is pressed:

```
    if (GUI.Button(new Rect(0, 0, 50, 50), "Load something"))
    {
        if (!this.TheOtherScript.HasBeenInitialized)
        {
            Debug.Break();//The script hasn't processed Start or Awake yet. Why???
        }

        this.TheOtherScript.LoadFile();
    }

```

Neither Awake nor Start is called on this script.

Which event could I react to in this case for initialization?

# Answer
> 2 votes
You can change Script Execution Order.

> You can use the Script Execution Order settings (menu: Edit \> Project Settings, then select the Script Execution Order\__ category).

You could also add a safecheck in your code:

```
public void LoadFile()
{
    if(!HasBeenInitialized) Start();

    if (_sPath == null)
    {
        Debug.Break();
    }
    //do something with _sPath
}

```

EDIT ----- ANSWER TO PREVIOUS QUESTION BELOW

First of all check that your Unity version is not an Alpha one. In that case anything might happen.

If your unity version is anyone of 2019.1 or previous everything will be working as expected.

Awake

> Awake is called after all objects are initialized

Start

> However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled. Start may not be called on the same frame as Awake if the script is not enabled at initialisation time.

This means your `Awake` and `Start` are called properly (because your game object starts enabled). You may just add a `Debug.Log` statement to check them.

```
public void Awake()
{
    Debug.Log("Awake Called");
    _sPath = Application.persistentDataPath + "/somefilename.dat";
}
public void Start()
{
    Debug.Log("Start Called");
    _sPath = Application.persistentDataPath + "/somefilename.dat";
}

public void LoadFile()
{
    if (_sPath == null)
    {
        Debug.Break();
    }
    //do something with _sPath
    Debug.Log(_sPath);
}

```

The issue relies most likely on `MainScript` method.

Also:

* Make sure the scripts are saved before launching play
* Make sure the scripts are attached to the Game Objects before going in play mode

# Answer
> 1 votes
The problem was "Script Execution Order":

The "OtherScript" is initialized AFTER "MainScript" is initialized". So when "MainScript" access the "OtherScript", it may happen that OtherScript hasn't been initialized yet.

The solution was change the Script Execution Order under "Project Settings..." -\> "Script Execution Order".

The script "OtherScript" has to be added with a negative time number, for example -50. It will then be initialized before any other script which are not explicitely listed here.

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


# Question
Title: How to split 2 teams for a FPS death match game in Unity?
I'm making a playable one level only FPS death match game in Unity. I'm in the part where the AIs now can find and shoot their own target and keep looping to find targets until nothing left. Every AIs and including player were tagged with tag "Target" for the AIs to randomly find their target. (I already excluded self finding).

Now I want to split them in 2 teams. And here is the thing that I keep wondering. **Should I use 2 tags for 2 teams (like team red, team blue for ex) then make and attach 2 scripts separately for each AI in the team (the logic in the script will be like "team red" will find game object with tag "team blue" and vice versa). Is that how it works? Is there more efficient way or should I say, "smarter" way to work around this problem?**

Here is the script if you need to know more about what I am trying to say https://github.com/Bezari0us/FPS\_AI\_Behaviour

# Answer
> 2 votes
# Use tags (but one script)

Well, your tag might not be using the *Unity* tag system. But you absolutely do not want to use different scripts! You'd be copying *the entire class* and changing *one* line. As soon as you find yourself duplicating code in order to make a simple behavioral differentiation, you should realize that your design is broken.

For example, if you wanted to move from 2 teams to 3, how much code would you have to change? If the answer is "all the work you did to make 2 teams all over again" then you did everything wrong. All you should have to do is add a single entry in a single place (e.g. adding the new team name to `EnumTeams` or similar) and everything else handles it automatically. You might never reach that ideal, but in thinking about it you can identify "oh, if I do this, I'll have to do a lot of work again in the future if I wanted to add a third team, is there a better way I can do it instead?"

What you should do instead is to make that "one line change" some sort of variable factor. Either the script has a public field that says "I am on blue team" (and then your random targeting logic looks at that field, and if the target's team is the same as self's team, ignore that target and find a new one) or you adjust the architecture to introduce a new class that defines the team and how targeting logic should handle teams.

What I mean by a new class here is some sort of "team" concept that allows your AI to identify what team it's on, and what teams its team is allied with (if you had 8 teams and wanted to have alliances, now you have teams of teams, how much rework would you have to do again!?). You might even want to have the "find me a target" code here, so that you can choose randomly from a list of only valid targets (eg. writing a function that automatically finds all living players that are NOT on the current team or its allied teams, and selecting a random one from that list, avoiding having to write a loop that keeps randomly selecting until a valid object is found).

# Answer
> 0 votes
I totally agree on Draco18s answer.

> you absolutely do not want to use different scripts!

I could add my opionion on WHAT you might use to differentiate teams.

**enums**
Probably the easier and safer if you want something quick.

```
public enum TeamType { Blue, Red }

public class TeamScript : MonoBehaviour
{
      public TeamType team;
      public void AssignTeam(TeamType teamToAssign) => team = teamToAssign;
}

```

---

**string tags**
That might be used together with unity tags.

```
public class TeamScript : MonoBehaviour
{
      public string team;
      public void AssignTeam(string teamToAssign) => team = teamToAssign;
}

```

---

**Scriptable Objects**
My favorite. Probably the most advanced.

```
//this might be also an empty script
[CreateAssetMenu(menuName = "TeamIdentifier")]
public class TeamIdentifier : ScriptableObject
{
}

public class TeamScript : MonoBehaviour
{
      public TeamIdentifier team;
      public void AssignTeam(TeamIdentifier teamToAssign) => team = teamToAssign;
}

```

The Scriptable Object needs also to be instantiated in the Project Window by:
Right Click =\> Create =\> TeamIdentifier

---

All of these options might be assigned in the Inspector Window.
And you may also easily assign them from the script (with the `AssignTeam` method) or checking them (from the field `TeamScript.team`).

---
Tags: unity, c#, first-person-shooter
---


# Question
Title: Using keyword [NonSerialized] causes Property to disappear from Inspector
I have the following class to represent items in an inventory:

```
[System.Serializable]
public class InventoryItemInfo : MonoBehaviour
{
    public int Row = 0;
    public int Col = 0;
    public int Rotation = 0;
    public InventoryItemType ItemType;
    public int Amount;
    public int EffectiveWidth = 0;
    public int EffectiveHeight = 0;

    public int Width = 0;
    public int Height = 0;

    public bool Selected = false;
    public Vector3 TilePosAccordingToCurrentRotation;
    public Vector3 TileScaleAccordingToCurrentRotation;

    [NonSerialized]
    public Transform TheNicelyPositionedMesh;

    [HideInInspector]
    private int _iCurRow = 0;
    private int _iCurCol = 0;
    private int _iRotationToCheckForDirtyness = -1;

    public Vector3 DefaultRotation;

    public bool Initited = false;

    public bool Dirty = true;
    private bool _bInitialRotationGotten = false;
    (...)

```

With the keyword \[NonSerialized\], the property "TheNicelyPositionedMesh" disappears from the Unity Inspector.

I don't see why. Why is that keyword coupled with the visibility in the Inspector?

Thank you!

# Answer
The Unity bug report team admitted that the keyword \[NonSerialized\] doesn't perfectly indicate what it does. In fact, it does more: It also hides the property from the Inspector.

They told me to post a change suggestion at the Unity forums (now that the feedback section is no longer valid): https://forum.unity.com/forums/scripting.12/

As a workaround, they suggested the following:

"In order to create a field which is not serialized but visible in the editor, you will need to create a Custom Editor.
> 1 votes

# Answer
Because Unity 'stores' public variables and private variables marked with the SerializeField attribute by serializing them. By using the NonSerialized attribute you can tell Unity that you don't want Unity to serialize it even when it normally would.

The inspector shows only serialized values in the inspector because these are the only ones that are actually stored/saved on disk.

If you change a value in the inspector, Unity handles serialization of that new value.

When you then Instantiate the object (either by calling Instantiate for prefabs or entering/exiting playmode for object in the scene), Unity will overwrite the default values of these serialized fields with the values you have set in the inspector. Unity does this before invoking Awake.

Values that are not serialized will therefore not be overwritten by values set in the inspector, so showing (editable) NonSerialized variables in the inspector doesn't make sense because any changes you do to them will be reverted back to their default values (set in the script) whenever Unity serializes/deserializes.

There are still valid usecases for when you want to see and prehaps even modify non serialized values in playmode. But as far as I'm aware Unity doesn't have an attribute to show non-serialized variables , not even as read only. The only way to show those is by either making them serialized, temporarily using the debug inspector or writing a custom inspector.

See also this section of the manual.

---

EDIT:

To clarify when Unity serializes something, first of all, if you haven't read that section of the manual. you really should.

Here is a short summary which might or might not be easier to understand then the manual, but it won't cover everything, so read that manual if you really want to know how everything works ;)

Unity can serialize any type that is one of the following:

* All classes that derive from UnityEngine.Object, for example GameObject, MonoBehaviour, etc.
* All basic data types like int, string, float, bool.
* Some built-in types like Vector2, Quaternion, etc.
* Enums
* custom classes or structs marked with the \[Serializable\] attribute
* Arrays of a serializable type
* List of a serializable type

Unity will then of those classes that it can Serialize, Serialize all its:

* public variables that are not marked with \[System.NonSerialized\]
* private variables marked with \[SerializeField\]

Note that it can only serialize fields of which the type is Serializable by Unity as explained above.

Fields marked with \[HideInInspector\] are still serialized (if it passes above criteria), they are just not show in the inspector.

Code explains more then words, so here is a small exmple which I hope covers everything.

```
[System.Serializable]
public class MyClass1 // Serialized, because we marked it with [System.Serializable]
{
    public int i1; // Serialized, because Unity can serialize int, field is public and MyClass1 is Serializable
    private int i2; // Not Serialized, because field is private
    [SerializeField] private int i3; // Serialized, Because Unity can serialize int and field is marked with [SerializeField] attribute.
}

public class MyClass2 // Not serialized, because we aren't [Serializable]
{
    public int i1; // Not serialized, because MyClass2 isn't [Serializable]
    private int i2; // Not serialized, because MyClass2 isn't [Serializable] (And we are private)
}

public class Example : MonoBehaviour // Serialized, because MonoBehaviour inherrits from UnityEngine.Object
{
    public MyClass1 c1; // Serialized, because we are public and MyClass1 is Serializable
    private MyClass1 c2; // Not Serialized, because we are private

    [SerializeField] private MyClass1 c3; // Serialized, because we are marked with [SerializeField] and MyClass1 is serializable
    [System.NonSerialized] public MyClass1 c4; // Not Serialized, because even though the field is public AND MyClass1 is Serializable, we are marked with [System.NonSerialized]

    public MyClass2 c5; // Not Serialized, because even though we are public and Example is Serialized, MyClass2 isn't Serializable

    public GameObject c6; // Serialized, because field is public and GameObject inherrits from UnityEngine.Object (And is therefore serializable).
}

```
> 4 votes

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


# Question
Title: Armature's bone can't be rotated in Unity when I'm trying to rotate its chest toward its looking direction?
I want to rotate my character's chest, so its looking direction will be visualised correctly.

But I think that the animation controller doesn't let me.

I logged its rotation before and after I set it, and after setting, it's correct, but next frame before I would set it, it's always snapped back.

How could I make my character's animation transformed, based on its looking direction?

This is the code:

```
Debug.Log(Chest.localRotation.eulerAngles);
Chest.localRotation = Quaternion.Euler(90, 90, 0);
Debug.Log(Chest.localRotation.eulerAngles);

```

# Answer
Animations set the rotation between Update and LateUpdate.

If you want to apply a modification to an animated pose, you need to apply it in LateUpdate, so it applies "over" the animation, rather than being replaced by it.

Note that if you want to persist some orientation from frame to frame (eg. for a lerped blend) you'll want to store the calculated value in your script, so it doesn't get stomped by next frame's animation tick before you can update the future frames using this historical data.
> 1 votes

---
Tags: unity, animation, skeletal-animation
---


# Question
Title: Cocos Creator - orientation change event in native build for iPhone and Android
I am making some Hybrid app which has some native part in Both iOS and Android and common functionality (which includes and games/animation and UI) which I make in Cocos Creator.

The problem I am facing while I am trying to change the device orientaiton from Portrait to Landscape of vice-versa.

I tried to get the current frame size or get notified about the change, but no success.

Anyone face this issue? Any ideas are welcome!

# Answer
Hi I have develop a game for iOS, android and for browser and I have used this code to get sizes of my device.

```
console.log("Game Manager onLoad called", cc.winSize.width, cc.winSize.height,cc.director.getVisibleSize().width);

console.log("OS NAME ", cc.sys.os);
console.log("Platform NAME ", cc.sys.platform);

```

this may help you.
> 1 votes

---
Tags: cocos2d-x, cocos2d-x-js
---


# Question
Title: How can OnMouseDown in the parent object be triggered from the child placed on top of it?
I am learning Unity from a book. The example is to create a 2D memory game as follows (viewed in perspective view).

The green (background) at `z=5`, the purple diamond (front card) at `z=0` and the red (back card) at `z=-5` for example. The front card is set as the parent of the back card in the hierarchy window.

A box collider (2D) component and a script below are attached only to the parent.

```
public class FrontCard: MonoBehaviour
{
    public void OnMouseDown()
    {
        Debug.Log("testing 1, 2, 3!");
    }
}

```

When I play the game and click the back card, the `OnMouseDown` gets invoked.

# Question

How can the `OnMouseDown` get invoked when I click the back card by considering the script is attached to the front card game object that is placed below the back card?

# Answer
> 1 votes
As always, your very first step should be to read the documentation for the methods you're using:

> OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or **Collider**.

Under the hood, having an `OnMouseDown` function tells Unity to fire a ray from the main camera each frame, through the on-screen position of the mouse/stylus/touches. Rays detect colliders.

If your back card has no collider, it's completely invisible to the raycast, and they ray will go straight through it to hit the front card's collider.

---
Tags: unity
---


# Question
Title: How to make extendable Mario warp pipe in Unity?
I want to make a warp pipe from the Mario games in Unity. The key feature of this object will be that I can set the length (height) of its "neck" to any length I require, as long as it is greater than 0.5m (the fixed depth of the interior of its "cap"). That is, *I want this object to be "extrudable" and the neck material to be tilable under this operation.*

I have already modeled the pipe in Blender and baked textures for the material (but I won't be upset if I have to redo the material, it just needs to be a green anistropic type, very basic). It consists of 2 pieces, the neck and the cap. The cap is a child of the neck. Only the neck grows/shrinks.

I have never done this before and am not sure how to begin. How can I create this feature? I would like the pipe to grow/shrink in the editor when I change the public variable "height".

**EDIT:** I just put the neck and cap back together as one object and used a bone to control the neck length. I exported the FBX and am seeing how the material looks on it at different lengths now

**EDIT 2:** So I tried to make a script that alters the transforms of the prefab's children in the inspector but it is not working. It doesn't work in the inspector and it doesn't work while running the game if I execute the function in the start method. The prefab contains two objects, PipeNeck and PipeCap. The script is attached to the parent inside the prefab. Here is the script:

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

public class ExtrudePipe : MonoBehaviour
{
    public float pipeHeight = 0.5f;
    private GameObject neck = GameObject.Find("PipeNeck").gameObject;
    private GameObject cap = GameObject.Find("PipeCap").gameObject;

    void Start()
    {
        Extrusion();
    }

    void Extrusion()
    {
        neck.transform.localScale = new Vector3(1, 2 * pipeHeight, 1);
        cap.transform.localPosition = new Vector3(0, pipeHeight - 0.5f, 0);
    }
}

```

**EDIT 3:** So I realized there were 8 new errors hidden under a hundred known warnings for something else that I didn't clear on my last test. These errors say that I can't use transform.\* in monobehavior, I had to put them in a function instead. So I put it in Awake() and now the pipe is stretched when the game is played, but I would still rather get instant feedback from the editor. Here is the updated code. Does anyone know what will get me instant feedback by typing the new height into the prefab's inspector field, "pipeHeight"?

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

public class ExtrudePipe : MonoBehaviour
{
    public float pipeHeight = 0.5f;

    void Awake()
    {
        Extrusion();
    }

    void Extrusion()
    {
        GameObject neck = GameObject.Find("PipeNeck").gameObject;
        GameObject cap = GameObject.Find("PipeCap").gameObject;
        neck.transform.localScale = new Vector3(1, 2 * pipeHeight, 1);
        cap.transform.localPosition = new Vector3(0, pipeHeight - 0.5f, 0);
    }
}

```

pipeHeight changed from "0.5" to "2":

**EDIT 4:** Last script was garbage, this one works when the game runs. Funny how simple things mess you up:

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

public class ExtrudePipe : MonoBehaviour
{
    public float pipeHeight = 1.0f;

    void Awake()
    {
        Extrusion();
    }

    void Extrusion()
    {
        if (pipeHeight == 1.0f)
        {
            return;
        }

        GameObject neck = GameObject.Find("PipeNeck").gameObject;
        GameObject cap = GameObject.Find("PipeCap").gameObject;
        float scaleFactor = (pipeHeight -0.5f)/ (0.5f * neck.transform.localScale.y);
        neck.transform.localScale = new Vector3(1, scaleFactor, 1);
        cap.transform.localPosition = new Vector3(0, pipeHeight - 1, 0);
    }
}

```

**EDIT 5: WORKING SOLUTION, IN EDITOR AND IN GAME:**

Slap this on the default parent object within the prefab (or I guess on the prefab in the scene) and it will work instantly in the editor as well as in the game. Special thanks to DMGregory, who has been tremendous help here since I started months ago!

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

public class ExtrudePipe : MonoBehaviour
{
    public float pipeHeight = 1.0f;

    void OnValidate()
    {
        Extrusion();
    }

    void OnAwake()
    {
        Extrusion();
    }

    void Extrusion()
    {
        GameObject neck = GameObject.Find("PipeNeck").gameObject;
        GameObject cap = GameObject.Find("PipeCap").gameObject;
        neck.transform.localScale = Vector3.one;
        cap.transform.position = Vector3.zero;

        if (pipeHeight <= 1)
        {
            return;
        }

        float scaleFactor = (pipeHeight -0.5f)/ (0.5f * neck.transform.localScale.y);
        neck.transform.localScale = new Vector3(1, scaleFactor, 1);
        cap.transform.localPosition = new Vector3(0, pipeHeight - 1, 0);
    }
}

```

# Answer
To edit your height in the editor, just call your extrustion method from OnValidate. This is called in the editor when you change a parameter:

```
void OnValidate() {
    Extrusion();
}

```

Note that this is not called in the built game, so you'll want to either save your scene with the pipe in the desired height, or call the extrusion method at runtime in Start or similar if you need to adjust the height of a dynamically-spawned pipe.
> 2 votes

# Answer
Why so complicated? If you just want to linearly stretch the whole object, you could just change the y-scale of its Transform component, either directly in the Inspector or via script with `transform.localScale.y`.

If you want to stretch the neck of the pipe but not the cap, make them both children of the same object instead of children of each other. Change the `transform.localScale` of the neck and the `transform.localPosition` of the cap so it stays on top.

If you want to do that via script in the editor, you will need to write a custom inspector script which changes these transforms when the user changes the height of the pipe.
> 0 votes

---
Tags: unity, c#, scripting, gameobject
---


# Question
Title: Unreal engine how do I change the visual studio version without having loaded up a project?
I get an error which I mentioned in a previous post. I did a little more research on this error and found out that I need to use an up-to-date visual studio. I think that I might need to change the visual studio version from the config. I have both visual studio 2017 and 2013 on my computer.

# Answer
> 1 votes
to anyone else who has been searching for the answer of how to switch vis studio version without opening project, you must change the selected version in both the DefaultEditor and DefaultEditorSettings files located in the config folder.

will look like this

\[/Script/SourceCodeAccess.SourceCodeAccessSettings\] PreferredAccessor=VisualStudio\[your desired version number\]

in my case I had to switch from a 2019 to 2017 so it looks like this

\[/Script/SourceCodeAccess.SourceCodeAccessSettings\] PreferredAccessor=VisualStudio2017

# Answer
> 0 votes
4.15 uses only VS2015+. Easiest solution is to uninstall 2013. Otherwise, just open the game solution in 2017 and compile it. It's unclear what you mean by "without having loaded the project".

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


# Question
Title: Problem with rendering multiple textures from same image (LWJGL 3)
I have started with LWJGL3 and trying to built game engine. I'm stuck on generating terrains. I have one image that contains two textures.

So now for example I want to generate terrain with only texture 2, so my texture coordinates looks something like this : textures : (0.6f,0f) (0.9f,1f) .....

Everything is fine if terrain is not long, but if I stretch terrain on z-axis, terrain is using texture 1. As you can see on image. I just can't understand why is doing that ?

# Answer
> 0 votes
The cause is most likely mipmaps being shrunk so much that the texture 1 bleeds out. There is a high chance that both textures merge together in one pixel at the last mipmap level. Try disabling mipmaps.

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


# Question
Title: JWJGL Multi-threading to separate update and render
**Introduction:**

I am currently designing a game in Java using the LWJGL 3.0, with Gradle. I have quite an advanced knowledge on multi-threading, and I am aware how GLFW does/doesn't implement multi-threading from this guide. Currently, I have one class `Updater` with a loop for updating, and another class `Renderer` for rendering, each extending Runnable with their own loops and time calculations. Below is a diagram showing the structure of the classes and update and render methods. I have also set up a lock system, using the Java Lock class (again below).

**My Problem:**

Despite setting each thread as the current context before each loop executes its window call, and setting the current context to null at the end, I still get the error `Exception in thread "RENDERER" java.lang.IllegalStateException: GLFW error [0x10008]: WGL: Failed to make context current: The requested resource is in use.` Any idea as to why? Been at this for a few hours now.

Loop class:

```
private void threadLoop() {
    try {
        lock.lock();
        locked = true;
        loop();
        TPS++;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
        locked = false;
    }
}

@Override
public void run() {
    init();
    long lastTime = System.nanoTime();
    double ns = SECOND / (MAX_TPS/2);
    double delta = 0;
    long timer = System.currentTimeMillis();
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1) {
            threadLoop();
            TPS++;
            delta--;
        }
        if(System.currentTimeMillis() - timer > 1000) {
            finalTPS = TPS;
            timer += 1000;
            TPS = 0;
        }
    }
    stop();
}

```

Thread Manager:

```
public void update() {
    if (window == null) return;
    window.setThread();
    window.update();
    window.nullThread();
}

public void render() {
    if (window == null) return;
    window.setThread();
    window.render();
    window.nullThread();
}

```

Renderer:

```
@Override
protected void loop() {
    if (state != null) state.render();
    threadManager.intermediateCode();
    threadManager.render();
}

```

Updater:

```
@Override
protected void loop() {
    if (state != null) state.update();
    threadManager.intermediateCode();
    threadManager.update();
}

```

Window:

```
public void setThread() {
    glfwMakeContextCurrent(getID());
}

public void nullThread() {
    glfwMakeContextCurrent(NULL);
}

public void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(0.0f, 0.3f, 0.8f, 0.0f);
    glfwSwapBuffers(ID);
    System.out.println("Rendered window");
}

public void update() {
    glfwPollEvents();
    System.out.println("Updated window");
}

```

# Answer
After doing some more research, I added a lock system over the access to the `window.update()` and `window.render()` calls, like below. This ensured that only one thread was accessing the window at any time, hence the context resource could not be in use. Not sure why my lock system in the main loop didn't prevent this, but it's fixed now.

New `update` and `render` methods in `ThreadManager` class

```
public synchronized void update() {
    if (window == null) return;
    if (rendering) {
        try {
            wait();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException caught.");
        }
    }
    stateManager.update();
    window.setThread();
    window.update();
    window.nullThread();
    rendering = true;
    notify();
}

public synchronized void render() {
    if (window == null) return;
    if (!rendering) {
        try {
            wait();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException caught.");
        }
    }
    stateManager.render();
    window.setThread();
    window.render();
    window.nullThread();
    rendering = false;
    notify();
}

```

EDIT: Upon further research, I found that the `glfwPollEvents()` method must be called from the same thread that the window is created in. Therefor I just added `threadManager.init()` to the `Updater` init method, and it fixed the issue without the need of the second lock above.
> 1 votes

---
Tags: opengl, java, lwjgl, multithreading, glfw
---


# Question
Title: What are the ascii numbers for shift and control?
I is trying to makey makey a program that will detect when certain keys are pushed. My only problem is that I dont know the nombers that corrospond to the shift key and control keys. I am writing this code for a game. Here are teh codes:

```
switch(event->keyval) {
    case ?:
        printf("Shift key was pressed");
    break;
    case ??:
        printf("Control key waas pressed");
    break;
}

```

What can replace ""?"" and ""??""

Also, if possible, my answer SHOULD be able to fit in a `char` type

# Answer
To get state of the shift and control buttons in GTK, you need to apply bitwise AND to the event state.

```
if(event->state & GDK_SHIFT_MASK)
{
    printf("Shift key was pressed");
}
else if(event->state & GDK_CONTROL_MASK)
{
    printf("Control key was pressed");
}

```

Alternatively, you can use macros (or their values, but please **don't**) defined in gdkkeysyms.h

> #define GDK\_KEY\_Shift\_L 0xffe1
>
> #define GDK\_KEY\_Shift\_R 0xffe2
>
> #define GDK\_KEY\_Control\_L 0xffe3
>
> #define GDK\_KEY\_Control\_R 0xffe4

```
switch(event->keyval) {
    case GDK_KEY_Shift_L:
        printf("Left shift key was pressed");
    break;
    case GDK_KEY_Shift_R:
        printf("Right shift key was pressed");
    break;
    case GDK_KEY_Control_L:
        printf("Left control key was pressed");
    break;
    case GDK_KEY_Control_R:
        printf("Right control key was pressed");
    break;
}

```
> 1 votes

---
Tags: c
---


# Question
Title: Determining value to add / subtract scaling
I have a menu panel. It appears if the user presses the Enter key, and it disappears if he presses the Enter key again.

When the menu is still hidden, its X scale is set to 0. In its normal / expanded state is 0.00175f. When the menu is shown or hidden, I want to smoothly scale from 0 to 0.00175f or from 0.00175f to 0.

To do that, I have written a coroutine:

```
private IEnumerator pShrinkExpandMenu(bool uShrink)
{
    if (!uShrink)
    {
        Menu.SetActive(true);//the menu should be expanded / enlarged, so we need to make sure it's visible
    }

    float fWidthIfExpanded = 0.00175f;
    float TimeInSecondsToSwitch = 0.3f;

    _TimeElapsedOnShrinkingExpanding += Time.deltaTime;

    while (_TimeElapsedOnShrinkingExpanding < TimeInSecondsToSwitch)
    {
        float fValue;

        if (uShrink)
        {
            fValue = ...
        }
        else
        {
            fValue = ...
        }

        Menu.localScale.X = fValue;

        yield return 0;
    }
    if (uShrink)//if we shrink, and it's completely shrunken, hide it
    {
        Menu.SetActive(false);
    }
}

```

I hope that my coroutine is fine. One thing that I just don't know is how to determine the value that the X scaling should be changed during one loop.

I have no idea how to calculate fValue.

Could anybody explain that to me, please?

# Answer
> 1 votes
Three simple changes:

1. Compute a start & target scale depending on whether you're shrinking or growing. I just do it with a ternary operator: `float targetScale = uShrink ? 0f : fWidthIfExpanded;`
2. You can replace your `while` loop with a `for` loop, which includes your time incrementing logic built-in.
3. Compute your intermediate value with a `Lerp` (linear interpolation) between your start and your end, proportional to how close `elapsed` gets to your duration.

Something like this:

```
private IEnumerator pShrinkExpandMenu(bool uShrink)
{
    if (!uShrink)
    {
        Menu.SetActive(true);//the menu should be expanded / enlarged, so we need to make sure it's visible
    }

    float fWidthIfExpanded = 0.00175f;
    float TimeInSecondsToSwitch = 0.3f;

    float startScale = Menu.transform.localScale.x;
    float targetScale = uShrink ? 0f : fWidthIfExpanded;

    for (float elapsed = 0f; elapsed < TimeInSecondsToSwitch; elapsed += Time.deltaTime)
    {
        float blend = elapsed/TimeInSecondsToSwitch;

        // You can apply some non-linear mapping to blend here for an easing effect.
        // eg. blend *= blend will give you a quadratic ease-out

        var scale = Menu.localScale;
        scale.x = Mathf.Lerp(startScale, targetScale, blend);
        Menu.localScale = scale;

        yield return null;
    }

    if (uShrink)//if we shrink, and it's completely shrunken, hide it
    {
        Menu.SetActive(false);
    }
}

```

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


# Question
Title: Calculating damage with damage mitigation/amplification curve/function
Let's say instance A is attacking instance B for N damage. I want to calculate the ideally expected damage if those instances have damage mitigation/amplification depending on target's current HP.

Instance B has an ability that it will take less damage as its HP gets lower. It could be like a (half of) sin curve, or maybe some complex function. So the formula look something like this:

$$damage = damage\_{raw} \cdot ({1 \over 4} + {3 \over 4} \cdot \sin ({\pi \over 2} \cdot {hp \over hp\_{max}}))$$

B will have 75% damage mitigation at 0% HP and 0% at 100% HP.

What I want to here is to chop the damage into infinite pieces and apply each to B so B can fully utilize its ability, and get the value after the process.

Also I'd like know how I'll calculate it when A has a similar ability that also changes the damage, like, increasing damage if the target has lower HP. Also there can be a case both of the instances have a variety of damage changers.

I think it's related to calculus but I have no knowledge about it.

# Answer
I think your idea of chopping the damage up into many pieces might actually be the best way to go, treating current health as a floating point value so that it can track "loose change" when subtracting fractional damage.

The advantage is that we could then sub-in any damage resistance/vulnerability function we want, and the same code "Just Works" - it might looks a bit like this in C#:

```
public delegate float Vulnerability(float currentHealth, float maxHealth);

private float currentHealth;
private float maxHealth;

public void TakeDamage(float incomingDamage, Vulnerability vulnerability) {
    for(int i = 0; i < incomingDamage; i++) {
        currentHealth -= vulnerability(currentHealth, maxHealth);
    }

    // Handle any fractional bit left at the end.
    float leftover = incomingDamage % 1.0f;
    currentHealth -= leftover * vulnerability(currentHealth, maxHealth);

    if(currentHealth <= 0f)
        Die();
}

```

Note how this code doesn't care what math the `vulnerability` function is doing internally. It just provides an arbitrary mapping between each point of damage and the amount we should actually take, based on our current health level. The result is approximate, and will tend to slightly overestimate damage dealt, but you can compensate by slightly increasing your resistance values.

---

In contrast, let's look at what a continuous/analytical solution might look like. Here I'm going to simplify our vulnerability function to make it more tractable. Instead of the sinusoid curve, let's do something basic like...

$$V(T) = 1 - r\cdot T$$

Where \\$V(T)\\$ is the amount of damage we should take per point of incoming damage, at the current value of \\$T\\$, which is the total amount of damage we've taken so far. \\$r\\$ is a real number coefficient that controls how quickly the damage resistance ramps up as we take more damage. For instance, if we want to imitate your example of 75% damage reduction near 0 HP, it would look like this:

$$r = \frac 3 4 \cdot \frac 1 {\text{max health}}$$

Now we need a function \\$T(i)\\$ that tells us how our total damage taken increases as a function of total incoming damage received, \\$i\\$. We want the derivative of this function, its rate of change with respect to \\$i\\$, to match our vulnerability function \\$V(T)\\$, ie...

$$\begin{align} \frac {d T(i)} {d i} &= V(T(i))\\ \frac {d T(i)} {d i} &= 1 - r \cdot T(i) \end{align}$$

So now we have a linear equation that relates the function to its own derivative - a differential equation. Fortunately, this one is reasonably easy to solve with the integrating factor \\$U(i) = e^{r\cdot i}\\$, whose derivative is \\$\frac {dU(i)} {di} = r\cdot e^{r\cdot i}\\$.

Since all our remaining upper-case letters are functions of \\$i\\$ now, from here on I'm going to abbreviate \\$T(i) = T\\$, \\$\frac {d T(i)} {d i} = T'\\$, and likewise for \\$U\\$.

Rearranging and multiplying everything by our integrating factor gives us...

$$\begin{align} T' + r \cdot T &= 1\\ e^{r\cdot i}T' + r e^{r\cdot i} \cdot T &= e^{r\cdot i} U \cdot T' + U' \cdot T = e^{r\cdot i}\\ \int{U \cdot T' + U' \cdot T} \\, di &= \int{e^{r\cdot i}} \\, di\\ U \cdot T &= \frac 1 r e^{r\cdot i} + c\\ e^{r\cdot i} \cdot T & = \frac 1 r e^{r\cdot i} + c\\ T &= \frac 1 r + c\cdot e^{-r\cdot i} \end{align}$$

Now we just need to work out the constant of integration, \\$c\\$. We know that at \\$i = 0\\$, \\$T(i) = 0\\$ (if we've received no incoming damage, then we've taken no damage). That lets us solve...

$$\begin{align} T(i) &= \frac 1 r + c\cdot e^{-r\cdot i}\\ T(0) &= \frac 1 r + c\cdot e^{-r\cdot 0}\\ 0 &= \frac 1 r + c\\ c &= \frac {-1} r \end{align}$$

So we've finally arrived at our continuous function for total damage taken, given total incoming damage received:

$$T(i) = \frac {1 - e^{-r\cdot i}} r$$

For such a simple starting point, that was a fair bit of work to get to, and the result doesn't have a super obvious relationship to the vulnerability function we started with.

If we want to change the shape of our vulnerability function, we have to do a whole new mathematical derivation, and we're not guaranteed that a closed-form solution exists. For instance, if we want to try...

$$V(T) = \frac 1 4 + \frac 3 4 \cos \left( \frac \pi 2 \frac T {\text{max health}} \right) \\;\text{ ...or... }\\; V(T) = 1 - \frac 3 4 \left( \frac T {\text{max health}} \right)^2$$

...to get the slow start & accelerating resistance you had in your original example, we end up with *non-linear* differential equations, which can be much more difficult to solve.

These might be a solvable case - I'm not sure. It's been quite a while since I studied differential equations so I'm rusty on all but the simplest of them.

Overall though, I'd say doing a discrete approximation - chopping the damage into "small enough" slices and applying a constant resistance to each slice - is likely to give you better results for a game:

* simpler to get up & running
* clear and easy to debug
* scalable to arbitrary vulnerability functions
> 3 votes

---
Tags: mathematics
---