# Question
Title: disabling or enabling a public component
I need to be able to disable only a specific component of an object publicly. I got a public component but I cant find any ways on the internet on how to disable and enable that component. Here's the code:

```
    public Component script;
    void Start()
    {
    }
    void Awake()
    {
        if (sliderchanged.drop == 1)
        {
            script.enabled = false; //this is the error
        }
        if (sliderchanged.drop == 0)
        {

        }
    }
    // Update is called once per frame
    void Update()
    {

    }

```

# Answer
> 3 votes
**Solution**

Try replacing your `Component` type to a `MonoBehavior`.

Then `script.enabled = false` will work.

---

**Explanation**

The `Component` is the base class for anything that can be attached to a gameobject, it is very barebones, and **does not support enabling/disabling**.

The `MonoBehavior` class inherits all the functionality of `Component` but adds some extra features. For your purposes, what's important is that it supports enabling/disabling via scripts or the inspector.

---

**Resources**

Here's a more detailed SO answer which explains the differences between Component, Behavior and Monobehavior if you're interested.

---
Tags: unity, c#, gameobject, game-component
---


# Question
Title: How to design initial difficulty progression for a dungeon crawler without it feeling boring?
I'm at a stage where I'm trying to design an initial world or set of levels to help me think about and test progression in a dungeon crawler. For some reason this has really stopped me in my tracks. I know that I want my player's heros to get stronger, and I want the game to get more difficult so they can't over power anything. This really is the game loop anyways.

So what I tried to do to distill the progression design down is to literally focus on nothing but HP and Damage increase. How do I make this interesting if the player power and enemy power looks something like this:

1. Level 1 Hero has 100HP/10DMG, Level 1 Enemy has 50HP/10DMG
2. Level 2 Hero has 200HP/20DMG, Level 2 Enemy has 100HP/20DMG
3. Level 3 Hero has 300HP/30DMG, Level 3 Enemy has 150HP/30DMG

As you can see, the balance ratio between the two always stays at 2:1. The fight will take the same amount of time. It will look the same from HP bars losing life. Why would the player keep wanting to play or even care about leveling up if this is how the game goes? This isn't fun. It isn't interesting. But it is a linear balance curve of 2:1. Ok, I've designed that I guess.

So of course the next step is to make the player be stronger than the enemies for a bit after they level up. They want to feel strong, right? Well how long do I do this for? How long do I wait until I make the enemies stronger and challenging again so the player wants to level up to get stronger again? How do I know exactly how strong a hero will be at each level in my world?

That's one problem.

The second thing to consider is that simply giving stat increases is incredibly boring. So instead, I'd like to give the player's spells and abilities which effectively increase their HP or DMG. How often do I give them these? How do I keep it fun between levels? How do I know how strong a hero will be at each level in my world?

...

I think looking at it this way has taken the magic out of the game and design, but is there any other way? How do I get past this and is there common ways to look at this type of hero vs. enemy/level balance?

# Answer
> 3 votes
**Feeling stat increases**

My initial suggestion to help player's **feel** increase in raw stats is to let player's experience over-leveled mobs early. These OP mobs shouldn't block or occupy *mandatory* paths in your dungeon. If you let player's experience the power of high level monsters early, then in later levels, the player can rencounter the same mobs that gave them such difficulty previously, and will now be able to defeat them with relative ease and really **feel** their stat progression.

**Implications on difficulty balance**

Creating various levels of difficulty (through **optional** encounters) in a dungeon, will also help differently skilled players balance the game for themselves. A super skilled player might choose (and be able to) defeat level 5 mobs on the first level through superior knowledge and mechanics, while a new player might choose to only enter rooms blocked or occupied by lvl 1 mobs as they are still grokking the game's systems and timings.

**Resources**

Here's a related question which offers some topical game design resources to give you a base to jump off from.

# Answer
> 3 votes
A common approach to this is a lock-step approach.

1. Give the player more power
2. Give the player the opportunity to enjoy their power trip by using their newfound power on old opponents.
3. Introduce more challenging opponents which match the new power-level of the player, thus forcing the player to play serious again.
4. Repeat.

The result is that the gameplay will alternate between phases where the player feels challenged (by the introduction of a more powerful enemy), followed by a reward for overcoming the challenge (more power and a phase of curb-stomping what used to bother them).

This is why most dungeon crawlers with levelup systems are designed in a way that levelups happen in the middle of the dungeon crawl instead of between dungeons. The enemies stay the same, but the player gets more powerful. And new equipment is rarely found right before a boss fight. They are found either a couple rooms before the boss, or right after it a a reward for beating the boss.

Or let's take the example of a classic JRPG with an overworld with towns with equipment shops. When the player reaches a new overworld region, they will at first struggle against the new overworld enemies. That is until they reach a new town with the next equipment tier for sale. They will then buy that equipment and then keep exploring the same overworld region where they face the exact same opponents. But those opponents are now notably less challenging thanks to the recent powerup. That is until the player discovers the dungeon, where they then face enemies which measure up to their new equip.

# Answer
> 2 votes
HP and Damage increases for the player and enemies are just a tool that help you do some other things. Until you decide what other things you're trying to do, it's very hard to know what health and damage progression will give you good results. They can be used for:

## Planned Obsolescence

If you have items to pick up, or abilities to learn, you can use HP and Damage increases to make old items and abilities grow less useful over time. Maybe at level 5 the player learns to cast fireballs which do 10 damage in a circle; at level 15 when you give them the ability to make cones of fire that do 30 damage in a cone, then they'll have little use for the fireball even though it has better range and is easier to avoid hitting your teammates with.

## Grinding

If you give the player some control over how powerful they are, let them dwell in a lower-level area for a bit before moving on if they want to be a bit stronger, then the player can substitute patience for skill. But ideally the extra combat is more practice for them, which the less-skilled players probably need. It can be a bit difficult to correctly tune grinding mechanics like this to not be too bothersome though.

## That nice back and forth between being a bit too strong and having to really struggle

As you alluded to, it can feel good to be powerful, and it can feel rewarding to win a really tough fight. It's actually not terribly hard to design this sort of oscillation, just look at how much XP and loot the critical path of the game rewards (aside from any detours for grinding use), and you can get an estimate of the player's strength over time and tune your enemy stats accordingly. As for how much: in a purely linear game, you probably want to have a short power trip section immediately after the player levels up, and before giving them some great treasure have a serious battle or two. In an open game, I'd have there be difficult fights at objectives, and then have the player cross back through areas that used to be hard to get from one objective to the next.

# Answer
> -1 votes
You can have stronger characters and more powerful items be more attractive to monsters, drawing them in larger groups

---
Tags: game-design, balance
---


# Question
Title: Need help with fixing Optimized Raycasting / Line of Sight algorithm
I'm trying to implement collision detection with raycasting for my 2D javascript game. The game uses equally-sized tiles as its level structure so to optimize collision detecton I'm trying to use a LOS algorithm very similar to the one at the bottom of this this article.

However, I've noticed that at certain angles, tiles that should be detected are not. I'm also noticing an overall "L" shape pattern where tiles that are beyond the ray's endpoint are being detected when they don't need to be. I don't think these are intended behaviors of the algorithm but I can't quite figure out what I could be doing wrong.

I've assembled a small jsfiddle here that includes the most relevant code and an additional visualization. You can click anywhere on the canvas to set a new ray origin.

Would appreciate any help. Thanks.

```
const GRID_HEIGHT = 10
const GRID_WIDTH = 10
const CELLSIZE = 32
const OUTLINE_COLOUR = 'green';
const FILL_COLOUR = 'red'
const RAY_COLOUR = 'blue';
const canvas = document.getElementById('demo');
const ctx = canvas.getContext('2d');
var mouseVector = new Vector2D([96, 0], [1, 0]);
canvas.height = GRID_HEIGHT * CELLSIZE;
canvas.width = GRID_WIDTH * CELLSIZE
canvas.addEventListener("mousemove", updateMouseVector);
canvas.addEventListener("click", setMouseVectorOrigin);

function Vector2D(point1, point2) {
  if (point2 != undefined) {
    this.p1 = point1;
    this.p2 = point2;
  } else {
    this.p1 = [0, 0];
    this.p2 = point1;
  };
};

function drawCellOutline(x, y) {
  ctx.fillStyle = OUTLINE_COLOUR;
  ctx.strokeRect(x, y, CELLSIZE, CELLSIZE);
};

function fillCell(x, y) {
  ctx.fillStyle = FILL_COLOUR;
  ctx.fillRect(x, y, CELLSIZE, CELLSIZE);
};

function drawGrid() {
  for (let y = 0; y < GRID_HEIGHT; y++) {
    for (let x = 0; x < GRID_WIDTH; x++) {
      drawCellOutline(x * CELLSIZE, y * CELLSIZE);
    };
  };
};

function clearCanvas() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
};

function getMouseCoordinates(e) {
  let mouseX, mouseY;

  if (e.offsetX) {
    mouseX = e.offsetX;
    mouseY = e.offsetY;
  } else if (e.layerX) {
    mouseX = e.layerX;
    mouseY = e.layerY;
  }
  return [mouseX, mouseY]
}

function updateMouseVector(e) {
  let mousePos = getMouseCoordinates(e);
  mouseVector.p2[0] = mousePos[0];
  mouseVector.p2[1] = mousePos[1];
}

function setMouseVectorOrigin(e) {
  let mousePos = getMouseCoordinates(e);
  mouseVector.p1[0] = mousePos[0];
  mouseVector.p1[1] = mousePos[1];
};

function drawRay(rayVector) {
  ctx.fillStyle = RAY_COLOUR;
  ctx.beginPath();
  ctx.moveTo(rayVector.p1[0], rayVector.p1[1]);
  ctx.lineTo(rayVector.p2[0], rayVector.p2[1]);
  ctx.stroke();
}

function raycastCollision(rayVector) {
  let dx = Math.ceil(Math.abs(rayVector.p2[0] - rayVector.p1[0]) / CELLSIZE);
  let dy = Math.ceil(Math.abs(rayVector.p2[1] - rayVector.p1[1]) / CELLSIZE);
  let x_inc = (rayVector.p2[0] > rayVector.p1[0]) ? 1 : -1;
  let y_inc = (rayVector.p2[1] > rayVector.p1[1]) ? 1 : -1;
  x_inc *= CELLSIZE;
  y_inc *= CELLSIZE;

  // "error" is The difference between the next horizontal cell vs the next vertical cell.
  // if error is positive then horizontal is closer, otherwise vertical.
  let error = dx - dy;

  let pos = [rayVector.p1[0], rayVector.p1[1]]; // Create copy because we're going to be mutating it.

  let n = 1 + dx + dy; // 1 represents thw tile we're starting from.
  for (; n > 0; --n) {

    fillCell(Math.floor(pos[0] / CELLSIZE) * 32, Math.floor(pos[1] / CELLSIZE) * 32);

    if (error > 0) {
      pos[0] += x_inc;
      error -= dy;
    } else {
      pos[1] += y_inc;
      error += dx;
    };

  };
};

function main() {
  clearCanvas();
  drawGrid();
  raycastCollision(mouseVector);
  drawRay(mouseVector);
  requestAnimationFrame(main);
};

requestAnimationFrame(main);
```

