# Question
Title: Endless runner player detect player drop
Starting to learn/write my first game using Corona/Solar2d game engine. And have a very basic question on how do people handle a such this situation which I assume should be common to any game engine.

I am trying to build an endless runner game, where I have an uneven terrain player have to jump between different height platforms while moving forward. Here is the closest to what I have in mind.

https://youtu.be/qWz0vOywFdY

How do I find if the player has fallen between the the two platforms while jumping ?

# Answer
A common way to solve this is to have an invisible "kill box" or "kill plane" near the bottom of your screen. If the player falls low enough to touch it, you know they missed a jump by so much that they can't recover, and it's time to count a failure.

This can take two common forms:

* It can be a "trigger" collision object, that's one that can detect when other physics bodies touch it, but does not act as a solid obstacle that will push back against them or be pushed. In Solar2D terms, that's a fixture with `isSensor` set to true.

You listen for collision events/callbacks from this object to detect when physics objects have touched the kill box, and react by destroying those objects or triggering a game over / restart.
* Or it can be an implicitly-defined threshold that doesn't exist as an object in your physics world. Instead its a kind of "lethal altitude" value that you set. Each time you update your player, you check their y coordinate against this threshold. If they've fallen below the lethal altitude, time to die.
> 2 votes

---
Tags: game-design, game-mechanics, corona-sdk
---


title: Using octrees as LOD system

text:
# Question
Title: Using octrees as LOD system
I am using an octree to define my 3D voxel world.

And I want to use octree subdivision as a LoD system.

This means, subdivide close to the player, but far away nodes un-subdivided.

But it occurs to me that in some cases, the octree can quickly degenerate to a grid.

To illustrate, see the 2D sample of a quad tree below.

If the player is at location A, no problem, subdivide that cell, done.

If the player is at location B, two cells would require subdivision.

But at location C, all cells are subdivided, causing no reduction in work.

Are octrees even viable approaches to LoD, or do I need something else?

# Answer
As Kromster alludes, this apparent problem occurs because of the small scale of your example. Usually when we reach for sparse octrees, we have more than two levels of subdivision.

Here's your same 2D quadtree example, but with 4 levels of subdivision instead of 2:

You can see how, even in the worst case where we have a cluster of detailed content spanning the center cross of the tree, we only need 16 high-detail (blue) cells, 12 medium-detail (green) cells, and 12 low-detail (orange) cells, for a total of 40 active cells.