```
<canvas id="demo"></canvas>
```

# Answer
```
const GRID_HEIGHT = 10
const GRID_WIDTH = 10
const CELLSIZE = 32
const OUTLINE_COLOUR = 'green';
const FILL_COLOUR = 'red'
const RAY_COLOUR = 'blue';
const X = 0;
const Y = 1;
const canvas = document.getElementById('demo');
const ctx = canvas.getContext('2d');
var mouseVector = new Vector2D([0, 0], [0, 0]);
canvas.height = GRID_HEIGHT * CELLSIZE;
canvas.width = GRID_WIDTH * CELLSIZE
canvas.addEventListener("mousemove", updateMouseVector);
canvas.addEventListener("click", setMouseVectorOrigin);

function Vector2D(point1, point2)
{
  if (point2 != undefined)
  {
    this.p1 = point1;
    this.p2 = point2;
  }
  else
  {
    this.p1 = [0, 0];
    this.p2 = point1;
  };
};

function drawCellOutline(cx, cy)
{
  ctx.fillStyle = OUTLINE_COLOUR;
  ctx.strokeRect(cx * CELLSIZE, cy * CELLSIZE, CELLSIZE, CELLSIZE);
};

function fillCell(cx, cy)
{
  ctx.fillStyle = FILL_COLOUR;
  ctx.fillRect(Math.floor(cx) * CELLSIZE, Math.floor(cy) * CELLSIZE, CELLSIZE, CELLSIZE);
};

function drawGrid()
{
  for (let y = 0; y < GRID_HEIGHT; y++)
  {
    for (let x = 0; x < GRID_WIDTH; x++)
    {
      drawCellOutline(x, y);
    };
  };
};

function clearCanvas()
{
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
};

function getMouseCoordinates(e)
{
  let mouseX, mouseY;

  if (e.offsetX) {
    mouseX = e.offsetX;
    mouseY = e.offsetY;
  } else if (e.layerX) {
    mouseX = e.layerX;
    mouseY = e.layerY;
  }
  return [mouseX, mouseY]
}

function updateMouseVector(e)
{
  let mousePos = getMouseCoordinates(e);
  mouseVector.p2[0] = mousePos[0]// + 0.5;
  mouseVector.p2[1] = mousePos[1]// + 0.5;
}

function setMouseVectorOrigin(e)
{
  let mousePos = getMouseCoordinates(e);
  mouseVector.p1[0] = mousePos[0]// + 0.5;
  mouseVector.p1[1] = mousePos[1]// + 0.5;
};

function drawRay(rayVector)
{
  ctx.fillStyle = RAY_COLOUR;
  ctx.beginPath();
  ctx.moveTo(rayVector.p1[0], rayVector.p1[1]);
  ctx.lineTo(rayVector.p2[0], rayVector.p2[1]);
  ctx.stroke();
}

function rayMarch(rayVector)
{
      let cellVector = {p1: [rayVector.p1[X] / CELLSIZE, rayVector.p1[Y] / CELLSIZE],
                                    p2: [rayVector.p2[X] / CELLSIZE, rayVector.p2[Y] / CELLSIZE]};

    let x0 = cellVector.p1[X];
    let x1 = cellVector.p2[X];
    let y0 = cellVector.p1[Y];
    let y1 = cellVector.p2[Y];

    let dx = x1 - x0;
    let dy = y1 - y0;
    dx = Math.abs(dx);
    dy = Math.abs(dy);
    //adjust dx / dy to avoid div-by-zero
    let dtDx = 1.0 / dx;
    let dtDy = 1.0 / dy;

    let xInc = 0//dx / steps;
    let yInc = 0//dy / steps;
    let txNext = 0;
    let tyNext = 0;

    let x = Math.floor(x0);
    let y = Math.floor(y0);

    let n = 1;

    if (dx == 0)
    {
      xInc = 0;
      txNext = dtDx; // infinity
    }
    else if (x1 > x0)
    {
      xInc = 1;
      n += Math.floor(x1) - x;
      txNext = (Math.floor(x0) + 1 - x0) * dtDx;
    }
    else
    {
      xInc = -1;
      n += x - Math.floor(x1);
      txNext = (x0 - Math.floor(x0)) * dtDx;
    }

    if (dy == 0)
    {
      yInc = 0;
      tyNext = dtDy; // infinity
    }
    else if (y1 > y0)
    {
      yInc = 1;
      n += Math.floor(y1) - y;
      tyNext = (Math.floor(y0) + 1 - y0) * dtDy;
    }
    else
    {
      yInc = -1;
      n += y - Math.floor(y1);
      tyNext = (y0 - Math.floor(y0)) * dtDy;
    }

    let t = 0;
    for (; n > 0; --n)
    {
        fillCell(x, y);

        if (tyNext < txNext)
        {
            y += yInc;
            t = tyNext
            tyNext += dtDy;
        }
        else
        {
            x += xInc;
            t = txNext;
            txNext += dtDx;
        }
    }
};

function main()
{
  clearCanvas();
  drawGrid();
  rayMarch(mouseVector);
  drawRay(mouseVector);
  requestAnimationFrame(main);
};

requestAnimationFrame(main);
```

```
<canvas id="demo"></canvas>
```

See also working fiddle. For your future reference:

* This algorithm is called DDA (digital differential analyser). The canonical implementation requires cell co-ordinates to be a floating point value with each increment of 1 denoting the width of a full cell. Thus in `x`, the start of the first cell's edge is 0, the middle of the second cell is 1.5, 2/3s through the third cell is 2.67, etc. **The first thing you needed to do** was to divide your `mouseVector` values by `CELLSIZE` and work only in this form, never in `CELLSIZE`d form.
* if you are learning from example code as in this case, do not change variable names within the function(s). Rather copy out your values from your custom vector into `x0, y0, x1, y1` as per the original as this helps you avoid at least one class of mistakes / errors when transcribing the algorithm, i.e. it is easier to transcribe this way.
* use canonical / industry standard naming e.g. `raycastCollision` -\> `rayMarch`.
* simplify your naming: `drawCellOutline` -\> `outlineCell` (matches your `fillCell`)
* do not repeat yourself in function call parameters which you can include within the function itself e.g. `fillCell(x * CELLSIZE, y * CELLSIZE)` -\> `fillCell(x, y)`; since they are grid-aligned they must all be of `CELLSIZE`, not so?
* do not expect to use the advanced / optimised version of an algorithm until you have studied and understood the basic version.
* in my opinion, always use Allman indentation, as it is easier to understand your blocks visually.
> 1 votes

# Answer
The algorithm at the bottom of the article is for integer inputs (the components of rayVector are always integral multiples CELLSIZE ). As you are using floating-point numbers you may probably get an error result
> 0 votes

---
Tags: javascript, algorithm, graphics, raycasting, line-of-sight
---


title: How to browse packages in Unity?

text:
# Question
Title: How to browse packages in Unity?
How to browse packages in Unity?

I have the `Version: 2020.1.17f1.4949 Personal`.

I want to install the Burst and Collection packages. I follow this guide. I open my **Package Manager** and try to search for `collections` and `burst`, but nothing pops up. Also, I see literally 0 packages and I can not understand why is it so hard to browse packages in Unity. I spent 2 hours, but was not able to find a single Unity package. That is very frustrating.

Could someone help me to figure out how the **Pacakge Manager** works, how could I browse packages?

It seems I was able to install the collections package by following this guide. And I used the `com.unity.collections` as an URL, not as a name.

The trick was to be patient, because after the package is selected it took me ~2 minutes before the package actually started installing.

Now I am left to figure out how install the burst package.

# Answer
> 3 votes
##### explanation

Packages starting in Unity 2020 are hidden by default in the Package Manager if they're in preview and are not close to their full release date. Now you have to either edit your project manifest file manually, or you can add the package from a git URL.

---

##### resources

* This guide will explains things in more detail and with images.
* Explanation of why Unity chose to start doing things this way.

---
Tags: unity
---


# Question
Title: Issues using Physics2D.Linecast for Movement Collision
It's quite possible I'm missing something obvious (I'm still rather new to this) despite checking the documentation, but I'm at my wit's end with this issue.

I'm attempting to add simple linecast collisions to my 2D movement system that checks if there's a wall on the relevant layer to disallow movement, but I cannot get the distance parameter to function properly. It's responding as if my distance is set to the default MathF.Infinity, despite me feeding a float variable into it.

Furthermore, unity keeps giving me this error after I moved my layermask declaration into the Start function: "The name 'mask' does not exist in the current context." I'm unsure why this is happening.

Here's the relevant code:

```
float distance = 1f;

void Start()
{
    LayerMask mask = LayerMask.GetMask("BlockingLayer");

}
void FixedUpdate()
{
    // Move up IF !isMoving and No collision detected.
    if (Input.GetKey(KeyCode.W) && !isMoving && Physics2D.Linecast(transform.position, Vector2.up, mask, distance))
            StartCoroutine(MovePlayer(Vector2.up));
}

```

Alright, after working with the helpful people responding, I've updated my code. Unfortunately, my issue seems to have inverted. Rather than detecting collision always, collision does not seem to be detected ever. Here's the new code (Edited to reflect small change):

```
    float maxDistance = 2f;
RaycastHit2D hitU;

void FixedUpdate()
{
     hitU = Physics2D.Raycast(transform.position, Vector2.up, LayerMask.GetMask("BlockingLayer"));
    // Move up IF !isMoving and No collision detected.
    if ((hitU.collider != null && (hitU.distance < maxDistance)))
    {
        if (Input.GetKey(KeyCode.W) && !isMoving)
        {
            StartCoroutine(MovePlayer(Vector2.up));
            Debug.DrawRay(transform.position, Vector2.up, Color.red);
        }

    }

```

# Answer
##### Distance param

I think you're confusing the parameters for `Physics2D.Raycast` with `Physics2D.LineCast`. The "distance" parameter your passing into `Physics2D.LineCast` is actually a "minDepth" value. Which according to Unity Docs:

> Only include objects with a Z coordinate (depth) greater than or equal to this value.

Which means it actually has nothing to do with distance in 2D space, but rather rather operates on the z-axis.

##### Solution

I would employ `Physics2D.Raycast` instead. The tricky "gotcha" with this method (at least in 3D), is that the distance param is actually just used by the Unity engine to optimize the raycasting algorithm so unity doesn't do more intersection tests than it has to. It isn't a guarantee for the precise max distance that the raycast hits will return.

You'll have to perform these checks yourself to be sure:

```
var hit = Physics2D.Raycast(transform.position, Vector2.up);

//if there was a hit, and distance was less than maxdist...
if ((hit.collider != null && (hit.distance < maxDistance))
{
   //do....
}

```

---

##### "The name 'mask' does not exist in the current context."

This is happening because your `mask` variable goes out of scope at the end of the your `Start()` method. You have to declare your `mask` variable as a member variable, so it's lifetime matches the lifetime of your script.

Try this instead:

LayerMask mask;

void Start()
{
    mask = LayerMask.GetMask("BlockingLayer");
}
```

> 0 votes

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


# Question
Title: How to play videos in Gamemaker Studio 2?
I made a little cutscene in Adobe Animate. I was wondering what would be the best way to have it triggered in game-maker studio 2.

The Video is .mp4 but I could convert it as I have the .fla file saved as well. I wanna figure the how to play a cutscene in game-maker studio 2.

# Answer
> 1 votes
Yes, you can play videos through GameMaker Studio 2, but you'll have to open and play the file yourself through extensions or DLLs.

Whilst there were built-in functions to open video files in previous GM versions, these have been marked as Obsolete Splash Functions in GMS1 and don't even appear in GMS2's Obsolete Functions list, meaning that they have been likely definitely removed.

---

As stated in the *3rd Party Support* section of GMS2's Obsolete Functions:

> GameMaker Studio 2 moves a lot of built-in functionality from previous versions into extensions...

This is a reasonable decision by YoYo Games to keep the GMS2 codebase clean and move all platform-dependent, OS-specific source code outside and consider it an extension.

Opening a video file is a different operation on different OSs. On Windows or macOS you need a library (DLL or Dylib respectively) to tell the OS you want to open a given video file with a particular codec; HTML5 may not let you do such a thing; mobile platforms have a different way of dealing with flow control.

You can either browse the GameMaker Marketplace and look for the right extension for you, or create an extension yourself if you feel like coding a little DLL specifically for your project.

---
Tags: animation, video, cutscene, game-maker-studio-2
---


# Question
Title: Why my Submit button not triggered once?
I have some issues for match the string and the InputField.text it's triggering multiple times after `Active` or `dead Active Gameobject` when press Submit button(in this case is "Cek Jawaban").

this my script

```
public void Answer(int index)
    {
        inputPanel.SetActive(true);

        inputField.text = "";

        inputPanel.transform.Find("KunciBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            if (inputField.text != "")
            {
                if (inputField.text == jawaban[index])
                {
                    Debug.Log("Right");
                }
                else
                {
                    Debug.Log("Wrong");

                }

                inputPanel.SetActive(false);
            }
            else
            {
                Debug.Log("jangan kosong");
            }
        });
    }

```

as you can see on the console the first that trigger once but after second time its trigger twice.

# Answer
> 3 votes
There are 2 ways of giving functionality to the button: 1) via code; 2) using 'OnClick' feature within 'button' component in unity 'inspector' panel;

Here is the catch:

**You are supposed to use ONE of these methods, NOT both of them.**

Because button will fire **all** tasks assigned to it.

So, either assign functionality via code, - it should look something like this:

```
inputPanel.transform.Find("KunciBtn").GetComponent<Button>().onClick.AddListener(() => fireThisNiceFunction());

```

Or just use 'button' component in unity menu and assign your functionality that way. That's it!

If you choose to do it via code, - make sure that you assign listener only once! In your example you are actually assigning new listener every time button is clicked, so those listeners pile on top of each other.

p.s. Also you can wipe all button listeners clean by using

```
myNiceButton.GetComponent<Button>().onClick.RemoveAllListeners();

```

---
Tags: unity
---


title: filter camera output by mesh

text:
# Question
Title: filter camera output by mesh
(skip to edit for the actual problem)

I have a simple plane mesh generated via script (has arbitrary shape).

I want the shader to discard (set to black) all pixels that aren't passing through that mesh. Currently, the mesh is in MeshFilter but isn't rendered through Mesh Renderer, as I don't want the mesh itself to be visible - it's only purpose is to filter the camera output.

I could also send the mesh data to shader, but since it has arbitrary shape (and arbitrary number of vertices), I don't know how I can check if the pixel is running through that mesh or not. The mesh is made of few vertices (201) generated each `fixedUpdate` (currently, all the mesh vertices are changed in `fixedUpdate` (vertices set to empty array with fixed length, then filled). I didn't see low performance yet, so I didn't want to dive into optimizations just yet). All the vertices have same `y` axis (I don't care about `y` axis at all, so a vertical check can be omitted) and they don't overlap (I'm using simple raycasting to get visible area, something similar to this, but in 3D and the result is a plane-like mesh).

What I want is to show movable objects (like enemies) only when they're under that mesh (camera is from top, aiming down), else just show the map itself (which doesn't change), slightly darkened.

I found this page for creating a simple screen shader in Unity (I couldn't find how to apply shader to camera from Unity docs at all), but it didn't work (no errors, it just didn't show the screen with the black and white effect with intensity set to 1 (which should be fully black and white if I understand it correctly) or 0).

#### Edit:

As DMGregory pointed out, this is a job for stencil buffer.

What I thought of now is to check if the pixel is inside one of the triangles (not sure how fast that is), using for example this code from this question, then write that result to stencil buffer and filter out all points that aren't in that triangle. Then merge the result with the map 'background'.

I know how to merge them (at least I think so) and how to filter out pixels based on their stencil buffer value (direct example in docs).

# Answer
> 0 votes
What I was looking for all along is called fog of war. @DMGregory told me that, after a long discussion about the effects I was talking about.

---
Tags: unity, shaders, fragment-shader, mesh
---


title: How to disable emission at runtime

text:
# Question
Title: How to disable emission at runtime
I'm changing shader at runtime.

I don't know why, when i "load" Standard shader, Emission is 'flagged' on .

So I'm asking you: how can I disable emission ?

Getting material, I can change emission color with this code, but i want to disable emission at all.

```
Material mymat = GetComponent<Renderer>().material;
         mymat.SetColor("_EmissionColor", Color.red);

```

Thanks

# Answer
> 2 votes
A simple solution as suggested from DMGregory is setting black color as the emission color:

```
Material mymat = GetComponent<Renderer>().material;
mymat.SetColor("_EmissionColor", Color.black);

```

---
Tags: unity
---


# Question
Title: A concise set of equation of physics that handles basic 2d physics for acceleration?
I am making an Asteroids clone and I want to implement proper physics for the objects. What equations would I use to calculate the acceleration? For example, I have a ship, and it might have properties like mass and other stuff (whatever might be relevant, I don't know). If I assume thrust of 10 units, how would the ship accelerate over time in the given direction? There is no friction since the game is set in space, so I don't need to worry about deceleration.

When I Google formula for acceleration, it says `final velocity - starting velocity / elapsed time` but that's for calculating how much an already accelerating object is accelerating by isn't it? Or am I confused? Thanks for helping.

# Answer
I found that newtons second law of motion was what I was looking for.

`Force = Mass * Acceleration`.

Rearranging this gives us the acceleration.

`Acceleration = Force / Mass`

Then I am adding this amount to my objects velocity vector every frame.
> 1 votes

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


# Question
Title: Procedural Dungeon Generation with set room sizes and no hallways
I am working on a generator for a Dungeon game. Basically, I have different types of rooms, and different shapes of rooms. The different types contain a list of allowed shapes, and each shape contains possible door locations. I have a set box size (4x4), and I want to generate rooms following that size with randomized types, shapes, and doors. I've been doing research for a few days about all the dungeon/house generators I can find but none of them quite fit the bill. They either use corridors, rely on randomized room sizes, or some other quirk. Any ideas about how to go about this would be greatly appreciated. I've attached an example I made that shows about what I'm looking to create.

The requirements are as follows:

* The room shapes are predetermined
* The possible door placements for each room are predetermined
* The full dungeon shape is predetermined, and is always a box (4x4, 8x8, etc)
* There are no big hallways, only doors leading straight to the next room
* There should always be at least 2 big shapes

The closest algorithm that I've found would be a binary space partition, but I'm unsure of how to implement that with predetermined room shapes, all the implementations I've seen randomly select points to divide at with hallways, which wouldn't fit the bill.

Any suggestions are greatly appreciated!

# Answer
> 3 votes
While 1 unit seems to be common denominator for all sizes, the rooms are apparently made from bigger (5x5) blocks, fitting to their own grid. You could start with a bigger grid to lay out the rooms, then migrate the data into a smaller grid to add the doors.

Room arrangement can be brute-forced, just keep trying to fit a room repeatedly into random position and orientation, checking that it is in bounds and is not colliding with any other rooms. To minimize the chance of getting stuck, order the pieces by size, starting with biggest first. But in case if the algorithm gets stuck, just start from scratch, because this kind of generation is pretty cheap.

Once the rooms are in place, transform them into a finer grid, with walls on the outer perimeter. And the doors, of course.

Ensuring that all the rooms are connected may be tricky. You'll have to do a flood-fill from a random starting room and see if it visits all the other rooms. (This can be done on the room arrangement stage, before the walls.) If the answer is negative, restart the process.

---
Tags: procedural-generation
---


# Question
Title: In a chess simulator, how to efficiently determine checkmate?
I'm working on a small C++ chess simulator game for the first time, and I have a bit of a programming dilemma. I have searched for similar questions on this site and StackOverflow, but can't find a consensus on what to do here, so hopefully this is an appropriate question for this site.

I'm currently working on implementing **check,** through a function that starts at the king's position and checks all knight moves, verticals, horizontals, and diagonals for threatening pieces. If it finds a threatening piece that isn't blocked by another piece, then the king is considered to be in check and the player must make their next move in a way that gets them out of check. That seems to be the most efficient solution for determining check from the chess-related posts I've seen.

However, I'm stuck on **how to efficiently implement checkmate.** The only logical way I can think of is that once the check flag has been raised, run the check function on *every legal follow-up move* to see if it results in non-check, and if none of them do, it is checkmate.

Or, to express this in C++ pseudocode:

```
bool checkForCheckmate() {
  for (allLegalMoves)
  {
    doMoveTemporarily();
    if (!inCheck) {
      return false; // The player can get out of check, so it's not checkmate.
    }
  }
  return true; // If we got here, none of the player's legal moves can get them out of check, so it's checkmate.
}