Compare this to subdividing the whole grid to the finest detail level, which takes 256 cells in this 2D quadtree example. (For a 3D octree, the exponent is even worse - you'd need 4096 cells for a full grid this fine), so we've potentially reduced our workload by 85% or more!

See this past Q&A for more examples of how you can leverage multiple levels of hierarchy for effective compression of voxels.
> 2 votes

---
Tags: voxels, octree, level-of-detail, spatial-partitioning
---


# Question
Title: Changing ImageView position based on angle of rotation
I am trying to make an `ImageView` change its position based on the direction it is facing.

```
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class Demo extends Application {

    public void start(Stage window) {
        window.setTitle("Changing ImageView position based on angle of rotation");

        int speed = 10; // You can modify the speed here

        ImageView imageView = new ImageView(new Image("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTBJoRKh1UKimWTSLdabW2b8RSLDeSgMfSqqg&usqp=CAU"));
        imageView.setX(100);
        imageView.setY(100);

        imageView.setRotate(65); // This is where you can change the angle of rotation

        Group root = new Group();
        root.getChildren().add(imageView);
        Scene scene = new Scene(root);
        window.setScene(scene);

        final long[] lastNanoTime = {System.nanoTime()};

        new AnimationTimer() {
            @Override
            public void handle(long currentTime) {
                double elapsedTime = (currentTime - lastNanoTime[0]) / 1000000000.0;
                lastNanoTime[0] = currentTime;

                imageView.setX(imageView.getX() + Math.sin(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
                imageView.setY(imageView.getY() + Math.cos(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);

            }
        }.start();

        window.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

```

The above code is based on the code I am using. You can adjust the degrees accordingly to see the issue. The `ImageView` does not move in the direction it is facing. Note: I found a random .png file online for the purpose of this demo. You can substitute with a different image in you own code in order to better visualize the problem.

The issue is, the `ImageView` does not move in the direction it is facing. When oriented vertically (0° or 180°) the `ImageView` moves backward, but when oriented horizontally (90° or 270°) it moves straight ahead like it should. When oriented diagonally, it moves somewhere in between.

What am I doing wrong and how do I fix it?

# Answer
> 0 votes
The question was resolved on Stack Overflow. The y axis is inverted in JavaFX, so I need to use -cos(θ) instead.

---
Tags: java, 2d, animation, rotation, javafx
---


# Question
Title: How can I change the radius size width and other parameters in runtime in the Update?
```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(LineRenderer))]
public class DrawRadiusAroundTurret : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(0, 5)]
    public float xradius = 5;
    [Range(0, 5)]
    public float yradius = 5;
    [Range(0.1f, 5f)]
    public float width = 0.1f;
    LineRenderer line;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = segments + 1;
        line.widthMultiplier = width;
        line.useWorldSpace = false;
        CreatePoints();
    }

    private void Update()
    {
        CreatePoints();
    }

    void CreatePoints()
    {
        line.widthMultiplier = width;

        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0f, y));

            angle += (380f / segments);
        }
    }
}

```

I tried this, At the top I added :

```
private float prevxRadius = -1.0f;
private float prevyRadius = -1.0f;
private float prevSegments = -1.0f;

```

Then in the Update , but it's never get to the CreatePoints it's only get to the first return no matter what values I change in the inspector.

```
private void Update()
    {
        if (xradius == prevxRadius) // and also check yradius and segment
            return;
        prevxRadius = xradius;

        if (yradius == prevyRadius) // and also check yradius and segment
            return;
        prevyRadius = yradius;

        if (segments == prevSegments) // and also check yradius and segment
            return;
        prevSegments = segments;

        CreatePoints();
    }

```

Then I tried this in the Update but it's not working either it's calling the CreatePoints after the

```
prevxRadius = xradius;

```

when I change the xradius value but the prev and current values are the same.

```
private void Update()
    {
        if (xradius == prevxRadius) // and also check yradius and segment
            return;
        prevxRadius = xradius;
        CreatePoints();

        if (yradius == prevyRadius) // and also check yradius and segment
            return;
        prevyRadius = yradius;
        CreatePoints();

        if (segments == prevSegments) // and also check yradius and segment
            return;
        prevSegments = segments;
        CreatePoints();
    }

```

The main goal is to change in real time in editor mode and runtime the values of the xradius,yradius and the segments.

# Answer
Myself, I'd do this in `OnValidate` if these variables are meant to be tuned in the editor. This gets called only when loading or editing the component, so it's ideal for this kind of reactive fix-up during tuning.

If these parameters can be set by scripts in-game, I'd have them call a `SetRadii(x, y)` method or something similar that can handle applying the changes on demand, rather than polling for changes every frame in your update loop.

This way, we don't need our `prev` variables at runtime at all - they can live only in the editor:

```
#if UNITY_EDITOR
float prevXRadius, prevYRadius;
int prevSegments;

void OnValidate() {
    // Can't set up our line if the user hasn't connected it yet.
    if (line == null)
        return;

    // If any values have changed, update our points.
    if(xRadius != prevXRadius || yRadius != prevYRadius || segments != prevSegments) {
        CreatePoints();

        // Cache our most recently used values.
        prevXRadius = xRadius;
        prevYRadius = yRadius;
        prevSegments = segments;
    }
}
#endif

```
> 1 votes

# Answer
This is working. Is that a good and logic solution ?

```
private void Update()
    {
        if (xradius != prevxRadius) // and also check yradius and segment
        {
            CreatePoints();
        }
        prevxRadius = xradius;

        if (yradius != prevyRadius) // and also check yradius and segment
        {
            CreatePoints();
        }
        prevyRadius = yradius;

        if (segments != prevSegments) // and also check yradius and segment
        {
            CreatePoints();
        }
        prevSegments = segments;
    }

```
> 0 votes

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


# Question
Title: Getting the edge-cells in a list of cells on a 2d grid, and knowing which neighbor is missing
I create a "circle" on my 2d-grid using this code:

```
public List<Cell> GetSurroundingCellsCircle(Coord originCoord, int distance)
{
    List<Cell> matches = new List<Cell>();
    int EX = distance + coord.x;
    int EY = distance + coord.z;
    int SQ = distance * distance;

    for (int x = coord.x - distance; x <= EX; x++)
    {
        for (int z = coord.z - distance; z <= EY; z++)
        {
            int c = x - coord.x;
            int d = z - coord.z;

            if ((c * c + d * d) < SQ)
            {
                Cell cell = GetCell(new Coord(x, z));
                if (cell != null)
                    matches.Add(cell);
            }
        }
    }

    return matches;
}

```

This code works fine and returns a list of cells that together create a circle-shape. Now I want to get all the edge-cells of this circle, and not only that, but I also need to know which side of the edge-cell that has no neighbor, so I know where to draw the line. I want a result that looks like this red line:

I wrote this code that would work for a square (it just finds the max/min of X/Z and draws a sphere there, but as you can see in my image, its missing the "rounding" cells:

```
int maxX = 0, maxZ = 0, minX = 0, minZ = 0;

        for (int i = 0; i < cells.Count; i++)
        {
            int cX = cells[i].coord.x;
            int cZ = cells[i].coord.z;

            if (i == 0)
            {
                minX = cX;
                minZ = cZ;
            }
            else
            {
                if (cX < minX)
                    minX = cX;

                if (cZ < minZ)
                    minZ = cZ;
            }

            if (cX > maxX)
                maxX = cX;

            if (cZ > maxZ)
                maxZ = cZ;
        }

        for (int i = 0; i < cells.Count; i++)
        {
            int cX = cells[i].coord.x;
            int cZ = cells[i].coord.z;

            if (cX == maxX || cZ == maxZ || cX == minX || cZ == minZ)
            {
                Gizmos.DrawSphere(
                    new Vector3((cells[i].coord.x * GridBase.WORLD_CELL_SIZE) + GridBase.WORLD_CELL_OFFSET,
                    1,
                    (cells[i].coord.z * GridBase.WORLD_CELL_SIZE) + GridBase.WORLD_CELL_OFFSET),
                    1);
            }
        }

```

# Answer
Okay. Once again, this is what I think should work, but maybe you need to shift the positions a bit around. The reason for the bloated array size is to get border cells to spit out, well, borders, instead of arrayOutOfBounds exceptions.

If you want to use this for anything else than circles, take the middle of the figure, use that as x and y (has to be int), distance becomes the bigger difference between xmax-xmin and ymax-ymin.

Remember, this is just what I think could work, and if it does not, it should at the very least provide you with an idea of what to do.

```
List<Cell> edgecells (int distance, int centerx, int centery, List<Cell> matches){//The list matches needs to contain ALL cells of the circle
//the functoin takes the distance, as well as the coordinates of the location of the center of the circle.
List<Cell> edgec = new List<Cell>();
int shiftx = centerx - distance+1;
int shifty = centery - distance+1;
Cell locationgrid[distance*2+2][distance*2+2];//SHOULD work, if not initialze the array somehow else. Has to be NULL.
for(int i = 0; i<matches.count; i++){
    locationgrid[matches[i].x-shiftx][matches[i].y-shifty] = matches[i];//This line puts all the cells ordererd in the locationgrid, instead of a list
    //Meaning a list of coords like 0|0 1|0 0|1 1|1 gets turned in an array useful for other stuff
}

for(Cell l1[] : locationgrid){//this iterates through all the grid parts. Since it's now a grid, adjacent cells can be used in calculation.
    for(Cell l : l1){
        //Assumption here is that each cell has four extra values, 'up', 'down', 'right', 'left', all responsible for storing if there's a border.
        //WARNING: the comparison method may not work and always return true!
        if(locationgrid[l.x+1][l.y]==NULL){
            l.right = true;
            edgec.Add(l);
        }
        if(locationgrid[l.x-1][l.y]==NULL){
            l.left = true;
            edgec.Add(l);
        }
        if(locationgrid[l.x][l.y+1]==NULL){
            l.up = true;
            edgec.Add(l);
        }
        if(locationgrid[l.x][l.y-1]==NULL){
            l.down = true;
            edgec.Add(l);
        }
    }
}

return edgec;//this list now contains only edge cells who have their information set about where the border is.
}

```
> 0 votes

# Answer
Just for anyone interested, I ended up getting the edges before creating the list:

```
public struct EdgeCell
{
    public bool north;
    public bool south;
    public bool west;
    public bool east;
    public InfoCell cell;
}

public List<EdgeCell> GetSurroundingCellsCircleEdge(Coord coord, int distance)
{
    bool CheckIfCoordInCircle(int x, int z)
    {
        int c = x - currentCoord.x;
        int d = z - currentCoord.z;

        if ((c * c + d * d) < SQ)
        {
            return true;
        }

        return false;
    }

    List<EdgeCell> matches = new List<EdgeCell>();
    int EX = distance + coord.x;
    int EY = distance + coord.z;
    int SQ = distance * distance;

    for (int x = coord.x - distance; x <= EX; x++)
    {
        for (int z = coord.z - distance; z <= EY; z++)
        {
           if(CheckIfCoordInCircle(x, z))
           {
                EdgeCell eCell = new EdgeCell();
                InfoCell cell = GetCell(new Coord(x, z));

                if (!CheckIfCoordInCircle(x - 1, z))
                {
                    eCell.cell = cell;
                    eCell.west = true;
                }
                if (!CheckIfCoordInCircle(x + 1, z))
                {
                    eCell.cell = cell;
                    eCell.east = true;
                }
                if (!CheckIfCoordInCircle(x, z - 1))
                {
                    eCell.cell = cell;
                    eCell.south = true;
                }
                if (!CheckIfCoordInCircle(x, z + 1))
                {
                    eCell.cell = cell;
                    eCell.north = true;
                }

                if (eCell.cell != null)
                    matches.Add(eCell);
            }
        }
    }

    return matches;
}

```
> 0 votes

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


title: wavefront .obj file loader problem

text:
# Question
Title: wavefront .obj file loader problem
I'm pretty new to direct x and c++, I have a problem with loading .obj files.

This is a cube

I think the problem is with creating vertices and indecies.

```
list<vertex> FinalVertices;

list<unsigned long> Indecies;
for (int i = 0; i < Faces.size(); i++)
{
    for (int j = 0; j < Faces.size(); j++)
    {
        if (Faces[i] == Faces[j])
        {
            cout << 'b' << endl;
            if (i == j)
            {
                FinalVertices.push_back(Faces[i]);
                Indecies.push_back(j);
            }
            goto a;
        }
    }
a:
    cout << ' ';
}

```

# Answer
It looks like you're adding an index only when you encounter a new unique vertex. You want to add the index for repeated vertices too, so move that line outside the `if (i==j)` block.

```
if (Faces[i] == Faces[j]) {
    cout << 'b' << endl;
    if (i == j) {
        FinalVertices.push_back(Faces[i]);
     }
     Indecies.push_back(j);
     goto a;
}

```
> 0 votes

---
Tags: c++, directx11
---


# Question
Title: Is it safe to make a null reference check like if(component) on Unity GameObjects/Components?
I was reading that Unity does not store GameObjects being `null` literally, but instead overloads the `==` operator.

For this reason the null coalescence operators `??` `??=` don't work on GameObjects or Components

But if GameObjects and Components are never set to the literal value `null`, and instead `==` is overloaded, is it unsafe to do a null check `if(component != null)` as `if(component)`? The latter option compiles and seems to work fine, but I don't understand why if it's not ever the value `0`, and if this will actually cause problems down the line

# Answer
> 2 votes
Yes, because `GameObject` inherits `Object` that implements a conversion to bool, `Object.bool`, which is what gets evaluated when you write `if (object)`.

The linked docs assert that the conversion behaves equally to `operator!=` which I assume in any sane world of boolean axioms behaves as `!(operator==)`, meaning that the conversion behaves as `operator==`, not as `System.Object.ReferenceEquals(gameObject, null)`.

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


# Question
Title: Fixed timestep, updates per second keeps changing?
I've been trying to create a deterministic, fixed gameloop.
The game loop should run TICK\_RATE # of physics updates per second, and then render as quickly as possible (didn't do interpolation yet).
The issue I'm currently having is that the # of physics updates per second isn't constant. I want it to be the same as TICK\_RATE, but it constantly changes by 1.
E.g. the tick-rate varies from 60-61 if TICKRATE = 60.

I thought this issue might be due to rounding issues, but manually calculating the delta time with System.nanoTime() and storing everything as a double gives me the same problem. If the physics simulation constantly varies by 1 frame per second, it's not longer deterministic, which I think would be hard to replicate (for networking and replays for example).
Any ideas on how to fix this so the number of physics updates per second is constant?

```
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx

private const val TICK_RATE = 60 //Number of updates per second
private const val TIME_STEP = 1f / TICK_RATE //Seconds per tick
private const val MAX_FRAME_SKIP = (TICK_RATE * .2).toInt() //If fps drops below 20% of tickrate, slow down game to
                                                            //avoid spiral of death

class FixedTimestep : ApplicationAdapter() {

    private var accumulator = 0f

    //variables for ticks per second tracking
    private var tps = 0
    private var previousNanoTime = System.nanoTime()

    override fun render() {
        var frameSkipCount = 0
        val delta = Gdx.graphics.rawDeltaTime
        accumulator += delta
        while (accumulator > TIME_STEP && frameSkipCount < MAX_FRAME_SKIP) {
            accumulator -= TIME_STEP
            //do physics step

            //display tps to console every second
            tps++
            val currentNanoTime = System.nanoTime()
            if (currentNanoTime - previousNanoTime >= 1000000000L) {
                println(tps)
                tps = 0
                previousNanoTime = currentNanoTime
            }
        }
        //render
    }
}

```

# Answer
Having a constant time-step does not mean that you force your client to update exactly 60 times per real-life second, it means that whenever you update your physics the timestep *you send to your physics engine* must have a set value (in this case `1/60th` of a second).

In other words your code is mostly correct:

```
TIMESTEP = 1 / 60;

accumulator = 0;

update(delta) {
    render(delta);
    accumulator += delta;

    // Don't forget the "=" too in case of the very rare edge-case where they are equal!
    while(accumulator >= TIMESTEP) {
        // THIS is the important part!
        // This is where you must send TIMESTEP, not delta, to your physics engine.
        physicsTick(TIMESTEP);
    }
}

```

The fact that `physicsTick(TIMESTEP)` might in reality be called 4, 10, 60, 61, 581, ..., times per second should be irrelevant to you and is the **entire reason** behind the "accumulator pattern" (that the step can remain constant but the number of steps each second dynamic). What if a user has a super slow computer that can only handle 10 ticks per second? What if a hacker unlocks the tick rate to 2000 ticks per second? That should not break anything on the server and being 1 frame off every now and then definitely shouldn't.

Remember that the server is always the authority. When displaying a replay to the user or updating the positions of network entities you use the *server's* physics interpretation and send that to the client. This is how games like Overwatch handle replays Source here (YouTube: "Overwatch Gameplay Architecture and Netcode"). Sorry I don't have a timestamp but I recommend listening to the entire talk! They talk about clientside prediction and networking using fixed physics timestep.
> 2 votes

# Answer
The problem may be caused by disagreement between the clocks, either due to rounding errors or different timer resolution. Try using same source of current time and avoid time-delta accumulator — work with a timestamp instead.

Here is a "little" script in Python (sorry, I don't know Kotlin) to demonstrate what I mean. Run this file as a normal Python script (`python script.py`). Hit `Ctrl+C` after some time to show final stats. The script maintains 2 clocks (real and logical) while emulating core loop; the script prints message every time one of the clocks thinks one second has passed, where "sync" means clocks do agree (at exact same moment).

As per my own advice, 1) I derive frame count goal from a timestamp instead of using an accumulator and 2) all time-related information comes from same source (`get_time`). Notice how logical clock maintains stable update rate even when clocks do disagree.

Play with variables to cause the "spiral of death" or rubber-banding.

```
import time
import random

MS = 0.001

UPDATE_RATE = 60
RENDER_OVERHEAD = 3 * MS
UPDATE_OVERHEAD = 7 * MS
MAX_UPDATE_TIME = 200 * MS
OVERLOAD_INITIAL = 500 * MS
OVERLOAD_DELTA = -50 * MS

def main():
    now = get_time()
    real_clock = FixedTimestep(now, 1)
    logical_clock = FixedTimestep(now, UPDATE_RATE)
    subsystems = Subsystems()

    ups = 0
    update_count = 0
    stats_real_seconds = 0
    stats_logical_seconds = 0

    try:
        while True:
            subsystems.render()
            frame_time = get_time()
            while True:
                real_clock_advanced, real_second_passed = real_clock.advance(frame_time)
                logical_clock_advanced, logical_second_passed = logical_clock.advance(frame_time)

                if logical_clock_advanced:
                    subsystems.update()
                    update_count += 1

                if real_second_passed:
                    stats_real_seconds += 1

                if logical_second_passed:
                    stats_logical_seconds += 1
                    ups, update_count = update_count, 0

                if real_second_passed or logical_second_passed:
                    report(real_second_passed, logical_second_passed, ups)

                if not real_clock_advanced and not logical_clock_advanced:
                    break

                if MAX_UPDATE_TIME < (get_time() - frame_time):
                    break

    except KeyboardInterrupt:
        pass

    print("Done.")
    print(f"Stats: {stats_real_seconds} real seconds, {stats_logical_seconds} logical seconds.")
    print("Sanity check:", "pass" if (stats_logical_seconds == stats_real_seconds) else "SPIRAL OF DEATH")

def get_time():
    return time.time() # float, seconds since epoch

def report(real_second_passed, logical_second_passed, ups):
    real_text = "real" if real_second_passed else "----"
    logc_text = "logc" if logical_second_passed else "----"
    sync_text = "sync" if (logical_second_passed and real_second_passed) else "    "
    ups_text = f"{ups} UPS" if logical_second_passed else ""
    message = f"{real_text} {logc_text} | {sync_text} | {ups_text}"
    print(message)

def random_spread(margin):
    return random.uniform(1 - margin, 1 + margin)

class FixedTimestep:
    def __init__(self, now, tick_rate):
        self._start_time = now
        self._tick_rate = tick_rate
        self._count = 0

    def advance(self, now):
        local_now = now - self._start_time
        goal = int(local_now * self._tick_rate)
        if self._count < goal:
            self._count += 1
            second_passed = (self._count % self._tick_rate) == 0
            return (True, second_passed)
        return (False, False)

class Subsystems:
    def __init__(self):
        self._overload = OVERLOAD_INITIAL

    def render(self):
        delay = RENDER_OVERHEAD * random_spread(0.5)
        time.sleep(delay)

    def update(self):
        self._overload = max(0, self._overload + OVERLOAD_DELTA)
        delay = (UPDATE_OVERHEAD + self._overload) * random_spread(0.8)
        time.sleep(delay)

if __name__ == "__main__":
    main()

```
> 0 votes

---
Tags: libgdx, timestep, kotlin
---


# Question
Title: Simulate shake, tilt and multi-touch in Unity WebGl app
I am developing a multi-platform game in Unity.

It works great on Android and also on WebGL (haven't yet checked iOS).

My problem is that in some of the levels I need to use mobile-specific actions like shake, tilt and multi-touch.

Is there any way to simulate this in a WebGL app?

Examples of what I need: Tilt to move an object without touching the object. The idea is to "sail" the object from the top of the screen into a basket at the bottom avoiding some obstacle on the way. Tilt to cause an object to move across the screen

Shake to cause something to break.

Multi-touch to select two objects at the same time.

# Answer
> 1 votes
> Tilt to move an object without touching the object. The idea is to "sail" the object from the top of the screen into a basket at the bottom avoiding some obstacle on the way. Tilt to cause an object to move across the screen

What you could do here is use mouse dragging on the background to cause a rotation of the whole scene.

> Shake to cause something to break.

Shake the mouse cursor. A good way to detect shaking is to check the difference between mouse positions per frame and count how many times per second the change on the x-axis or y-axis changes from positive to negative.

> Multi-touch to select two objects at the same time.

Standard for multi-selection on PC is to use shift+leftclick or ctrl+leftclick to add an additional object to the current selection. But players might not expect that to be possible in your game, so you need to teach them. But then there is the problem that moving the selection will move it in formation. So it won't allow you to do things like moving two objects towards each other.

So depending on what you *actually* want the player to do, you might have to look for a different UI solution.

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


# Question
Title: How to get the file location of missing sprite in unity?
I accidentally moved some of my sprites and now I can't remember where they were originally. Now in Unity, it says missign - sprite. So can't I get the location saved in scene file??? i.e. if it is referring to Desktop\file.extension and I move it to Desktop\files\file.extension, can I get Desktop\file.extension in Editor???

# Answer
> 1 votes
Unity uses GUID (globally unique identifiers) to keep track of asset references. Any reference to an asset in your project will refer to it by its GUID under the hood.

When you create or move/copy in a new asset file, Unity generates a new GUID for it, and stores it in a ".meta" file alongside it, along with any relevant import settings for the asset.

So for instance if your sprite image is "\[project path\]\Assets\Sprites\mySprite.png", then its GUID will be stored in "\[project path\]\Assets\Sprites\mySprite.png.meta"

These files are hidden by default, but you can configure the editor to save "visible meta files" and use asset serialization mode "force text" to inspect these GUID and their references by hand.

When you move or rename files in the project window in Unity itself, it automatically moves/renames the corresponding meta files too, to keep everything in sync. No other files need to be updated to reflect the new name/location, because they only refer to the GUID, which hasn't changed.

But if you move an asset using your OS file explorer, then to Unity it looks like you deleted the file from its original place (so it deletes the now-unused meta file that had the GUID recorded in it), and then you created a new file in a new location (so Unity creates a new .meta file with a new GUID for this brand new asset). Since the file has a new GUID now, existing references to that sprite are broken.

If you catch this early, before Unity has deleted the .meta files, you can go inspect the .meta files that were left behind and move them to the folder where their corresponding data files went, so your data files keep their old GUIDs.

If Unity has already deleted these files, then you may be out of luck. You can try going through your recycle bin to see if the old .meta files are there for you to undelete. Failing that, you might have to go fix each reference by hand. If you have a *lot* of references to just a few files, you can peek into the scene or prefab file to find the old GUID and paste it into the file's new .meta file to repair all references to that one file at once. But if each asset is referenced just once or twice, doing it by hand through the editor interface might be simpler.

So, moral of the story:

* Move/rename files inside Unity itself, not in external tools.
* OR, if you have to move/rename something elsewhere, be sure to move/rename the .meta files at the same time.

---
Tags: unity
---


title: How to execute a code from many scripts

text:
# Question
Title: How to execute a code from many scripts
I want to execute a function from many scripts attached on gameobjects which will be spawned. Since game objects are spawned, I can't assign the script in the inspector. What i want is that, there are three gameobjects, A,B,C. C is already in the scene. A and B are spawned with different scripts,the spawned gameobject's script should call the function on the gameobject C. I can make a delegate but there are different scripts that want to call the function. So should i have to create different delegates for each script on A and B and then assign them onto the gameobject C so that A and B can call their delegates and these delegates will trigger the function on C or there is something like a event that i can call from B. If it was possible, i can create a event on A and assign it on C. Now A can call the delegate and B can also call that event and trigger the function on C, but this is not possible as event can't be called from another script.

I need something like a function that i can call from any script and it calls the function from C.

Note that function should not be static. As i can call a static function from any script but it can call only static methods, which i don't want.

# Answer
> 0 votes
I used an abstract class in which i put my event. Then i implemented that abstract class on A and B. Now i can call the event from both the game objects even they have different scripts.

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


# Question
Title: The A,I can't seems to move/strafe on the left continously?
```
 void Update()
{
    ChasingPlayer();
}

void ChasingPlayer()
{
    if (chasing == true)
    {
        transform.LookAt(player.transform);  //facing player
        transform.position += transform.forward * approaching * Time.deltaTime;  //going towards player
    }

        float distance = Vector3.Distance(transform.position, player.position);
    Debug.Log(distance); //calculating the distance between player and enemy
    if(distance < 10)
    {
        chasing = false;
        transform.position += Vector3.left * 2f * Time.deltaTime;
        Debug.Log("STOP!");
    }
}

```

I want my A.I to approach to the player but when it reaches within 10 feet(?), I want it to stop moving towards the player and strafe/move to the left or right from there but instead it just moving in a curve movement that leads towards the player. How should i stop the AI within 10 feet(?) and move to the left/right?

# Answer
Your code reads

```
transform.position += Vector3.left * 2f * Time.deltaTime;

```

`Vector3.left` is a world-space direction; it does not take the enemy's current rotation into account. Perhaps what you want is this:

```
transform.position += transform.right * 2f * Time.deltaTime; //to go right

```

or

```
transform.position -= transform.right * 2f * Time.deltaTime; //to go left

```
> 0 votes

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


# Question
Title: Unity - Change base class variable to a derived class in inspector dynamically
In an item system I'm trying to create I'm using prefabs to store an item's default values, and then grab that item from the prefab to use in runtime. It works well, but I was wondering if there was a way to dynamically change a variable with a base type to a derived type, probably with a custom editor, so that I wouldn't have to make separate classes for each derived type. This is the how I'm imagining it would be like:

```
public class ItemPrefab : Monobehaviour {
    public ItemTypes itemType;
    public Item item;
}

public enum ItemTypes {
    meleeWeapon,
    rangedWeapon
}

```

Item is an abstract base class, and MeleeWeapon and RangedWeapon are serializable derivatives. With that, I'm trying to do something to the effect of this:

```
switch (itemType) {
    case ItemTypes.meleeWeapon:
        item = item as MeleeWeapon;
        break;
    case ItemTypes.rangedWeapon:
        item = item as RangedWeapon;
        break;
}

```

I was wanting it to be the same as the below, just less scripts.

```
public class MeleeWeaponItemPrefab : Monobehaviour {
    public MeleeWeapon item;
}

public class RangedWeaponItemPrefab : Monobehaviour {
    public RangedWeapon item;
}

```

Edit: Here is my item system so far (I just included MeleeWeapon because I didn't want this to get too long).

```
public abstract class Item {

    [Header("Basic Info")]
    [SerializeField] private string name = "";
    [SerializeField] private Image icon = null;
    [SerializeField] private GameObject itemPrefab = null;
    [SerializeField] private float weight = 0;
    [SerializeField] private int maxStack = 0;
    private Guid gUID;

    public string Name => name;
    public Image Icon => icon;
    public GameObject ItemPrefab => itemPrefab;
    public float Weight => weight;
    public int MaxStack => maxStack;
    public Guid GUID { get { return gUID; } private set { gUID = Guid.NewGuid(); } }
}

public abstract class Weapon : Item {
    public abstract void Attack();
}

[System.Serializable]
public class MeleeWeapon : Weapon {

    [Header("Weapon Attributes")]
    [SerializeField] private MeleeWeaponTypes weaponType = default;
    [SerializeField] private float damage = 0;
    [SerializeField] private float chargeDamage = 0;
    [SerializeField] private float meleeSpeed = 0;
    [SerializeField] private float chargeTime = 0;
    [SerializeField] private float chargeCooldown = 0;

    public MeleeWeaponTypes WeaponType => weaponType;
    public float Damage => damage;
    public float ChargeDamage => chargeDamage;
    public float MeleeSpeed => meleeSpeed;
    public float ChargeTime => chargeTime;
    public float ChargeCooldown => chargeCooldown;

    public override void Attack() {
        // attack
    }
}

```

I have other stuff in Weapon and its derivatives but I removed it to keep the base idea more simple. Anyway, I then have prefabs with a MonoBehaviour that hold a derived type of Item, like I showed above, as data containers that I use to instantiate items during runtime.

# Answer
First, your `Item` class should probably extend `ScriptableObject` so you can define your weapons in asset files.

There are two approaches I use for situations like this, both which involve generics.

**Approach 1**: Use a generic base class

```
public class WeaponItemPrefab<T> : Monobehaviour where T : Weapon {
    [SerializeField] private T item;
    public T Item => item;
}

public class MeleeWeaponItemPrefab : WeaponItemPrefab<MeleeWeapon> { }
public class RangedWeaponItemPrefab : WeaponItemPrefab<RangedWeapon> { }

```

**Approach 2:** Create a service class for retrieving the weapon types

```
public class WeaponPrefabService : MonoBehaviour {
    [SerializeField] private List<Weapon> weapons; //filled in from Inspector

    public T GetWeapon<T>() where T : Weapon {
        foreach (Weapon weapon in weapons) {
            if (weapon is T) {
                return weapon as T;
            }
        }
        return null;
    }
}

```

Note that if you have a large list of weapons and call the `GetWeapon()` function frequently, it might be better for performance to sort the weapons into a Dictionary:

```
private Dictionary<Type, Weapon> weaponsDictionary;

public void Start() {
    weaponsDictionary = new Dictionary<Type, Weapon>();
    foreach (var weapon in weapons) {
        weaponsDictionary.Add(weapon.GetType(), weapon);
    }
}

public T GetWeapon<T>() where T : Weapon {
    T weapon = null;
    weaponsDictionary.TryGetValue(typeof(T), out weapon);
    return weapon;
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: How to prevent Unity from generating unnecessary changes after saving a scene with no actual changes
I was having trouble where Git shows a lot of changes (for my case, about ~3000 diff change since I have many objects in the scene) after saving a scene (.unity file) in Unity, even though there are no changes made to the scene.

Upon checking, I noticed Unity recompiled the scene file and some values are just in a different order.

How do we prevent this from happening?

Steps to reproduce:

1. Open the scene file.
2. Disable and re-enable any GameObject (just to trigger Unity to think there are changes, so you can save the scene file).
3. Save the scene file.

# Answer
> 1 votes
**EDIT: This bug seems to have been fixed in newer versions of Unity (e.g. 2020 LTS and 2021 LTS).**

---

As far as I know, this is caused by a bug or design flaw in the Unity Editor. When you add UI prefabs to a scene, the Editor is very aggressive about generating property overrides for most properties on your UI prefabs, even when those overrides aren't actually needed. Not only does this increase the size of the scene file, it can completely break your UI if you make changes in the prefab and those changes don't show up correctly in the scene because of undesired overrides. IIRC this problem has gotten worse in newer versions of Unity.

If you have a simple, 100% reproducible example, I'd suggest reporting this to Unity as a bug.

---
Tags: unity, scene, serialization, version-control
---


title: Player not detecting layermask

text:
# Question
Title: Player not detecting layermask
I'm trying to implement a simple collision detection for my player but it is not detecting the layer mask as my Player comes into contact with it. I have a move point that moves slightly ahead of the player, and if it comes in contact with the StopMovement layermask then it should NOT move any further. Unfortunately, the layer is never detected and therefore the player just moves right through the object.

Script:

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    private float moveHorizontal;
    private float moveVertical;

    public Transform movePoint;

    public LayerMask whatStopsMovement;

    // Start is called before the first frame update
    void Start()
    {
        movePoint.parent = null;
    }

    // Update is called once per frame
    void Update()
    {
        moveHorizontal = Input.GetAxisRaw("Horizontal");
        moveVertical = Input.GetAxisRaw("Vertical");
    }

    private void FixedUpdate()
    {
        transform.position = Vector3.MoveTowards(transform.position, movePoint.position, moveSpeed * Time.fixedDeltaTime);

        // stops the movePoint from going too far
        if (Vector3.Distance(transform.position, movePoint.position) == 0f)
        {
            if (Mathf.Abs(moveHorizontal) == 1f) // makes it so we can check if 1f OR -1f without == 1f || -1f
            {
                if (!Physics2D.OverlapCircle(movePoint.position + new Vector3(moveHorizontal, 0f, 0f), 0.2f, whatStopsMovement))
                {
                    Debug.Log("No collision");
                    movePoint.position += new Vector3(moveHorizontal, 0f);
                }
                else
                {
                    Debug.Log("Collision");
                }
            }

            else if (Mathf.Abs(moveVertical) == 1f) // makes it so we can check if 1f OR -1f without == 1f || -1f
            {
                if (!Physics2D.OverlapCircle(movePoint.position + new Vector3(moveVertical, 0f, 0f), 0.4f, whatStopsMovement))
                {
                    Debug.Log("No collision");
                    movePoint.position += new Vector3(0f, moveVertical);
                }
                else
                {
                    Debug.Log("Collision");
                }
            }
        }
    }
}

```

Any help at all is appreciated.

# Answer
`Physics2D.OverlapCircle` detects `Collider2D` components.

Your square obstacle does not have a `Collider2D` that we can see, so it will be invisible to physics methods.
> 1 votes

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


# Question
Title: Formula Racing Physics in curves (under-steer, over-steer)
I have a working physics code for a -let's say- WipeOut-style vehicle \[well, closest approximation\]. Some time next year I would like to do a formula game but am struggling to get to tweak my code to behave anywhere near the way the formula (say, like in F1 GP game that ran on 100 MHz Pentiums) behaves in **curves**.

Visually, think 3D engine and a 3D track (with hills/valleys - but still a track (not a generic heightmap)).

Since the target HW is below 100 MHz and code is written in ASM, we can't use any off-the-shelf physics engines, but it must be written from scratch (initial prototyping will be done in C++ for max productivity and understanding of limitations of the physics component).

Now, I don't have any issue with the following (already working):

* non-linear acceleration (e.g. each gear range has different constants/behavior)
* hill-based acceleration/decceleration (how steep hill is)
* car gets lighter over time (less gas in the tank), affecting acceleration
* each parameter can have an additional modifier (linear, non-linear) applied to it over the time

My greatest issue is I can't seem to get the thing to **over-steer** / **under-steer** in curves. I want to allow the player to choose several different levels of physics - from Arcade, through gradually more realistic features, to a full-blown (as far as manageable by me) physics (like in F1GP game). So far, I have these racing physics modes implemented:

* Arcade racing (kinda like in Lotus/Outrun)
* gear-specific non-linear acceleration (each formula has different characteristics)
* hill-based speed-up/down (steepness)
* speed-based drag in curves (how quickly car reacts to turning)
* tire temperature gradually rising (affecting all physics ranges, modifiers and constants)

Through trial&error I found a way how to get the car to turn faster/slower based on current speed. It works pretty well, but it won't realistically skid the car away from the track (like F1GP does).

Also, nowhere in the code, I actually use any vectors. It's all just constants, valid ranges, and type of applied modifier (none/speed-up/down, linear/non-linear) that we use on the desired variable, as that's the fastest possible way on given platform (all these values fit into available CPU's registers, unlike vectors that have to be read from slow RAM).

So, how does one actually get the car to ***under-steer/over-steer*** in curves ? What's the actual physics here ? Rigid Body ? I believe it should be perfectly possible to emulate this feature via 2D vectors (car direction + speed) ?

# Answer
> 1 votes
I would add oversteer/understeer control as follows:

* Have different friction settings for the front tyres and rear tyres (against terrain.)
* If front tyres have more friction, your car should oversteer.
* If rear tyres have more friction, your car should understeer.

If that does not work for you, you could play by widening/shorting the track (spacing between the left and right wheels.) I suspect a wider car to oversteer more easily, but you would have to experiment with that. The friction differential is probably a better approach.

Note: that in real-world F1 racing, oversteer can be induced with higher downforce on the front wing.

So if you model downforce in your simulation, you could play with that: shift downforce from the rear to the front for more oversteer.

Lastly, you can also eliminate oversteer by moving from rear-wheel-drive to front-wheel-drive. The latter is typically understeered, the former is typically oversteered.

**UPDATE**: If you do not use a physics engine, you can fake oversteer by giving the car-rotation some momentum!

So instead of controlling the car's angular velocity with the joystick, you control the angular acceleration of the car with the joystick:

As you move back the joystick to the centre, the car continues its rotation for a while, forcing your players to counter-steer.

pseudo code:

```
rotvel = rotvel + joystick.x * dt;
rotang = rotang + rotvel * dt;
// bleed off the residual angular velocity
rotvel = 0.80f * rotvel;
// apply the rotation to the car
car.rotation = rotang;

```

---
Tags: physics, 3d, racing
---


title: Optimizing 3D tile-based geometry

text:
# Question
Title: Optimizing 3D tile-based geometry
For my game, I have a tool that lets me quickly create map geometry. You can see a (albeit early version) demo of the tool here. The main problem with the tool is that even a semi-large map can EASILY amount to around thousands to even 10s of thousands of tiles. The easiest way to fix this, I found, was to use a script I found online to merge all of the tiles into one mesh at the start of runtime (this is because I want to still be able to edit my tilemap in the editor)

This works and has a noticable improvement to the performance (especially if post-processing is enabled) however I'm left with a mesh that has a bunch of triangles that just aren't needed. You can see an image of the mesh here. The problem with this is that if I want to do any kind of point lights with shadows (baked lighting isn't possible, really, due to the interactivity of my game since you can turn lights on/off and I have a weird day/night system that is split into multiple periods of the day and only changes after a mission/event) would mean I'm rendering that mesh again from each point lights POV (and I need a LOT of point lights). I can't really just not use shadows since it causes very noticable light bleeding at walls.

I've tried to find some sort of algorithm to simplify the mesh and I came across a script that seems to do exactly what I want, but I couldn't get it to do anything except cause my mesh to become completely black with seemingly no change in mesh topology. Here's the script by the way

I've also found an algorithm called Greedy Meshing which seems to also do what I want, but seems to be meant for voxel based worlds like minecraft and I'm not sure how to implement it in my case since my tiles aren't voxels.

I've been trying to find other algorithms but the various game dev servers on discord can't seem to help me. Does anyone know how I can solve this problem? I'm not really smart enough to come up with my own algorithm/system to simplify the mesh.

# Answer
> 0 votes
I have solved this for the most part, atleast for floor tiles.

I was able to get the script, that I spoke about in the OP that didn't work, working and was able to get it to simplify the floor tile mesh (wall simplification doesn't work yet, sadly.)

Here's an image of the tilemap in the editor and the tilemap at runtime

Essentially:

* Tiles are first merged using Unity's MeshCombiner utility
* Then the mesh simplification classes 'Weld' function is used to remove any duplicate vertices
* Then the mesh simplification classes 'Simplify' function is used to simplify the mesh

---
Tags: unity, c#, 3d-meshes, mesh, meshcollider
---


title: Attach movement to each list object

text:
# Question
Title: Attach movement to each list object
How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N-1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere.

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

public class Spawner : MonoBehaviour
{
    public GameObject[] prefabs;
    public List<GameObject> listBalls = new List<GameObject>();
    private GameObject x;
    public int timer = 0;
    private float movementSpeed = 5f;

    void Start()
    {
        createBall();
    }

    void Update()
    {
        if (Time.time - timer > 0.8f)
        {
            createBall();
            timer += 2;
        }
        listBalls[listBalls.Count-1].transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
    }

    void createBall()
    {
        x = prefabs[Random.Range(0, prefabs.Length)];
        Instantiate(x, x.transform.position, Quaternion.identity);
        listBalls.Add(x);
    }

    void moveBall(GameObject x, GameObject y)
    {
        x.transform.position += y.transform.position - new Vector3(0,0,-1);
    }
}

Loop added but movement staggered

        void Update()
    {
        if (Time.time - timer > 0.8f)
        {
            createBall();
            timer += 2;
        }
        foreach (GameObject item in listBalls)
        {
            item.transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
        }
    }

```
</code></pre>

# Answer
> 0 votes
There are several ways to do this, depending on how exactly you want the balls to move. Most solutions are going to use some kind of *loop*. If you aren't familiar with loops, you should read some tutorials on loops in C#.

**Example 1: All balls move same direction/distance each frame**

```
Vector3 movement = new Vector3(0, 0, movementSpeed * Time.deltaTime);

foreach (var ball in listBalls) {
    ball.transform.position += movement;
}

```

**Example 2: Each ball moves towards the next ball**

```
float distance = movementSpeed * Time.deltaTime;
//move the last ball
listBalls[listBalls.Count - 1].transform.position += new Vector3(0, 0, distance);

//move each ball (except the last) towards the next ball
for (int i = 0; i < listBalls.Count - 1; i++) { //note we don't want to move the last ball again
    Transform ball = listBalls[i].transform;
    Transform nextBall = listBalls[i + 1].transform;
    ball.position = Vector3.MoveTowards(ball.position, nextBall.position, distance);
}

```

---
Tags: unity, movement, spawning
---


# Question
Title: Forward Shading with multiple shadow-casting lights
I am currently thinking about how to organize shadowing and lighting.

We use forward rendering and currently, our algorithm looks like this:

* collect all items that are visible in the view
* for each item, collect a list of lights where the item is in the attenuation radius (each item keeps a list of lights)
* determine the shadow light by the distance of the main character (only one light can currently cast shadow)
* render the scene by using a constant buffer of the currently processed item to shade it (each item is rendered with a constant buffer which contains light properties. the number of lights per item is predefined so we have a `Light[16]` and `numLights` in the constant buffer)

How would I do multiple shadow-casting lights in an organisatory way?
We do not want to go the deferred way, since we dont want to limit us to GBuffers.

# Answer
The answer is primarily depends on target hardware. For modern GPU I would like to suggest tiled or clustered forward rendering.

The core idea behind the clustered forward rendering is to split frustum on clusters (froxels).

You need the following GPU resources:

* Texture3D to be aligned within frustum.
* Buffer to keep indices of lights (list).
* Several constant or structured buffers to keep lights' data for each light type (omni, spot, etc).

Shading algorithm is following:

1. On CPU: For each cluster collect all lights that affect given cluster. Add indices of these lights to list of indices. Write starting offset and count of indices to 3D texture. This part could be done on GPU side, but CPU is pretty fast.
2. On GPU: In pixel shader determine cluster, get index offset and number of indices and iterate over all lights.

For shadows I would recommend to render all shadow maps to atlas. Light may contain atlas region and shadow map projection matrix.

See this paper for more details:
> 1 votes

---
Tags: rendering, lighting, shadow-mapping
---


# Question
Title: Software rendering 3d triangles in the proper order
I'm implementing a basic 3d rendering engine in software (for education purposes, please don't mention to use an API). When I project a triangle from 3d to 2d coordinates, I draw the triangle. However, it's in a random order and so whatever gets drawn last draws on top of all other triangles (which might be in front of triangles it shouldn't be in front of)...

Intuitively, seems I need to draw the triangles in the correct order. So I can calculate all their distances to the camera and sort by that. The objects furthest away get drawn last. Is this the proper way to render triangles? If I'm sorting all the objects, this is n\*log(n) now. Is this the most efficient way to do this?

# Answer
> 4 votes
This is a valid approach normally known as the Painter's Algorithm. Sorting your triangles will not support overlapping triangles. By that I mean two triangles that overlap in a way such that half of one triangle is infront of the other, while the other is behind. If you don't need to support this, you could probably just do **sorting back to front**. That is, the furthest geometry gets drawn **first**.

The more general technique typcally used is a depth buffer. When you paint a pixel, you also record its depth. Then, when you go to paint the pixel again, you can compare depths to see if you need to keep the new pixel or the old pixel. Please see the linked wikipedia article for more info.

# Answer
> 0 votes
1st question: Is this the proper way to render triangles? This will usually work, but not always (see below for details).

2nd question: If I'm sorting all the objects, this is n\*log(n) now. Is this the most efficient way to do this? Probably, unless you know something special about the triangles before you start drawing them (e.g., if you are drawing a surface that doesn't fold over itself, you can do it quicker because any order will work).

Some details on the 1st question: I think I'm working on the same problem. I create a list of triangles using triples of (x,y,z) coordinates and then send them in order to a draw\_triangle method. None of my triangles overlap (i.e., none puncture or slice through each other). However, the "back to front" approach using distance does not always work. It occasionally draws some triangles in front of others when they should be behind them.

Stephen's response that "you could probably just do sorting back to front" is fairly accurate, as this works *almost* all of the time for normal cases. However, I started noticing errors and eventually determined that the cause was the ordering algorithm that did back to front by distance.

A simple counter-example is two triangles arranged like a bowtie, where they overlap in the middle near their vertices. Assume the right triangle is slightly behind the left triangle. Now rotate the entire bowtie as a single unit so that the right side comes forward and the left goes back. Using "back to front" based on distance, the left triangle is drawn first because it is farther away. However, the correct order is to draw the right triangle first, because it is behind the left one where they overlap.

A solution to resolve this is based on a different method to compare the drawing order of any two triangles, instead of just distance. It looks at whether any vertex of one triangle is "inside of" the other triangle from the perspective of the viewer. If so, it determines whether that vertex is in front of or behind the other triangle and then orders the triangles the same way. If not, the order doesn't matter because neither triangle obstructs the other. This 2-triangle comparison is then used as the comparison operator for a sorting algorithm that sorts all triangles.

This works if there are no cycles in your triangle order. It is possible that part of triangle A is in front of part of triangle B, part of B is in front of part of C, and part of C is in front of A. For example, in the bowtie example, add a third triangle that overlaps part of the right side and part of the left, but does not overlap the center of the bowtie. In this case, the left triangle blocks the right, right blocks third, and third blocks left, so there is no ordering that will work. A more sophisticated method is required than just choosing an order to draw the triangles. Depth buffers would work if you switch to drawing pixels, or you could divide triangles into smaller ones that break the cycles in order to stay with the draw\_triangle interface.

---
Tags: 3d, rendering, 3d-meshes, software-rendering
---


# Question
Title: In snapshot-based networked game does client store N snapshots as well?
I understand that in a snapshot-based network replication system the server holds onto N full snapshots and uses incoming ACK'd data from the clients to construct delta snapshots. This makes sense. What I have not seen a lot of information about is how the client uses that delta compressed snapshot to apply the changes.

Does the client store N snapshots so that it can reconstitute the delta compression against the reference it claims to have, or does it simply have one snapshot state of accumulated deltas? I imagine the former being correct, but the latter being less memory.

I've read How would a game-state snapshot system be implemented for networked real-time games? and and other answers, looked at Fabien's post, and read a couple of articles by Valve, but I am still unclear.

Any thoughts on this?

# Answer
> 1 votes
## Overview

The server's state updates with each game tick and a new state is calculated. This new state is enqueued until it is ready to be sent.

When the networking loop is ready to send the state it checks to see what the last acknowledged state is. If there is none then it sends the full state. If there is one, it calculates the delta between that state, and the new one, and sends the resulting delta.

This delta is then sent to the client. The client enqueues the delta into its buffer. The client code then interpolates between deltas to calculate the current state.

## Old states need to be stored to buffer network traffic

Clients usually have a queue of game states or deltas. This buffer is used to reduce jitter (new deltas may arrive at semi-random times), provide insulation against packet loss/lag (if a packet fails to come through or is slow, there is still time to wait for another) and increase the rate of visual updates (deltas may be sent 100 times per second, but the client wants to run at 200fps and has a 144hz monitor).

Keep in mind, even though I called these "old" states, the client is yet to see the data. These states are only old from the server's perspective.

Beyond that, it depends on how deltas are being used, and what your architecture is. Deltas can either be absolute (A = 1) or relative (A += 1).

## There's no need to store past states for absolute deltas

If deltas are absolute, there is no need for clients to store past states. The server can calculate the delta from the last acknowledged state, and the system will run correctly. There is no chance that you will mess something up by setting A = 1 and then setting A = 1 again.

For example, imagine the client has the following states held in its cache:

* {tick\_number = 1, A = 0}
* {tick\_number = 3, A = 2}

The client then receives a delta {tick\_number = 2, A = 1}. We can trust that the server has sent us the delta relative to the last state it knows we have received, so we can insert it without any problems.

## You need a consistent reference point for relative deltas

If the system is using relative deltas, it is important to make sure that the client and server understand that the delta is relative to the same thing. If the server things that A = 1, while the client thinks that A = 10, then a delta of A += 1 is going to yield different results.

With this architecture, the client will need to store the youngest state that the server has used in a delta and every state younger than that.

For example, imagine the client has the following states held in its cache:

* {tick\_number = 1, A = 0}
* {tick\_number = 2, A = 1}
* {tick\_number = 3, A = 2}

The client receives the following delta from the server delta: {tick\_number = 5, relative\_to = 2, A = 2}. The client now knows that the server is always trying to use the newest state that the client has sent an acknowledgement for. Since the server is happy to send packets relative to tick number 2, that means there is no reason why the server would then go back to sending relative to tick number 1, so we can discard that state (unless it is still being used for interpolation).

## For applications with sparse tick rates and/or unreliable networks, there may be benefits to holding on to packets

Continuing from the scenario above, the client has received the packet for tick number 4, and discarded its own tick number 1 since it is obsolete. This is the state of packets in the client:

* {tick\_number = 2, A = 1}
* {tick\_number = 3, A = 2}
* {tick\_number = 5, A = 2}

Now the client receives a delta that has arrived out of order: delta {tick\_number = 4, relative\_to = 1, A = 3}. Well, if we had kept the tick number 1 state, we would be able to use this packet to interpolate and calculate the tick number 4 state. In the previous example we threw it out, so now we can't properly calculate the tick number 4 state.

Luckily, ticks are usually very small, so we can interpolate between tick number 3 and 5. If this would harm your application, then it could be worth storing states a little longer.

---
Tags: networking, server, client
---


# Question
Title: Using coroutines and texture array for talking animation?
I was thinking of having random textures from a texture array being chosen every 0.5 seconds through a coroutine to imitate talking if something like talking=true. Not sure how I could set this up and such so I appreciate any help!

# Answer
> 1 votes
Welcome to the community!

Not sure about texture changing, but if you would like to do that with sprites, here's an example.

```
public sealed class TalkingAnimation : MonoBehaviour
{
    [SerializeField] private SpriteRenderer _renderer;
    [SerializeField] private Sprite[] _sprites;
    [SerializeField] private float _spriteChangeInterval;

    public void StartTalking()
    {
        StopAllCoroutines();
        StartCoroutine(TalkingRoutine());
    }

    public void StopTalking()
    {
        StopAllCoroutines();
    }

    private IEnumerator TalkingRoutine()
    {
        while (true)
        {
            yield return new WaitForSeconds(_spriteChangeInterval);
            _renderer.sprite = _sprites[Random.Range(0, _sprites.Length)];
        }
    }
}

```

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


title: Unlock levels using coins - Unity

text:
# Question
Title: Unlock levels using coins - Unity
I'm creating a game that has multiple levels. The first three levels are free but the others can be unlocked either using coins (collected during the game) or through IAP. For the coins, I'm using a binary formatter to store the number of coins. The reason I'm using BF is because it persits through all levels(so far this seems to work as the coin score is carried through to other levels). Here is code I have so far in the coinSystem:

```
public class CoinSystem : MonoBehaviour
{
  public TextMeshProUGUI coinScoreText;
  public int coinScore;

  void Start()
  {
    LoadScore();
  }

  public void Save()
  {
    coinScore++;
    coinScoreText.text = coinScore.ToString();

    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open(Application.persistentDataPath + "/TotalCoinScore.dat", FileMode.Create);

    CoinContainer coinContainer = new CoinContainer();
    coinContainer.coinScore = coinScore;

    bf.Serialize(file, coinContainer);
    file.Close();
   }

  public void LoadScore()
  {
    if (File.Exists(Application.persistentDataPath + "/TotalCoinScore.dat"))
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/TotalCoinScore.dat", FileMode.Open);
        CoinContainer coinContainer = (CoinContainer)bf.Deserialize(file);
        file.Close();
        coinScore = coinContainer.coinScore;
        coinScoreText.text = coinScore.ToString();

     }
   }
 }

  [Serializable]
  public class CoinContainer
  {
     public int coinScore;
  }

```

This is code that I use to add to the coinScore.

```
public class Player : MonoBehaviour
{
  Rigidbody rb;
  public CoinSystem cs;
  public bool dead = true;

  void Start()
  {
    rb = GetComponent<Rigidbody>();
  }

  .
  .
  .
  .

  void OnTriggerEnter(Collider col)
  {
    if (!dead && col.gameObject.tag == "Enemy")
    {
        die();
    }
    if (!dead && col.gameObject.tag == "Coin")
    {
        cs.Save();
    }
  }

```

So now in the level select menu, I want to add a button that once clicked should enable the user to unlock a particluar level if he has enough coins. For example, if a level requires 500 coins and the user has 600, then on clicking this button the level is unlocked and the total coins now available are 100. And if the number of coins are less than what is required to unlock a level then the user should not be able to unlock that level. I'm not sure how to implement this.

# Answer
> 1 votes
You should first clean up your coinSystem save function. Save should do what it says: save. What you currently do is as well manipulate coin score and it is responsible for displaying it as well. Separate that into different functions. One responsible for displaying your score, the second to add any amount of coins. What if you later want to introduce bigger coins that are worth more than one point?

Now that you have them divided, you can add two more: boolean hasEnoughCoins(int amount) and reduceCoins(int amount). You would call your first function with a simple check against your coin amount and return true or false if he can afford to unlock your level. If he has, you can call the second function to reduce the total amount. After each add/ remove coin amount, you want to call your save.

On a side note: If you are allowing IAP for more coins, the total amount of coins should not be handled locally but server side.

---
Tags: unity
---


title: Direct3D Constant Buffer not updating

text:
# Question
Title: Direct3D Constant Buffer not updating
I started learning Direct3D a week ago and I've been following many tutorials but after I got to the point where I had to create a Constant Buffer I got stuck, the creation of the buffer seems to be working correctly but the `UpdateSubresource` function doesn't seem to update it, the value I'm trying to put in the buffer has no purpose apart from being a proof of concept, the value is the float brightness inside the struct `VS_CONSTANT_BUFFER`.

It is set to 1.0 during the buffer creation, then it is set 0.5 when the frame is redrawn but it doesn't update the buffer on the shader side.

Here is the code, I put all of the Direct3D stuff in one place so there is nothing you don't see:

```
#include "GraphicsInit.h"
#include"Window.h"

float red = 0.0f;
int angle = 0;

struct Vertex
{
    float x, y, z;
    float r, g, b, a;
};

Vertex triangle[] = {
    {-0.5f,-0.5f,0.5f,    1.0f,0.0f,0.0f,1.0f},
    {-0.5f, 0.5f,0.5f,    0.0f,1.0f,0.0f,1.0f},
    { 0.5f, 0.5f,0.5f,    0.0f,0.0f,1.0f,1.0f},
    { 0.5f,-0.5f,0.5f,    0.0f,1.0f,0.0f,1.0f},

    {-0.6f, 0.7,0.4f,    1.0f,1.0f,1.0f,1.0f},
    { 0.4f, 0.3f,0.9f,    1.0f,1.0f,1.0f,1.0f},
    { 0.9f,-0.8f,0.6f,    1.0f,1.0f,1.0f,1.0f}
};

unsigned int indices[] = {
    0, 1, 2,
    0, 2, 3,
    4,5,6
};

ID3D11VertexShader* vs;
ID3D11PixelShader* ps;
ID3D11InputLayout* InputLayout;
ID3D11Buffer* VertexBuffer;
ID3D11Buffer* IndexBuffer;

ID3D11Buffer* VSConstantBuffer = NULL;

//Struct needs to be equal to the one in the shaders
struct VS_CONSTANT_BUFFER
{
    float brightness;
};
VS_CONSTANT_BUFFER VSCBdata;

//CBStruct CBDat = {
//    {
//     std::cos(angle), std::sin(angle), 0.0f, 0.0f,
//    -std::sin(angle), std::cos(angle), 0.0f, 0.0f,
//     0.0f,            0.0f,            0.0f, 0.0f,
//     0.0f,            0.0f,            0.0f, 0.0f
//    }
//};

void InitD3D(HWND hWnd)
{
    //////////////////DEVICE AND SWAPCHAIN//////////////////
    DXGI_SWAP_CHAIN_DESC scd;
    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    scd.BufferCount = 1;                                    // one back buffer
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;     // use 32-bit color
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
    scd.OutputWindow = hWnd;                                // the window to be used
    scd.SampleDesc.Count = 4;                               // how many multisamples
    scd.Windowed = TRUE;                                    // windowed/full-screen mode

    D3D11CreateDeviceAndSwapChain(
        NULL,
        D3D_DRIVER_TYPE_HARDWARE,
        NULL,
        NULL,
        NULL,
        NULL,
        D3D11_SDK_VERSION,
        &scd,
        &swapchain,
        &dev,
        NULL,
        &devcon);

    /////////////////////////////////////////////////////////

    //////////////////SET THE RENDER TARGET//////////////////

    // get the address of the back buffer
    ID3D11Texture2D* pBackBuffer;
    swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

    // use the back buffer address to create the render target
    dev->CreateRenderTargetView(pBackBuffer, NULL, &backbuffer);
    pBackBuffer->Release();

    // set the render target as the back buffer
    devcon->OMSetRenderTargets(1, &backbuffer, NULL);

    /////////////////////////////////////////////////////////

    //////////////////SET THE VIEW PORT//////////////////

    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = sizeX;
    viewport.Height = sizeY;

    devcon->RSSetViewports(1, &viewport);

    /////////////////////////////////////////////////////////

    InitBuffers();
    InitPipeline();

}

void InitPipeline()
{
    //////////////////SHADERS COMPILING//////////////////

    ID3D10Blob* blobvs, * blobps;
    D3DX11CompileFromFile(L"Shaders.hlsl", 0, 0, "VS", "vs_4_0", 0, 0, 0, &blobvs, 0, 0);
    D3DX11CompileFromFile(L"Shaders.hlsl", 0, 0, "PS", "ps_4_0", 0, 0, 0, &blobps, 0, 0);

    dev->CreateVertexShader(blobvs->GetBufferPointer(), blobvs->GetBufferSize(), NULL, &vs);
    dev->CreatePixelShader(blobps->GetBufferPointer(), blobps->GetBufferSize(), NULL, &ps);

    devcon->VSSetShader(vs, 0, 0);
    devcon->PSSetShader(ps, 0, 0);

    /////////////////////////////////////////////////////////

    //////////////////INPUT LAYOUT//////////////////

    D3D11_INPUT_ELEMENT_DESC layout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    };
    dev->CreateInputLayout(layout, 2, blobvs->GetBufferPointer(), blobvs->GetBufferSize(), &InputLayout);
    devcon->IASetInputLayout(InputLayout);

    /////////////////////////////////////////////////////////

    blobvs->Release();
    blobps->Release();

    //////////////////IA//////////////////

    // select which vertex buffer to display
    UINT stride = sizeof(Vertex);
    UINT offset = 0;
    devcon->IASetVertexBuffers(0, 1, &VertexBuffer, &stride, &offset);
    devcon->IASetIndexBuffer(IndexBuffer, DXGI_FORMAT_R32_UINT, 0);

    // select which primtive type we are using
    devcon->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    /////////////////////////////////////////////////////////
}

// this is the function used to render a single frame
void RenderFrame(void)
{
    VSCBdata.brightness = 0.5f;
    // clear the back buffer to a deep blue
    devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(red, 0.2f, 0.4f, 1.0f));

    devcon->UpdateSubresource(VSConstantBuffer, 0, NULL, &VSCBdata, 0, 0);
    devcon->VSSetConstantBuffers(0, 1, &VSConstantBuffer);

    // draw the vertex buffer to the back buffer
    devcon->DrawIndexed(9, 0,0);

    // do 3D rendering on the back buffer here

    // switch the back buffer and the front buffer
    swapchain->Present(0, 0);
}

void InitBuffers()
{
    //////////////////VERTEX BUFFER//////////////////

    D3D11_BUFFER_DESC buffer_desc = { 0 };
    buffer_desc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(triangle);
    buffer_desc.Usage = D3D11_USAGE_DEFAULT;
    buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    buffer_desc.CPUAccessFlags = 0;
    buffer_desc.MiscFlags = 0;
    buffer_desc.StructureByteStride = 0;

    D3D11_SUBRESOURCE_DATA sub = { 0 };
    sub.pSysMem = triangle;
    sub.SysMemPitch = 0;
    sub.SysMemSlicePitch = 0;

    dev->CreateBuffer(&buffer_desc, &sub, &VertexBuffer);

    /////////////////////////////////////////////////////////

    //////////////////INDEX BUFFER//////////////////

    D3D11_BUFFER_DESC index_desc = { 0 };
    index_desc.Usage = D3D11_USAGE_DEFAULT;
    index_desc.ByteWidth = sizeof(unsigned int) * ARRAYSIZE(indices);
    index_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    index_desc.CPUAccessFlags = 0;
    index_desc.MiscFlags = 0;

    // Define the resource data.
    D3D11_SUBRESOURCE_DATA index_data;
    index_data.pSysMem = indices;
    index_data.SysMemPitch = 0;
    index_data.SysMemSlicePitch = 0;

    dev->CreateBuffer(&index_desc, &index_data, &IndexBuffer);

    /////////////////////////////////////////////////////////

    //////////////////CONSTANT BUFFER//////////////////

    // Define the constant data used to communicate with shaders.
    // Supply the vertex shader constant data.
    VSCBdata.brightness = 1.0f;

    // Fill in a buffer description.
    D3D11_BUFFER_DESC CBDesc;
    /////VERY STRANGÊ BEHAVIOUR
    CBDesc.ByteWidth = 16;
    //////
    CBDesc.Usage = D3D11_USAGE_DYNAMIC;
    CBDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    CBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    CBDesc.MiscFlags = 0;
    CBDesc.StructureByteStride = 0;

    // Fill in the subresource data.
    D3D11_SUBRESOURCE_DATA CBInitData;
    CBInitData.pSysMem = &VSCBdata;
    CBInitData.SysMemPitch = 0;
    CBInitData.SysMemSlicePitch = 0;

    // Create the buffer.
    dev->CreateBuffer(&CBDesc, &CBInitData,&VSConstantBuffer);

    // Set the buffer.
    devcon->VSSetConstantBuffers(0, 1, &VSConstantBuffer);

    /////////////////////////////////////////////////////////
}

void CleanD3D(void)
{
    //Device
    dev->Release();
    devcon->Release();
    /////////

    //Swapchain
    swapchain->Release();
    backbuffer->Release();
    /////////

    //Pipeline
    vs->Release();
    ps->Release();
    InputLayout->Release();
    /////////

    //Buffers
    VertexBuffer->Release();
    IndexBuffer->Release();
    VSConstantBuffer->Release();
    /////////
}

```

Here is the header file:

```
    #pragma once

#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include <directxmath.h>
#include <d3dx10math.h>

using namespace DirectX;

// include the Direct3D Library file
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")

//////GLOBAL VARIABLES//////
static IDXGISwapChain* swapchain;             // the pointer to the swap chain interface
static ID3D11Device* dev;                     // the pointer to our Direct3D device interface
static ID3D11DeviceContext* devcon;           // the pointer to our Direct3D device context
static ID3D11RenderTargetView* backbuffer;    // the pointer to our render target
/////////////////////////

void InitD3D(HWND hWnd);     // sets up and initializes Direct3D
void RenderFrame(void);
void CleanD3D(void);             // closes Direct3D and releases memory
void InitPipeline();
void InitBuffers();

```

And the shaders:

```
cbuffer VS_CONSTANT_BUFFER
{
    float brightness;
};

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VS(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    float4 col = { brightness,brightness,brightness,1.0f };
    output.position = position;
    output.color = col;

    return output;
}

float4 PS(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
 }

```

# Answer
> 1 votes
https://docs.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-updatesubresource

> A resource cannot be used as a destination if..... the resource is created with immutable or dynamic usage.

You can't use UpdateSubResource with a buffer created with D3D11\_USAGE\_DYNAMIC - you need to use Map instead.

Alternatively create with D3D11\_USAGE\_DEFAULT and use UpdateSubResource.

Which is better? It depends. Some drivers handle both the same internally. Map means that you shouldn't read from the returned pointer so you may need to refactor a little. UpdateSubResource involves an extra memory copy.

---
Tags: directx11
---


# Question
Title: When importing Mixamo animated characters into Unity, they come without avatar?
I'm using Unity 2019.3.3f1. I create the character in Adobe Fuse. I uploaded it to Mixamo and choose an animation. I then downloaded the fbx for unity file. When imported into Unity, it is visible that the file has no avatar or animator component. How can I fix this? Is it a Unity version issue?

# Answer
> 4 votes
I experienced this problem as well but since no one actually answered the question I'll say what I did to solve it. You are correct that it seems to be a version issue, I fixed it by simply making a new project in an older version (2018.4.7f1 specifically), and then I dragged the fbx file into the project. Once I imported it, I then exported it as a unity package file, and then imported it into the 2019 project file. This gave me the model with the animator component.

---
Tags: unity, animation, fbx, rigging, animator
---


# Question
Title: Unity3D multiple objects user rectangle selection
I wish to allow the user to select multiple units by click and drag as most RTS do. The issue I have is that the tutorials are either in 2D or only use the `transform.position` such as this one.

Using the `transform.position` will work for most cases but will not allow the user to select easily as selecting the head or feet of a unit will not work in this instance. It also means I have to do an other script using raycasts for single click selections as it is almost impossible to get the single point of the `transform.position` with one click.

How can I do a proper rectangle selection for a 3D game? By looking at 3D RTS games I own, I noticed that they use a simplified hitbox (usually a cube or capsule).

# Answer
> 1 votes
This is a general overview of how to approach the problem. I haven't included any code, but hopefully it's enough to answer your question.

A good way to approach this may be to use `Physics.BoxCastAll()`. BoxCast is similar to Raycast but, as the name suggests, uses a box instead of a ray.

First, you will need some type of collider on your units that the BoxCast can detect. If you're just using the collider to detect mouse interaction, you can use a box collider with "Is Trigger" checked. For performance reasons, you should put these colliders on their own layer and use a layer mask with the box cast.

The tricky part would probably be converting the 2D box drawn by the mouse into a world-space 3D box. One way to do this may be to find each corner of the box in screen space, convert the corners to world space, then calculate the center and extents of the box based on these corners. I *think* that you could just use the camera's rotation for the box's rotation, but am not 100% certain as I haven't tried this before. **EDIT:** As noted by DMGregory in the comments, you will probably also need to account for the camera frustum, which makes things trickier and may require using multiple box casts, or instead calling `Physics.OverlapBox()` multiple times for different distances.

If you go with this setup, you can just use a regular raycast for regular single-click selection. That's also a lot simpler than the highly complex selection manager from your link.

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


title: Canvas not scaling to screen size

text:
# Question
Title: Canvas not scaling to screen size
So I have a very simple scene set up with just a camera, a game object called TestGrid with a grid script, and then a canvas. I have a TextMeshPro prefab that I instantiate to fill the 10 x 20 grid with cells.

If I build and run the game, I see all the cells on my screen. However, in the editor play view, I can only see as many grid cell as would fit on startup. Making the game view smaller or larger will scale the ones already there, but everything that didn't fit initially is "clipped" out. The "canvas" is in the bottom left corner of the "grid"

I'll share my code as well:

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

public class TestGrid : MonoBehaviour {
  private float _cellSize = 50.0f;

  [SerializeField]
  private float _width = 0.0f;

  [SerializeField]
  private float _height = 0.0f;

  [SerializeField] private TextMeshProUGUI labelPrefab;

  // Start is called before the first frame update
  private void Start() {
    if (labelPrefab == null) {
      Debug.LogError("You must set a label prefab.");
      return;
    }

    GameObject canvas = GameObject.Find("labelCanvas");
    if (canvas == null) {
      Debug.Log("Unable to find canvas");
      return;
    }

    // This is just a 2D array of ints.
    Grid grid = new Grid((int)_width, (int)_height);
    var canvasRect = canvas.GetComponent<RectTransform>().rect;
    _cellSize = Math.Min((canvasRect.width / _width), (canvasRect.height / _height));

    for (int x = 0; x < grid.Data.GetLength(0); ++x) {
      for (int y = 0; y < grid.Data.GetLength(1); ++y) {
        SpawnLabel(new Vector3(x, y, 0), canvas, grid.Data[x, y].ToString());

        // TODO: Replace this with LineRenderer
        Debug.DrawLine(GetWorldPosition(new Vector3(x, y)), GetWorldPosition(new Vector3(x, y + 1)), Color.white, 100f);
        Debug.DrawLine(GetWorldPosition(new Vector3(x, y)), GetWorldPosition(new Vector3(x + 1, y)), Color.white, 100f);
      }
      Debug.DrawLine(GetWorldPosition(new Vector3(0f, _height)), GetWorldPosition(new Vector3(_width, _height)), Color.white, 100f);
      Debug.DrawLine(GetWorldPosition(new Vector3(_width, 0f)), GetWorldPosition(new Vector3(_width, _height)), Color.white, 100f);
    }
  }

  void Update() {
    // NYI
  }

  private void SpawnLabel(Vector3 localPos, GameObject canvas, string text) {
    float x = localPos.x;
    float y = localPos.y;
    var world = GetWorldPosition(new Vector3(x, y, 0)) + new Vector3(_cellSize, _cellSize) * .5f;
    var label = Instantiate(labelPrefab,
      world,
      Quaternion.identity, canvas.transform);
    label.text = text;
    label.fontSize = 100;
    label.autoSizeTextContainer = true;
  }

  private Vector3 GetWorldPosition(Vector3 local) {
    return local * _cellSize;
  }

}

```

**Additional images of environment:**

I'm actually not too sure what is going on here, so here is everything I know:

* I'm parenting my TextMeshPro prefab transform to the canvas transform, so that it scales properly
* My Canvas Scalar is set to **reference resolution of 2560 x 1440**, with a **RPPU of 108**
* Canvas Scalar is also set to **Scale With Screen Size**
* Canvas Screen Space is set to **Overlay**

I've also read the following links with no luck: https://stackoverflow.com/questions/32347009/unity-canvas-does-not-fill-screen https://answers.unity.com/questions/943190/ui-panel-not-covering-whole-screen.html https://answers.unity.com/questions/1331722/ui-scaling-issues.html

**Expected Results:** No matter what the screen size is, I should see my full 10 x 20 grid of "cells" (in play view they're just 0's).

**Question:** If my canvas is supposed to scale with screen size, why is it that when I choose a cell size calculated from the canvas size, that it thinks the canvas is 2560 x 1440 when the screen size is clearly much smaller than that?

Do I need to calculate with a different value? Must I dynamically resize everything I draw within the canvas? What's going on here?

# Answer
It looks to me like your code is placing things in a grid that you've built in world space. The canvas scaler component doesn't help if your grid is in world space.

Instead of manually creating a grid, use the GridLayoutGroup component. This component lets you easily create a grid on a canvas.
> 2 votes

---
Tags: unity, 2d, grid, scale
---


# Question
Title: Damage-calculating formula for turn-based RPG with a twist: I have developed a formula, do you the experts think it will scale up successfully?
I’m developing a turn-based combat system for an RPG. It’s a little different to your standard RPG though. The idea being, the faster the player solves the problem they are presented with each time it's their turn to attack, the stronger their attack is. I have come up with a very simple formula for this and have gone through examples at different levels to test scalability and it seems OK.

I just wanted to show the experts here and see if anyone could spot any issues with this formula for scalability or anything else I haven’t thought of. I also did some research online but couldn’t see examples of a similar model, though I did find more typical examples of damage calculating formulas.

For the game I am making, the input for the damage done is based on 2 things: there will be 20 seconds to answer a question, so the time taken to answer it is one factor; and, the level of the player. All decimal answers to this formula are rounded up to determine the damage and if you go over the time you miss your attack. The formula looks like this:

*Damage = (20 - time taken) x level*

Level in this will be counted through decimal points. Here are some examples:

Level 1: we would input **1.1** into the formula

Level 5: **1.5**

Level 10: **2**

Level 13: **2.3**

Level 37: **4.7** ….etc.

**Examples**

If a player takes **8 seconds** to answer the question and is **level five**, the formula works like this:

*(20 - 8) x 1.5 = 18*

The character would inflict 18hp damage.

If they were **level 10** and answered in **12 seconds**:

*(20 - 12) x 2 = 16*

The character would inflict 12hp damage.

If the player were **level 29** and answered in **17 seconds**:

*(20 - 17) x 3.9 = 11.7 = 12*

The character would inflict 12hp damage.

What do you all think? Any feedback is very welcome. Thank you for reading.

# Answer
> 1 votes
I don't see anything explicitly wrong with it, as in the end, it all depends on you - how far are you willing to make adjustments (to the design). I would, however, from experience with scaling up the damage formula across 500 levels, recommend the following:

* Before you write a single line of code, do all computations in Excel/OpenOffice - you do not want to figure out scaling issues after half day of debugging - excel will allow you to see them within 10 minutes.
* have various tabs for various formulas (you will end up with many, which is fine - that's the fun part of experimenting)
* Any time you hit a limit relevant to your game (HP, level, whatever) - explicitly break the table, and put comments right below the row where it happens so you don't forget it once you start implementing it
* no player will figure out that your progression tree is hardcoded to the initial values. You can't beat the math, and the last thing you want is to introduce dozen conditions in code that will make it an undebuggable mess. Once the gameplay starts to change too much due to high values, just end the game there (assuming you adjusted experience progression in excel first).

Case in the point - Mass Effect 1. I just replayed it twice last week. They literally get away with simple linear scaling of experience points. Whether you are level 7 or 47, you still get level upgrade for same amount of activities done (even though the game makes it look like you need to get 10x more experience, but you don't really).

---
Tags: mathematics, rpg, turn-based
---


# Question
Title: How can I play an audio source while a key is being held down?
```
        if (Input.GetKey(KeyCode.A))
        {
            audioSource.Play();
        }

```

Except this only functions once as the key is held down. Same goes with GetKeyDown. Is there any way I can get this to loop as long as they key is being held down? (Is in Update)

# Answer
`Input.GetKeyDown` is true on the frame when the player started pressing the key and `Input.GetKeyUp` on the frame when it is released. So all you need to do is call audioSource.Play on GetKeyDown and then AudioSource.Stop on GetKeyUp:

```
if (Input.GetKeyDown(KeyCode.A)){
    audioSource.Play();
}
if (Input.GetKeyUp(KeyCode.A)){
    audioSource.Stop();
}

```

Note that Stop will reset the audio clip to the beginning. There are also cases where you just want to pause the audio clip and then later resume it later at the same point. In that case use Pause and UnPause instead of Stop and Play.
> 2 votes

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


# Question
Title: Convert integer to float while also dividing down the scale, without data loss
I'm working on a game, and my intent is to avoid use of floating point for unit positions. To that end, I'm using 32-bit integers for all positions, with a millimeter scale.

However, for rendering, I know the GPU expects everything to be float, so I need to convert from millimeter-scale integer to meter-scale float. Sounds simple, but I'd like to know the most efficient way to perform these two conversions at the same time without losing something along the way.

I know I can convert my 32-bit integer to a double and know that it will all fit, before dividing by 1000 to get meters and converting the result to a float:

```
int i = 1234567890;
double d = i / 1000.0;
f = (float)d;

```

But I wonder if that's taking more steps than is necessary. The only other option I can think of is to do something like:

```
int i = 1234567890;
float f = (i % 1000) / 1000.0f;
f += i / 1000;

```

But that requires multiple divides and more steps than using a double.

Is there perhaps another existing method of performing this sort of conversion? Or are these my only real options?

# Answer
I think you're making this too complicated. The trick to preserving precision in your floating point numbers is just to keep their magnitude small. No chaining through doubles or two-stage fractional/whole conversion required.

If you want millimetre accuracy, single-precision floats will keep that as long as your numbers are less than about 16 km.

(If your play space is even smaller than that, then you actually *lose* precision with your millimetre integer scheme, so you might as well stick with floats throughout)

"But my world is bigger than 16 km" — that's not a problem, because the immediate neighbourhood of your camera, where millimetre-sized errors might actually be visible, is not.

When you compute the matrices to send down the pipe to your GPU, all you need to do is form the translation component as a relative offset from the camera.

```
Vector3Float translation = (object.integerPosition - camera.integerPosition) / 1000f;

```

So as far as the GPU is concerned, your camera is always at (0, 0, 0) this way, giving you maximum precision in any direction you look. Objects a very long way from the camera can still suffer precision loss, but a 1 mm offset over a 16 km distance barely changes the direction of the vector at all — your rounding to the pixel grid of the screen is actually a much larger source of error than anything you'd get from floats in this scenario.

The other members of the object transformation matrices will already tend to be near the -1...1 range where floats have very high precision, so you don't have to do anything fancy with them.

This goes in general for other values too. If it's an absolute measure, like a position in the world or a time stamp, use integers so that you have the same precision no matter where/when you are. If it's a relative measure, like an offset/displacement, duration (like deltaTime), velocity, etc. then use a float. This gets you consistent relative precision, where the errors stay small in proportion to the quantity you're measuring.
> 24 votes

# Answer
In a comment I mentioned in passing that you could switch to representing 1024ths of meters instead of millimeters. That also helps with representability generally. Your code would look like this:

```
int i = 1234567890;
float f = ((float)i) / 1024.f;

```

You don't need to worry about representability at all here. The temporary float value will already be the best representation of `i` possible in a single precision float, and the divisor `1024.f` is not only a perfectly representable floating point number (feel free to write it with the wonky hexadecimal floating literal notation if you prefer) but will actually reduce to a trivial subtraction of the exponent of your floating point value when executed.

Of course you (and your compiler) will probably notice that a division isn't necessary at all at this point. The above code could we written with a similar multiplication (or even maybe some fancy hardware instructions):

```
int i = 1234567890;
float f = ((float)i) * 0x1p-10f;

```

(`0x1p-10f` is just a direct representation of the value `1.f / 1024.f`)
> 5 votes

# Answer
Since you mentioned GPU, I will assume you mean a modern one. In this case, a conversion within a shader per vertex is going to have a performance impact of a single drop falling into the ocean. You will be able to benchmark it, but not see it.

Out of curiosity, why do you think you need integers ? I ask, despite having written a fully-integer SW rasterizing pipeline, but that was on sub-100 MHz CPUs. It does make very little sense on current CPU+GPU combos, though.
> -1 votes

---
Tags: c, floating-point, precision
---