```

While it makes sense to me and is logical, that seems extremely inefficient, and this is supposed to be a fairly simple and lightweight application. However, this seems to be the approach suggested by most sources when I look up "how to implement checkmate in a chess game."

**Is there another, potentially more efficient chess algorithm to check if a given arbitrary board arrangement is a checkmate?**

# Answer
A move which results in the own king being in check is already an illegal move. So `allLegalMoves` would already excludes any moves which end up with the own king in check by definition. If fact the FIDE Laws of Chess section 1.2 define checkmate as:

> The objective of each player is to place the opponent’s king ‘under attack’ in such a way that the opponent has no legal move. The player who achieves this goal is said to have ‘checkmated’ the opponent’s king and to have won the game. Leaving one’s own king under attack, exposing one’s own king to attack and also ’capturing’ the opponent’s king are not allowed.

That means the checkmate can be defined as `ownKingIsInCheck && allLegalMoves.size() == 0`. (By the way, this can be easily combined with checking for stalemate: `allLegalMoves.size() == 0` *without* the king being in check)

OK, but doesn't that just move the problem from the mate-check routine to the move enumeration routine instead of solving it? Well, you need to move it there anyway. When you determine all the legal moves, you have to exclude those moves which put the own king in check, regardless of whether or not the king is already in check.

So if you feel the need to optimize (do you, though?), then you need to optimize your check-checking routine. One possible approach can be to cache the squares threatened by each piece (this data can also be useful for your rating function, by the way). Keep in mind that when a piece moves, then any pieces which threatened its old square might now threaten new squares. So their threat area needs to be recalculated. (see Pin and Discovered Check for two test-cases your routine needs to be able to cover)
> 5 votes

---
Tags: c++, efficiency, chess
---


# Question
Title: Calculating stereo sound levels from 3d sound source?
When a sound is emitted in a (first person) game world at some source position relative to the player - based on its distance away we can calculate the factor to multiply the amplitude of the wave that should be sent to the speakers from the inverse of the distance (in a unit of some appropriate "origin" base distance) - fine.

What I am not clear about is how to generate 2 channel stereo left/right sound.

(A) Let's say when the source is directly in front of the listener in the game world (and at the base distance away) we play the sound wave at the original recording amplitude in both speakers. Let's denote this by `(L,R) = (1.0, 1.0)`.

(B) Now what if instead the sound source is directly to the right of the listener (and again base distance away). Clearly we play the sound louder in the right speaker than in the left one, right? But how much louder? Should the wave in the right speaker be louder than the wave in the right speaker in situation (A) ? What factor should we multiply the wave by in the left and right speaker? ie What should `(L,R)` be now?

(C) Now what if the source is at a 45 degree angle forward and off to the right of the listener ? What should `(L, R)` be in this situation?

How do you calculate `(L,R)` in general as a function of the relative source position and listener orientation?

# Answer
I think that finding parallels in real life can be helpful in finding the answer. Basically, there are two main factors to determine how loudly a sound is heard by an ear:

1. The position of the ear relative to the sound
2. The rotation of the ear relative to the sound (I.E. the shape of the ear and how sound bounces within it).

The latter might be too complex for us to figure out, but the former should be simple enough. If we know how to calculate volume for a specific point in space (I.E. (x1, y1, z1), and we know the ears are a bit apart (let's call this offset dX & dZ from the center of the head), so all we have to do is calculate the volume for each ear.

So, in general, if we have a function that we give a position to and it gives us the volume of sound in that position, we simply run that function on (x1 + dX, y1, z1 + dZ) and (x1 - dx, y1, z1 - dZ), and set the returning values as the volume levels for L and R respectively.

I hope that answers your question, or at least gives you a good starting point.
> -1 votes

---
Tags: audio
---


# Question
Title: Turn-based grid movement - each click of the clock you want to move the player
I am working one the movement for a tactical turn-based pygame. I'm stumped as to how to get a selected object to move one tile at a time up to it's max movement to the mouse's pos. Right now this is what I have. I'm not sure how to proceed.

```
def move_toward(self, new_location):
def do_calculations():
# ... code ...
return dx, dy
# ----
# you have the current x,y for the player.
# each click of the clock you want to move the player
# closer to the end location.
delta = .01 # or whatever
# get <delta> amount closer to the end corrds. <-- do this each tick of the clock.
new_x, new_y = do_calculations()
self.move(dx=new_x, dy=new_y)

```

Sprites.py

```
import pygame as pg
from settings import *

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y

    def move(self, dx=0, dy=0):
        if not self.collide_with_walls(dx, dy):
            self.x = dx
            self.y = dy
            self.rect = self.rect.move(dx * TILESIZE, dy * TILESIZE)

```

main.py

```
    def events(self):
    # catch all events here
    for event in pg.event.get():
        if event.type == pg.QUIT:
            self.quit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                self.quit()
        if event.type == pg.MOUSEBUTTONDOWN:
            x = pg.mouse.get_pos()[0] // TILESIZE
            y = pg.mouse.get_pos()[1] // TILESIZE
            print(x, y)

            self.player.move(dx=x, dy=y)

```

# Answer
> 1 votes
When developing a turn-based game, then it can be useful to design the basic architecture of the game in form of a finite state machine.

That means that your game can be in one of a number of states. Depending on the state the game is currently in, it looks and behaves differently.

* First, your game is in the "pick unit" state. In this state, the game waits for player clicks and when such a click happens on a unit they control, that unit becomes selected and the game changes into the "pick destination" state.
* In the "pick destination" state, the game still waits for player clicks, but they now do something different: When the square the player clicked is a valid movement destination for the selected unit, then the game switches to the "execute move" state.
* The "execute move" state is purely automatic without player input. The unit slowly moves from one square to the next until it reached the destination. Then the game progresses to the next state automatically.

Optionally, you might want to add some additional state transitions. For example, a transition from "pick destination" back to "pick unit" when the player signals that they changed their mind and would like to move a different unit.

OK, but how do you implement this?

One good way to do that is to implement each state as a separate class which all inherit from the same base class. The methods defined by that state base class would be methods for any kinds of situations where states would behave differently. Examples would be "handle\_click" or "tick\_update".

The regular functions in your game which handle such events would then check the state machine for the currently active state object and call the respective method in that state object so it can do whatever it wants. That way you have all the functionality which is specific to each state in one place.

That makes it easy to avoid bugs where a functionality which is supposed to only be active in one state is active in a different state. You will also notice that it will become very easy to add additional states to the game. For example, the state of being in some form of menu, waiting for the opponent to make a move, visualizing the move of the opponent, displaying the "You Win" / "You Lose" banner or even watching a cutscene. All you need to do for each of those things is to create yet another State class and to write the code which causes the transition to that state.

---
Tags: game-design, movement, tilemap, python, pygame
---


# Question
Title: Is there any way I could replace the return type to the struct inheriting the interface, while still implementing the interface?
I am currently working on my own game framework for C#, as part of a larger project of mine.
I am trying to implement a Vector2 struct in a way where external libraries can extend it to fit their own needs, so I am using an interface. The interface looks similar to this:

```
public interface IVector2
{
   public double X { get; set; }
   public double Y { get; set; }
   public double Length { get; }

   //Other things here

   public IVector2 DistanceFrom(IVector2 from);

   //Other things here
}

```

The problem with this is that when I implement this into a struct, it keeps the IVector2 return on `DistanceFrom`, instead of replacing it with the struct that it is now in. This means that to use those methods, either all vectors have to be stored as their interface, or I have to cast. I don't want to do either.
**Is there any way I could replace the return type to the struct inheriting the interface, while still implementing the interface?**
I know using a class would solve this problem, but I don't want to use a class for something so common as a vector because of memory concerns. The game using my library could use *thousands* of vectors, and that could build up really quickly.

# Answer
> 0 votes
I have discovered a way to do this. You have to require a generic to be passed (`IVector2<T>`), then assume that the generic is the type. You can then pass the generic via methods, and everything will work.

# Answer
> 1 votes
If you want libraries to be able to extend the structure by adding methods, without altering its storage, then you can do that via extension methods:

```
public static class VectorExtensions {
    public static Vector2 GetClockwisePerpendicular(this Vector2 v) {
        return new Vector2(v.y, -v.x);
    }
}

```

This will be available to code in that assembly as though it were a member of the type itself:

```
var up = new Vector2(0, 1);
var right = up.GetClockwisePerpendicular();

```

I'd recommend this approach over the interface route you're going now.

The main reason to use the interface would be if you want libraries to be able to change the storage of the `Vector2`, like adding new member variables, eg. a coordinate space or memoized length or unit direction.

The trouble with this is that now any method that accepts a `Vector2` has to be able to handle many different types with different storage sizes and layouts (dynamic polymorphism). This can't be done with raw value-type structs, so your struct gets "boxed" into a reference type object. That boxing entails a heap allocation for the garbage collector to track and reclaim, and extra indirection when manipulating the struct — costs you can most often avoid when working with data directly on the stack using a concrete struct type (ie. not an interface).

It's not a lot, so don't panic and remove interfaces everywhere! They're well worth their small overhead for many situations. But for something like a vector type that you're going to be using *a lot*, all this boxing and unboxing can add substantial overhead into your hot code paths.

For this reason, I would recommend not using an interface for your basic vector building blocks.

---
Tags: c#
---


# Question
Title: How to trigger onclick for Unity Selectable by script?
As title, I know Button can be triggered onclick by `button.onClick.Invoke();`

But how to simulate onclick event of Selectable?

Thanks for the help.

# Answer
> 3 votes
As you know:

```
button.onClick.Invoke();

```

Acts like the user has clicked the button, invoking callbacks, but there's no visual effect on the button itself.

Do you also want the Selectable to be highlighted as if you'd moused-over it and clicked on it? I.e. a "simulated" click?

If so, the following code works for at least Buttons:

```
public static void SimulateClick(Button button)
{
    ExecuteEvents.Execute(button.gameObject, new BaseEventData(EventSystem.current), ExecuteEvents.submitHandler);
}

```

From my (limited) understanding, this uses the EventSystem to create a new "Submit" event on the Button object, as if the user had clicked on it.

I tried it for a Toggle too, and it seems to works fine (Unity 2019.4).

I'm not sure if this is the best way to do it, but it seems legitimate since it's making use of the EventSystem which is designed to manage this kind of interaction.

# Answer
> 1 votes
You can actually create your own click event by overriding the `OnPointerDown(PointerEventData eventData)` method. This works perfectly well for normal Mouse Input but sadly not directly for controller input. My code using this method is this:

```
public override void OnPointerDown(PointerEventData eventData)
{
    base.OnPointerDown(eventData);

    if(!IsActive() || !IsInteractable())
    {
        return;
    }

    //Do stuff here i.e. invoke event or method
}

```

You can even add the a on click event assignable in the inspector (Like the one on a button element). If you'd like to do that make sure to implement `using static UnityEngine.UI.Button;` and make a SerializeField `private ButtonClickedEvent m_OnClick = new ButtonClickedEvent();` Then you can assign your method in the inspector and call `m_OnClick.Invoke();` in the above Method.

This approach is actually pretty similar to the general "Button" UI element, so using this or simply a button will probably not make much of a difference. Nevertheless, this works for me!

I also found out how to add an `onClick` event that can also be triggered by a controller (by the whole event system):

If you click on the points of a component in the inspector, you can sometimes "edit" the script, even if it is a Unity pre-built component like "Button". This helped me to understand the structure of a Button and helped me to find the solution.

You can implement the interface `ISubmitHandler` (and others like `ICancelHandler` , ...) to implement an `OnSubmit` method which is called every time the submit action, referenced in the `eventsystem`, is triggered. You can use these to get this working with controller and keyboard!

Hope that helps, cheers! :)

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


# Question
Title: 2D side-scroller game : smooth noise transition between biomes
I'm creating a little terraria-like 2D side-scroller game with TypeScript. Currently, I divide parts of the world into biomes, which each have their own properties (flat, mountainous terrain, etc.). I am using a one dimensional Perlin noise to generate the height of the terrain for each biome. Currently this is a problem for me because the borders between biomes are not at the same height. How could I make the transitions between biomes smoother?

Thank you in advance for your answers

# Answer
Conceptually, to transition between the 2 biomes *smoothly*, you need 2 biomes and a transition weight. That is, you do not choose between just one of them, but generate both and interpolate between their features (such as height, temperature, savagery, etc). The weight used to interpolate is also generated (preferably with a (relatively) smooth function), therefore you'll need to sample **3 different noises at once** and do some math over the values.

Notice a smooth transition, despite the biomes' differences in maximum height *and* height variability.

For properties that can't be interpolated, a value may be selected based on a threshold. For example, in many games a biome type is a categorical value, it has to be either one or another, not something in between. In that case, a simplest approach is to choose a biome with a biggest weight.
> 1 votes

---
Tags: 2d, perlin-noise, lerp, noise, typescript
---


# Question
Title: Blending Biomes in Procedural terrain generation
I've recently picked up procedural generation and it's been going great - until I decided to give Biomes a shot. With my current setup, I can assign a specific point in my world a biome based on its current height in a "global" biome noise generated with Simplex. The issue i'm having (and many others it seems) is to blend these biomes with eachother - while still being able to decide what goes where.

I tried blending it on my own by simply generating a height with a weight-value that could help with blending a biome with its neighbor. I calculated the weight by getting the distance normalized in a 0 to 1 scale, using this as a percentage. So if the "heaviest" biome had a weight of 0.8, the other neighboring biome would then have 0.2.

```
float totalHeight = (mainBiome * weight) + (otherBiome * (1f - weight));

```

However this didn't work out as I still got cliff-like borders between different height biomes.

Then I found an algorithm at Parzivail.com that actually worked perfectly in blending a biome with its surrounding biomes. The only issue is that it's pretty much only based on the index of my biomes-array.

```
float totalHeight = 0.0f;
float n = biomes.Length;
for (int i = 0; i < n; i++)
{
    float left = (i - 1f) / (n - 1);
    float right = (i + 1f) / (n - 1);
    if (left < noiseHeight && noiseHeight < right)
    {
        var layer = biomes[i];
        float w = -Mathf.Abs((n - 1) * noiseHeight - i) + 1f;

        layer.Evaluate(x, y, sampleCenter);

        totalHeight += w * layer.Height;
        layer.Weight = w;
    }
}

```

(desmos.com visualization)

I've tried modifying it in order to determine biomes based on temperaute and not only height, but whatever I do seems to bring the cliffs back.

Current implementation with seamless transition

How would I change my way of doing this, so I could set up the placement of biomes in a better way and not be forced to use my array indexes?

# Answer
So, after carefully reading the post at https://gamedev.stackexchange.com/a/164252/85899 I managed to get it to work as I wanted it. I'm currently in the works of adding temperature/moisture levels aswell, but I feel like it won't be an issue with this implementation. I'll share my solution below:

```
float noiseHeight = BiomeNoise.GetHeight(x, y, sampleCenter); // returning a noise value between 0 and 1
float totalHeight = 0.0f;
float totalWeight = 0.0f;
int n = biomes.Length;
float[] weights = new float[n];
// Evaluate the point (x, y) with each biome
for(int i = 0; i < n; i++)
{
    var layer = new BiomeLayer() { Biome = biomes[i] };

    // Calculates the noise for a specific point with a given biome
    layer.Evaluate(x, y, sampleCenter);

    float weight = (layer.Biome.Influence - Mathf.Abs(noiseHeight - layer.Biome.StartHeight)) / layer.Biome.Influence;

    // As we don't care about weights below 0, we can just skip blending this biome by setting a weight to 0
    weights[i] = Mathf.Max(weight, 0);
    layer.Weight = weights[i];
    totalWeight += weights[i];

    float height = layer.Height * weights[i];
    totalHeight += height;
}

// Divide total height by the sum of all weights
totalHeight /= totalWeight;

```

Result: (Canyons with a mix of grasslands at bottom left, desert at top right) - the pixelation is due to the LOD system. It's perfectly smooth at the biome borders!
> 1 votes

---
Tags: unity, c#, procedural-generation
---


title: Drawing OpenGL camera frustum

text:
# Question
Title: Drawing OpenGL camera frustum
I am trying to display camera frustum in my OpenGL application. I calculate the vertices of the frustum pyramid using reverse projection from screen space to world space. The camera uses perspective projection, but what is rendered looks like an orthogonal projection.

From my understanding, if any point in world space coordinates can be transformed to a screen space coordinates using matrix multiplication as following

$$ v\_{screen} = P \times V \times M \times v\_{model} $$

where:

* \\$P\\$ is camera projection matrix
* \\$V\\$ is a camera view matrix
* \\$M\\$ is a model transformation matrix
* \\$v\_{screen}\\$ is a 4-dimensional vector in screen space
* \\$v\_{model}\\$ is a 4-dimensional vector in model space

So in order to obtain camera frustum vertices in world space, I solve the above equation for \\$M \times v\_{model}\\$, which is same as saying \\$v\_{world}\\$, since model transformation here is none (identity matrix):

$$ v\_{world} = PV^{-1} \times v\_{screen} $$

And, as figured out on forums online, the resulting vertex, a 4-dimentional vector, would have the \\$w\\$ component, which, if omitted (as I did initially), would result in data loss and thus incorrect results being displayed.

So instead of naive

```
auto vertex = glm::vec3(glm::inverse(cameraProjection * cameraView) * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f));

```

I am now doing

```
auto p = glm::inverse(cameraProjection * cameraView) * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);

auto vertex = glm::vec3(p) / p.w;

```

Just for a sake of context, the camera transformation matrices are defined as

```
const float fov = 45.0f;

glm::vec3 cameraPos = glm::vec3(0.0f, 1.0f, 3.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 cameraRight = glm::vec3(1.0f, 0.0f, 0.0f);
glm::vec3 cameraForward = glm::normalize(glm::cross(cameraUp, cameraRight));

glm::mat4 initialCameraProjection = glm::perspective(glm::radians(fov), (float) window.getSize().x / (float) window.getSize().y, 0.1f, 100.0f);

glm::mat4 initialCameraView = glm::lookAt(
    cameraPos,
    cameraPos + cameraForward,
    cameraUp);

```

Then, using the list of vertices in screen space I map them onto vertices in world space using the inverse matrix approach from above:

```
std::array<glm::vec3, 8> _cameraFrustumCornerVertices{
    {
        { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
        { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
    }
};

const auto proj = glm::inverse(initialCameraProjection * initialCameraView);

const auto proj = glm::inverse(initialCameraProjection * initialCameraView);
std::array<glm::vec3, 8> _frustumVertices;

std::transform(
    _cameraFrustumCornerVertices.begin(),
    _cameraFrustumCornerVertices.end(),
    _frustumVertices.begin(),
    [&](glm::vec3 p) {
        auto v = proj * glm::vec4(p, 1.0f);
        return glm::vec3(v) / v.w;
    }
);

```

And then display the pyramid in violet color:

As you can see, the frustum looks nothing like a cut pyramid, but rather like an orthogonal projection.

Moreover, the view from the camera itself (using the `initialCameraView` and `initialCameraProjection`) does not align with what is rendered as a "frustum":

I bet the issue is with my math, but I can't think of anything else that could cause these errors. Where is my mistake?

# Answer
If I was not this blind, I would notice: the math is perfectly fine. I am transforming the data correctly. But I was not using the *transformed* data - I was rendering the original vertices in screen space instead.
> 2 votes

---
Tags: opengl, c++, mathematics, camera, matrix
---


title: Why are clipping planes... plane?

text:
# Question
Title: Why are clipping planes... plane?
A frustum is used to clip geometry, deciding which parts of it are visible. It seems that most cameras use a frustum shaped as a pyramid segment, i.e. a box between two rects of equal alignment on parallel planes. If the field of view is small (below 40 degree or so), this produces excellent results.

However, for larger angles, this design has a weird consequence: Objects in the center of the screen are clipped 'earlier' than those at the edges, i.e. when less far from the camera origin. This is caused by the far clipping plane being a plane, not an arc. So the Euclidian distance from camera origin to the frustum corners is larger than the distance to the far clipping plane. If the field if view is larger than about 100 degrees, the distance can in fact be twice as large or more.

As a player, one will quickly learn to look diagonally to see more. I've always found that pretty strange. Given that we mostly focus on and look at things of interest in the center of the screen, this is the exact opposite of what I would consider sensible. The view distance in the center should be at least as high as near the screen edges.

So it would seem more useful to either use an arc or quad instead of triangle to define the clipping area.

Regarding performance, I don't see a problem in making such a change at all. An arc, for instance, would replace the which-side-of-far-clipping-plane test with a squared distance check - pretty much the same. Replacing it with a quad would use the Manhattan distance instead, i.e. the player can see further in the center of the screen by factor sqrt(2).

On the other hand, only rendering stuff that is actually in the visual focus area, a *lot* of geometry can be excluded: at higher fov, half of it or more! There is also drastically less loading/unloading of objects when they enter and leave the visible space.

I've seen this implemented comparatively in games: The results were clearly superior, allowing larger view distances at the same performance and removing the diagonal-pop-in effect common in many games.

So I'm wondering: Why is the classic pyramid frustum still used everywhere?

# Answer
They're planar because that's how the math works out.

Classic OpenGL and Direct3D use projection matrices to transform the scene between "world space" and "screen space". "World space" is the coordinate system you're familiar with, while "screen space" is a distorted coordinate system that's very fast for projecting the scene onto the screen.

In "screen space", the viewing frustum isn't a frustum. It's an axis-aligned cube. This turns clipping into a simple test: "is the z-coordinate between the near clipping value and the far clipping value?". As you can imagine, this is a very, very fast operation -- back when OpenGL was developed, it was easily a thousand times faster than a squared-distance check, and even today, it's probably somewhere around twenty times faster.
> 5 votes

---
Tags: camera, performance, frustum
---


title: Matrix math in cascade shadow mapping

text:
# Question
Title: Matrix math in cascade shadow mapping
I am implementing cascade shadow mapping algorithm and currently stuck with matrix transformations - my AABBs, when projected in light space are pointing in the direction opposite to the light:

---

I was following the logic described in Oreon engine video on YouTube and NVidia docs.

The algorithm in my understanding looks like this:

1. "cut" camera frustum into several slices
2. calculate the coordinates of each frustum slice' corners in world space
3. calculate the axis-aligned bounding box of each slice in world space (using the vertices from step 2)
4. create an orthographic projection from the calculated AABBs
5. using the orthographic projections from step 4 and light view matrix, calculate the shadow maps (as in: render the scene to the depth buffer for each of the projections)
6. use the shadow maps to calculate the shadow component of each fragment' color; using `fragmentPosition.z` and comparing it to each of the camera frustum' slices to figure out which shadow map to use

I am able to correctly figure out camera frustum' vertices in world space:

The frustum extends further, but camera clipping distance... well, clips the further slices.

For this, I use inverse matrix multiplication of camera projection and camera view matrices and cube in normalized device coordinates:

```
std::array<glm::vec3, 8> _cameraFrustumSliceCornerVertices{
    {
        { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
        { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
    }
};

```

I then multiply each vertex \\$p\\$ by the inverse of the product \\$P\_{camera} \times V\_{camera}\\$

This gives me the vertices of the camera frustum in world space.

To generate slices, I tried applying the same logic, but using perspective projection with different `near` and `far` distances with little luck.

I then used vector math to calculate each camera frustum slice by taking the entire camera frustum vertices in world space and calculating the vectors for each edge of the frustum: \\$v\_i = v\_i^{far} - v\_i^{near}\\$.

Then I simply multiply these vectors by the lengths of an entire camera frustum and multiply them by the corresponding slice fraction: \\$v\_i^{near} + v\_i \cdot \\|v\_i^{far} - v\_i^{near}\\| \cdot d\_i\\$. Then I simply add these vectors to the near plane of the entire camera frustum to get the far plane of each slice.

```
std::vector<float> splits{ { 0.0f, 0.05f, 0.2f, 0.5f, 1.0f } };

const float _depth = 2.0f; // 1.0f - (-1.0f); normalized device coordinates of a view projection cube; zFar - zNear

auto proj = glm::inverse(initialCameraProjection * initialCameraView);

std::array<glm::vec3, 8> _cameraFrustumSliceCornerVertices{
    {
        { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
        { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
    }
};

std::array<glm::vec3, 8> _totalFrustumVertices;

std::transform(
    _cameraFrustumSliceCornerVertices.begin(),
    _cameraFrustumSliceCornerVertices.end(),
    _totalFrustumVertices.begin(),
    [&](glm::vec3 p) {
        auto v = proj * glm::vec4(p, 1.0f);
        return glm::vec3(v) / v.w;
    }
);

std::array<glm::vec3, 4> _frustumVectors{
    {
        _totalFrustumVertices[4] - _totalFrustumVertices[0],
        _totalFrustumVertices[5] - _totalFrustumVertices[1],
        _totalFrustumVertices[6] - _totalFrustumVertices[2],
        _totalFrustumVertices[7] - _totalFrustumVertices[3],
    }
};

for (auto i = 1; i < splits.size(); ++i)
{
    std::array<glm::vec3, 8> _frustumSliceVertices{
        {
            _totalFrustumVertices[0] + (_frustumVectors[0] * _depth * splits[i - 1]),
            _totalFrustumVertices[1] + (_frustumVectors[1] * _depth * splits[i - 1]),
            _totalFrustumVertices[2] + (_frustumVectors[2] * _depth * splits[i - 1]),
            _totalFrustumVertices[3] + (_frustumVectors[3] * _depth * splits[i - 1]),

            _totalFrustumVertices[0] + (_frustumVectors[0] * _depth * splits[i]),
            _totalFrustumVertices[1] + (_frustumVectors[1] * _depth * splits[i]),
            _totalFrustumVertices[2] + (_frustumVectors[2] * _depth * splits[i]),
            _totalFrustumVertices[3] + (_frustumVectors[3] * _depth * splits[i]),
        }
    };

    // render the thing
}

```

According to the algorithm, the next part is finding the axis-aligned bounding box (AABB) of each camera frustum slice and projecting it in the light view space.

I am able to correctly calculate the AABB of each camera frustum slice in world space:

This is a rather trivial algorithm that iterates over all the vertices from the previous step and finds minimal `x`, `y` and `z` coordinate of each vertex of a camera frustum slice in world space.

```
float minX = 0.0f, maxX = 0.0f;
float minY = 0.0f, maxY = 0.0f;
float minZ = 0.0f, maxZ = 0.0f;

for (auto i = 0; i < _frustumSliceVertices.size(); ++i)
{
    auto p = _frustumSliceVertices[i];

    if (i == 0)
    {
        minX = maxX = p.x;
        minY = maxY = p.y;
        minZ = maxZ = p.z;
    }
    else
    {
        minX = std::fmin(minX, p.x);
        minY = std::fmin(minY, p.y);
        minZ = std::fmin(minZ, p.z);

        maxX = std::fmax(maxX, p.x);
        maxY = std::fmax(maxY, p.y);
        maxZ = std::fmax(maxZ, p.z);
    }
}

auto _ortho = glm::ortho(minX, maxX, minY, maxY, minZ, maxZ);

std::array<glm::vec3, 8> _aabbVertices{
    {
        { minX, minY, minZ }, { maxX, minY, minZ }, { maxX, maxY, minZ }, { minX, maxY, minZ },
        { minX, minY, maxZ }, { maxX, minY, maxZ }, { maxX, maxY, maxZ }, { minX, maxY, maxZ },
    }
};

std::array<glm::vec3, 8> _frustumSliceAlignedAABBVertices;

std::transform(
    _aabbVertices.begin(),
    _aabbVertices.end(),
    _frustumSliceAlignedAABBVertices.begin(),
    [&](glm::vec3 p) {
        auto v = lightProjection * lightView * glm::vec4(p, 1.0f);
        return glm::vec3(v) / v.w;
    }
);

```

I then construct an orthographic projection from that data - as per algorithm, these projections, one per camera frustum slice, will be later used to calculate shadow maps, aka render to depth textures.

```
auto _ortho = glm::ortho(minX, maxX, minY, maxY, minZ, maxZ);

```

To render these AABBs, I tried rendering the view cube, like with the camera frustum, but got some dubious results:

Both the position and the size of the AABBs were wrong.

I tried making the AABBs "uniform", e.g. `left = ((maxX - minX) / 2) * -1` and `rihgt = ((maxX - minX) / 2) * +1`, which resulted in only centering the AABBs around the same origin point `(0, 0, 0)`:

```
const auto _width = (maxX - minX) / 2.0f;
const auto _height = (maxY - minY) / 2.0f;
const auto _depth = (maxZ - minZ) / 2.0f;

auto _ortho = glm::ortho(-_width, _width, -_height, _height, -_depth, _depth);

```

I then used `min / max` values of each corresponding coordinate instead of `+/- 1` in the view cube to get the correct results:

```
std::array<glm::vec3, 8> _aabbVertices{
    {
        { minX, minY, minZ }, { maxX, minY, minZ }, { maxX, maxY, minZ }, { minX, maxY, minZ },
        { minX, minY, maxZ }, { maxX, minY, maxZ }, { maxX, maxY, maxZ }, { minX, maxY, maxZ },
    }
};

```

Last step of an algorithm, though is not willing to cooperate: I thought that by multiplying each of the orthogonal projections by the light' view matrix I will align the AABB with the light direction, but all I got was misaligned AABBs:

```
std::array<glm::vec3, 8> _frustumSliceAlignedAABBVertices;

std::transform(
    _aabbVertices.begin(),
    _aabbVertices.end(),
    _frustumSliceAlignedAABBVertices.begin(),
    [&](glm::vec3 p) {
        auto v = lightView * glm::vec4(p, 1.0f);
        return glm::vec3(v) / v.w;
    }
);

```

Only when I multiply it by **both** light projection matrix and light view matrix I get something similar to alignment:

```
std::array<glm::vec3, 8> _frustumSliceAlignedAABBVertices;

std::transform(
    _aabbVertices.begin(),
    _aabbVertices.end(),
    _frustumSliceAlignedAABBVertices.begin(),
    [&](glm::vec3 p) {
        auto v = lightProjection * lightView * glm::vec4(p, 1.0f);
        return glm::vec3(v) / v.w;
    }
);

```

Ironically, seems the direction is opposite to the light' direction.

Despite my light being pointed to origin `(0, 0, 0)`, the AABBs seem to be projected in reverse order.

**Question:** why is this happening? Why is the direction & order of the projections reversed? How to put it in a correct order?

# Answer
> 2 votes
I have figured a hacky (at least from my lack of understanding) way to fix the issue - construct a new light view matrix every time.

This is also what is happening in Vulkan example of cascade shadow mapping

Apparently, one needs to update the light projection and light view matrices for every new camera frustum slice. And that kind of makes sense - the projection parameters will be different for each cascade (aka camera frustum slice).

Seems like this approach works just fine in **simple case**:

```
glm::vec3 _frustumCenter(0.0f);

for (auto p : _frustumSliceVertices)
{
    _frustumCenter += p;
}

_frustumCenter /= 8.0f;

// we position AABB at the center of a frustum slice (_frustumCenter) and orient it along the light direction
// the trick here is to offset the AABB by its half so that all the AABBs stack together nicely and neither overlap nor leave gaps
glm::mat4 _lightViewMatrix = glm::lookAt(
    _frustumCenter - _lightDirection * ((maxZ + minZ) / 2.0f),
    _frustumCenter,
    glm::vec3(0.0f, 1.0f, 0.0f)
);

glm::mat4 _lightOrthoMatrix = glm::ortho(minX, maxX, minY, maxY, 0.0f, maxZ - minZ);

```

Yet when camera is initially moved away, the projections happen to be mangled:

So I have tried a yet another approach (which happened to be very similar to the one in Vulkan example).

Instead of calculating each AABB corner vertex in light space, I calculate the bounding sphere radius as maximum of the distances from each of the frustum slice corner to the frustum center:

```
glm::vec3 _frustumCenter(0.0f);

for (auto p : _frustumSliceVertices)
{
    _frustumCenter += p;
}

_frustumCenter /= 8.0f;

float _boundingSphereRadius = 0.0f;

for (auto p : _frustumSliceVertices)
{
    _boundingSphereRadius = glm::max(_boundingSphereRadius, glm::length(p - _frustumCenter));
}

```

I then use light direction, frustum slice center and the bounding sphere radius to create light view matrix:

```
glm::vec3 _maxExtents(_boundingSphereRadius);
glm::vec3 _minExtents = -_maxExtents;

glm::mat4 _lightViewMatrix = glm::lookAt(
    _frustumCenter + _lightDirection * _boundingSphereRadius,
    _frustumCenter - _lightDirection * _boundingSphereRadius,
    glm::vec3(0.0f, 1.0f, 0.0f)
);

glm::mat4 _lightOrthoMatrix = glm::ortho(_minExtents.x, _maxExtents.x, _minExtents.y, _maxExtents.y, 0.0f, _maxExtents.z - _minExtents.z);

```

Since the projections I am mapping are built off the *bounding sphere*, they are rather huge. And they overlap. A lot:

So the orientation is correct, but the overlap (e.g. the projection size) is probably sub-optimal.

I was thinking about something similar to what is described in this blog:

Yet I can not think of a good intuition to build one - the only idea that comes to my mind is to get the face of a frustum slice AABB closest to the light and extrude it in the light direction.

But finding the face is a concerning part - don't want to mess with line-plane intersection - seems sub-optimal. And I can not universally pick a single face, since depending on the light direction I will need to extrude a different face:

In the screenshot above you can see that different lights would need to extrude different faces for correct shadow mapping - `light2` and `light3` can not extrude the top face of the frustum slice / AABB, since that would provide wrong projection matrix and wrong shadows being cast.

And that is exactly the reason why I picked bounding sphere - it is uniformly oriented, so I can pick whichever direction I need (like light direction) and extrude my projection box from \\$center - direction\\$ in the \\$direction\\$.

---
Tags: opengl, mathematics, matrix, shadows, glm
---


# Question
Title: Better use background chromas or transparency?
For `png` 2D sprites, its better use chromas or alpha channel?

* What is more performant during run-time processing?
* What uses less storage?
* Any difference between 2D & 3D?

*\[using **Godot Engine**\]*

# Answer
> 1 votes
There will be a shader in charge of displaying the sprites. This shader will have the logic to handle either the chroma key or the alpha channel.

If you use alpha channel, you will need to send more data to the GPU (the alpha channel). However, you wouldn't be sending the textures every frame, instead you send them on load and reuse them. Thus, the performance impact we are talking about is slightly more time on load and slightly more video memory used.

On the other hand, for the chroma key… Well, it depends. If you are going to make a single exact color transparent, then the shader is as performant as using alpha channel (with the drawback that you cannot specify levels of transparency). However, if you are going to set transparency depending on how close a color is to the chroma key, within some range. Then the shader code will be more complicated, and thus less performance in runtime (the performance hit might or might not is perceptible).

---

I remind you that if you use chroma key, you lose the ability to use the color you picked for your chroma key.

I will also remind you that you will not be sending the PNG to the GPU. You will have to decode the PNG into a bitmap with a pixel format the GPU supports. And you would do that conversion in CPU.

And I will further remind you that the formats you use to develop do not have to match the formats you deploy. If you find it easier to develop with PNG with chroma key, you might as well have a tool that converts them to a format that supports transparency and can be loaded directly into GPU, and add that as a step to your build process.

---

There isn't a difference between 2D and 3D about how you encode transparency.

However… Unusually in 2D you would know in what order to render things, while in 3D you would rely on depth test (well, unless you are doing ray-tracing or something like that). Now, if the fragment shader writes depth or drops fragments, the GPU needs to runs the fragment shader before deciding what occludes what, and thus having things with transparency (by chroma key or alpha channel) slows everything down. The simple solution is to draw all the opaque geometry first, and then the potentially transparent geometry afterwards.

See also: Do I lose/gain performance for discarding pixels even if I don't use depth testing?

---

You might also be interested in not having transparency. Instead create a mesh from the texture that only includes the opaque areas. This, of course, means more triangles. But it also means a simpler shader. Thus, you will have to decide if this trade-off is worth it for your game.

# Answer
> 1 votes
Transparency can be very costly on low end devices because the game has to do a lot of work to draw things in the right order (which obviously means more video memory). Of course it depends on the number and size of your objects so you'll have to test it to find out for sure.

Although a Chroma key solution would be more complicated so it's going to be a trade off.

There probably won't be any differences between 2D and 3D. I mean there's the perspective math you have to do but I don't think using transparency really changes that.

---
Tags: 2d, godot, image, spritesheet, png
---


# Question
Title: Displaying FPS arms for the local player, and the full body for remote players
I'm wanting to try my hand at making an FPS multiplayer game. If I use arms as the first person model while playing, how do I set it up so that the other players see a full body model, and not just arms?

# Answer
> 1 votes
I have used this concept in one of my multiplayer game with Photon Pun2. where we just check whether photonView.IsMine or not to load what ever is required. This is a player setup script runs whenever multiplayer scene is loaded.

```
public GameObject[] FPS_Hands_ChildGameobjects;
    public GameObject[] Soldier_ChildGameobjects;

    public GameObject playerUIPrefab;
    private PlayerMovementController playerMovementController;

    public Camera FPSCamera;

    private Animator animator;

    private Shooting shooter;

    // Start is called before the first frame update
    void Start()
    {
        shooter = GetComponent<Shooting>();
        animator = GetComponent<Animator>();
        playerMovementController = GetComponent<PlayerMovementController>();

        if (photonView.IsMine)
        {
            //Activate FPS Hands, Deactivate Soldier
            foreach (GameObject gameObject in FPS_Hands_ChildGameobjects)
            {
                gameObject.SetActive(true);
            }

            foreach (GameObject gameObject in Soldier_ChildGameobjects)
            {
                gameObject.SetActive(false);
            }

            //Instantiate PlayerUI
            GameObject playerUIGameobject = Instantiate(playerUIPrefab);
            playerMovementController.joystick = playerUIGameobject.transform.Find("Fixed Joystick").GetComponent<Joystick>();
            playerMovementController.fixedTouchField = playerUIGameobject.transform.Find("RotationTouchField").GetComponent<FixedTouchField>();

            playerUIGameobject.transform.Find("FireButton").GetComponent<Button>().onClick.AddListener(()=>shooter.Fire());

            FPSCamera.enabled = true;

            animator.SetBool("IsSoldier",false);

        }
        else
        {

            //Activate Soldier, Deactivate FPS Hands
            foreach (GameObject gameObject in FPS_Hands_ChildGameobjects)
            {
                gameObject.SetActive(false);
            }

            foreach (GameObject gameObject in Soldier_ChildGameobjects)
            {
                gameObject.SetActive(true);
            }

           playerMovementController.enabled = false;
            GetComponent<RigidbodyFirstPersonController>().enabled = false;

            FPSCamera.enabled = false;

            animator.SetBool("IsSoldier", true);

        }

    }

```

---
Tags: unity, multiplayer, first-person-shooter
---


# Question
Title: while(1) in separate threads. safe and efficient
In my TCP multithreaded server written in C, I have multiple threads with infinite loops checking for new inputs from thread safe queue and then doing their jobs. pseudocode:

```
void jobThread(void * arg){
    CustomQueue queue = (CustomQueue) arg;
    while(1){
        if(customQueueNotEmpty(queue)){
            doSomeJob(getItemFromQueue(queue))
        }
    }
}

```

I have multiple threads running like this, but number of threads is directly controlled with program. It is not like threads are spawned for each user online or job to be done, but rather user sessions and game-jobs are added dynamically to prespawned threads. Most probably the number of threads will be limited by number of CPUs on host machine.

My question is about the `while(1)` statement. In case when there are many users connected and many jobs to be done this is probably fine, because all of the CPU time is just used to do the job. But otherwise, most of the CPU time gets burned just to loop and check queue.

Should I add `sleep()` to make thread less CPU exhaustive? Or should I not use `while(1)` since it is not a good practice? Or do I not care at all since every thread can get its own CPU core and therefore does not slow other threads?

Edit: Philiph's answer suggested using condition variables which I imagine using something like this:

```
void jobThread(void * arg){
    CustomQueue queue = (CustomQueue) arg;
    while(1){
        while(customQueueNotEmpty(queue)){
            doSomeJob(getItemFromQueue(queue))
        }
        pthread_cond_wait(cond); //when queue is empty wait for other thread to reawake this
    }
}

```

and then in other thread that fills the queue call:

```
putInQueue(quueue, item);
pthread_cond_signal(cond);

```

when new message arrives. But what about case, when consumer thread reads queue as being empty just before the moment of producer thread filling it with new message. Then the consumer thread would wait without processing the new message and only awakening after yet another message arrives to awake the consumer and make it process both new messages.

# Answer
Having a thread busy-spin like that is not a good idea. It causes unnecessary CPU load. This drains the battery of mobile users device, causes unnecessary heat and power consumption for desktops and servers and steals CPU time from background processes.

A better idea could be to make the thread pause itself when it completed processing its message queue. Then have the system which handles the message queue resume the thread as soon as it enqueues a new message. How to do that depends on what threading library you are using. I haven't got any experience with multithreading in C in particular, but a cursory research tells me that pthread is a popular library choice, which further points me to `pthread_cond_wait` and to this stackoverflow question.
> 2 votes

---
Tags: multithreading, c
---


# Question
Title: What's a good method to update the U.I in Unity after a player scores a point?
I'm practicing with making a Pong clone and I've decided I want 2 large empty gameObjects on either side off camera to act as triggers to reset the game and add a point to either player's score, but Unity's U.I system confuses me.

Any help would be appreciated.

# Answer
> 0 votes
It's actually not uncommon for Unity UI code to just poll the current data in their Update method and change the text accordingly. For example, my standard approach to a UI widget which simply shows the score of a player would look something like that:

```
using UnityEngine;
using UnityEngine.UI;

public class PlayerScoreDisplay : MonoBehaviour
{
      public Player player
      public Text text;

      void Update() {
           text.text = player.score.toString();
      }
}

```

It might seem a bit wasteful to update the UI every single frame even if nothing changed. A more efficient architecture might be to use some messaging architecture or the Observer pattern and only update the UI when the data actually changed. But the UI is usually the least performance-intense part of an Unity game. So unless you have really a lot of UI elements, that optimization isn't worth the effort and additional code complexity. And it would definitely be over-engineering for a simple Pong practice game.

# Answer
> 0 votes
I use an event bus, which is basically the observer pattern, but many-to-many instead of 1-to-many.

You emit a "Scored" event from your player script, and the UI controller script picks it up and updates the UI. This way they the gameplay and UI logic stays completely decoupled.

Here is a small library I wrote for this purpose: https://github.com/starikcetin/Eflatun.EventBus

# Answer
> 0 votes
If you are interested in keeping your classes more organized. I would suggest you to segregate each class to be restricted to specific functionality.

One approach we used to do at work, was to do some sort of **MVC (Model View Controller)** approach (of course, not as literal as the framework textually is) where we have a controller that has access to all or many elements of the game (in this casethe class Game, thast has references to the players and the UI) and makes use of the **Observer Pattern** with delegates as Philipps also suggested.

Example (note that, for the sake of example, I ommited the inclusion of namespaces. Your approach of letting each player its score instead of the game having 2 scores is also correct, if not better):

```
public class Game : MonoBehaviour
{
    public Player player1;
    public Player player2;
    public UIController UIController;
    private int player1Score;
    private int player2Score;

    private void Start()
    {
        if(player1 == null || player2 == null) return;

        player1.onPlayerEvent += OnPlayerEvent;
        player2.onPlayerEvent += OnPlayerEvent;
    }

    private void OnPlayerEvent(Player player, int eventID)
    {
        switch(eventID)
        {
            case Player.ID_ADDSCORE:
            if(player == player1)
            {
                player1Score++;
                UIController.UpdatePlayerScore(1, player1Score);
            }
            if(player == player2)
            {
                player2Score++;
                UIController.UpdatePlayerScore(2, player2Score);
            }
            break;

            /*
            case 2:
            ...
            break;
            .
            .
            .
            case N:
            break;
            */
        }
    }
}

public class UIController : MonoBehaviour
{
    public Text player1ScoreText;
    public Text player2ScoreText;

    public void UpdatePlayerScore(int player, int score)
    {
        switch(player)
        {
            case 1:
            player1ScoreText.text = score.ToString();
            break;

            case 2:
            player2ScoreText.text = score.ToString();
            break;
        }
    }
}

public delegate void OnPlayerEvent(Player player, int eventID);

public class Player : MonoBehaviour
{
    public const int ID_ADDSCORE = 0;

    public event OnPlayerEvent onPlayerEvent;

    private void Update()
    {
        /// After conditions for the score to be updated are met:
        if(onPlayerEvent != null) onPlayerEvent(this, ID_ADDSCORE);
    }
}

```

But as Philipps mentioned already, the scope of your project is very simple, and a simple Update to fetch the players' score at every frame does not harm the performance at all.

Hope it helps, at least for the sake of having another perspective.

---
Tags: unity
---


# Question
Title: Making Sprite Movement Appear More Natural
Currently I have a 2D game in which the player and a computer controlled (non-player) sprite move from point to point collecting tokens in a continuous environment. The player and the non-player sprite are usually moving between two different points at different times, not together. One aspect of this game is tricking the player into believing that they are playing a multi-player game with another person, when in reality the other character is controlled by the computer.

The non-player sprites are currently controlled by a boid algorithm, which results in movement that is very smooth and linear. Since players use arrow keys to control their sprite, the smooth linear movement of the non-player sprites is not particularly convincing for tricking the player into believing the other character is human controlled. Adding random perturbations to the boid algorithm increases believe-ability, but does not exactly look natural.

I feel this should be easy, but for some reason I'm just not seeing it, so here is my question: **Is there a simple algorithm for sprite motion between two 2D points that would realistically simulate a human controlling a sprite with arrow keys?**

# Answer
Ok, here is a heuristic solution that results in sprite motion qualitatively similar to what one would expect from a human player using arrow keys. This solution works for motion from an initial position (A) in 2D to a goal position (B) in 2D:

1. First, define vectors corresponding to the arrow key directions.
2. Then, compute the heading vector between A and B.
3. Compute the angle between the heading vector and all of the arrow key direction vectors.
4. Select the arrow key direction vector with the smallest angle between itself and the heading vector. Assign this direction to some variable *v*.
5. On every update step, with some probability *p*, increment the sprite's position by *v*, and with probability *1-p*, repeat steps 2-4 to compute a new *v*, replacing the original point A by your current position.

Values above 0.5 for *p* seem to work best. Here is some pseudocode (with arbitrary assumption that velocity = 1):

```
UP = [0,1]
DOWN = [0,-1]
RIGHT = [1,0]
LEFT = [-1,0]

DIRS = [UP, DOWN, LEFT, RIGHT]

get_direction(sprite_X, sprite_Y, goal_X, goal_Y, DIRS):
    A = [sprite_X, sprite_Y]
    B = [goal_X, goal_Y]
    heading = (B - A) / |B - A|
    angles = []
    for DIR in DIRS:
        angles.append(angle_between(DIR,heading))
    v = DIRS[index_of_minimum(angles)]
    return v

update(sprite_X, sprite_Y, goal_X, goal_Y, v, DIRS, p):
    sprite_position = [sprite_X, sprite_Y]
    if (random(0, 1) <= p):
        sprite_position += v
    else:
        v = get_direction(sprite_X, sprite_Y, goal_X, goal_Y, DIRS)
        sprite_position += v
    return sprite_position

```
> 0 votes

---
Tags: physics, algorithm, sprites, movement
---


title: How to number tiles?

text:
# Question
Title: How to number tiles?
I want to number tiles and when gameobject moves, the gameobject should know which tiles it's in. I dont want to use collider. How can I do that ?

This is my game area. For example tile numbers should increase left to right. and when gameobject starts to move tile to tile, it should know which tile it's in. For example if gameobject in tile in this image, it should know that it's in sixth tile

I made and 2D array but I couldn't reference this array with tiles. Idk how to do.

```
 void Make2dArray(int _row, int _column)
{
    array2D = new int[_row, _column];

    for (int i = 0; i < _row; i++)
    {
        for (int j = 0; j < _column; j++)
        {

            array2D[i, j] = tileIndex;
            tileIndex++;
        }
    }
}

```

# Answer
It's important to recognize you now have an additional coordinate system. You already have world coordinates (the game objects in Unity) but you also have "grid coordinates". Your top left tile is 0,0. The one to the right of it is 1,0. The one below is 0,1.

Consider the world point 200,300. If your tiles are 100x00, world point 200,300 corresponds to grid coordinate 2,3. The math to turn, say, world point 250.6,320.5 into a grid coordinate is slightly more involved than just dropping the decimal. There may be better options here's the math with the modulo operator (%) to ensure you're working on *tile boundaries*. (Eg, you want 400 instead of world point 487.392.)

```
(int)(250.6) = 250
(int)(320.5) = 320
250 % 100 = 50
320 % 100 = 20
250 - 50 = 200
320 - 20 = 300
[200,300] / 100 = 2,3

```

With that above math, from any world point you can get any tile coordinate.

You can then turn any tile coordinate into a tile index, assuming you know how many tiles in each row. Given tile coordinate 2,3:

```
TilesPerRow = 12
((3 * 12) + 2) = 38

```

You don't actually need to associate a number with a tile. You just need to know each tile's X and Y coordinate. Of course, you certainly could pre-calculate these indices and store them, along with each tile's X and Y as a property in Unity, but you can turn any "world coordinate" into a "grid coordinate", and then into a tile index, **as long as your tiles either start at 0,0, or the middle tile is always 0,0 and you store the number of tiles across/down somewhere.** (Using a starting tile index other than 0,0 left as an exercise up to the reader but it pretty much just involves subtraction, to act as if that top left tile is at world coordinate 0,0).

So, with your box game object, its coordinate can tell you what tile it's in. Or multiple tiles, if it's larger than a single tile, if you treat it as a rectangle.

All that said, it sounds like you're fairly new to both Unity and programming in general. If you prefer to stick with your original solution, that 2D array needs to be on a globally accessible object. It could be a static variable on a component script that is attached to your tile objects. If none of that makes sense, perhaps following a few more Unity tutorials is in order.
> 2 votes

# Answer
It seems to me like the main problem is that you have the variable `array2D` on one gameObject, but you need different gameObjects to access that array.

When you have only ever have one tile grid in your game, then you can put it into a `static` variable. Static variables are variables which are not parts of each instances of a class but are global variables which are parts of the class itself:

```
public class GameArea : MonoBehaviour {

     public static int[] tiles;

     void Make2dArray(int _row, int _column) {
         tiles = new int[_row, _column];
         /*...*/
     }
}

```

Now all other classes can access that array using `GameArea.tiles`. No need for a reference.

OK, but when exactly do you call the method `Make2dArray`? Well, *some* object needs to call it. But when? In its `Start` method? What if there are other scripts which need to access the tiles in *their* `Start` method and they happen to run before that initialization script? They would run into a `NullReferenceException`.

Yes, there are ways to manage script execution order. But keeping that list in mind all the time can get really annoying, especially in complex projects. I actually *never* bother with that list. Because with properly structured code architecture, it's perfectly possible to write code which works regardless of execution order.

Here is one elegant way to initialize it before it is first accessed, regardless of who accesses it and how: Make that variable private, but add a public property to access it. That property first checks if the array is `null`, and when that's the case it initializes it:

```
public class GameArea : MonoBehaviour {

     public int rows;
     public int columns;

     private static int _tiles;

     public static int[] Tiles {
          get {
              if (_tiles == null) {
                    Make2dArray()
              }
              return _tiles;
          }
     };

     void Make2dArray() {
         tiles = new int[row, column];
         /*...*/
     }
}

```

I also turned the number of rows and columns into public variables, so you can set them in the inspector of the gameObject carrying this MonoBehaviour.

---

This should get you working for now. But a good next step could be to turn this whole MonoBehaviour into a proper Singleton. That allows you to delegate further functionality to the script. For example, you can move the logic for translating world-coordinates to tile-coordinates into that MonoBehaviour. When the object isn't always centered around the world origin, then you would require access to the `transform` for that. Which isn't `static`, so you can't access it in a `static` method. But by using a static method to get the one and only instance of that MonoBehaviour on a game object, you can get around that.
> 1 votes

---
Tags: unity
---