# Question
Title: Is there a name for this technique to put the tiles on the corner of a level?
A very common approach in development of old games is to put the tile set on the corner of a level, to use it as a reference. For example:

On this level, the developers put a set of tiles in the upper left corner.

But is there a name for this technique? I'm writing a manual about that and I would like to name it.

# Answer
I don't know if there is a name, but this seems to be something you'd do to conserve memory.

First, a basic tile is very low resolution - just a few pixels across. But when rendered, they are magnified 2x, 3x, 4x, etc. and are much more "blocky" on the screen.

Next, older games will have a block of memory dedicated to screen display - what is in that memory is what's shown on screen. Keep in mind that memory is VERY tight in older platforms, so as a developer you want to save every little bit you can.

So rather than put your tiles into a separate memory space, you just make them part of your screen memory, thus saving a bit. And the artifact of this of course is that they show up on the screen.

From the perspective of memory access, the code doesn't care if the memory being accessed is being used for screen memory or variable storage. Basically, memory management in older games was very simple and there was just one block of memory available. There was no GPU, so no idea of separate processors and memory for programming versus screen display.

To give a sense of how tight memory could be programming earlier games, here is a quote from a 1983 article about programming the Atari and VIC computers, "Atari's super hi-resolution screen (and the 16-color GTIA modes) uses almost 8K of RAM." That seems like very little, but keep in mind the computer perhaps only had 48K of memory, a lot of which was taken up by other things besides the game.
> 8 votes

# Answer
It's a palette. Same thing you see some artists doing with colors. They draw a group of a couple of the main colors or even a gradient going between them for easy access. It's much easier to use a picker tool to select the next color than to go into the color picker wheel, fiddle around with it for a couple of minutes and pray it matches the rest of the picture.

Same thing with tiles, since most tile editors are just very advanced pixelart programs, but with tiles instead of colors.
> 9 votes

---
Tags: tilemap, terminology, tilesets
---


# Question
Title: Having some trouble with my frustum checking code
I'm trying to check if a bounding sphere is either within or intersecting my frustum. It mostly works but there are cases where it should and it doesn't. The frustum is made up of 6 planes which have a position, direction and normal vector. Sphere has a center and radius value. The frustum is created from translating the mouse coordinates into 3d. If anyone can point me in the right direction it would be greatly appreciated. I'm not great at Maths either.

```
static float DistanceFromPointToPlane(Plane p, DirectX::SimpleMath::Vector3 point) {
    float distance = p.normal.Dot(point - p.position);

    return distance;
}

static bool IsSphereInsidePlane(DirectX::SimpleMath::Vector3 sphereCentre, Plane p, float radius) {
    float d = DistanceFromPointToPlane(p, sphereCentre);
    return -d > radius;
}

static bool SphereIntersectsPlane(DirectX::SimpleMath::Vector3 sphereCentre, Plane p, float radius) {
        return fabs(DistanceFromPointToPlane(p, sphereCentre)) <= radius;
    }

```

# Answer
> 2 votes
Assuming the "inside" of a plane is the opposite side of the plane.normal, the function `IsSphereInsidePlane` correctly determines if the sphere is **completely** inside the plane. The second function correctly determines if the sphere is intersecting.

You should either: use both functions to determine if the sphere is inside OR intersect, or better you should change the return value of `IsSphereInsidePlane` to return `d < radius` and use only this function, forgetting about the other one

---
Tags: directx11, intersection, frustum, bounding-spheres
---


# Question
Title: How to implement a slight skid in a car game
I have a top down car game, where I'm trying to allow a slight skid; I've tried the following code to calculate the X and Y, but there is no skid whatsoever:

```
radians = rotation * Math.PI / 180;

aX = (momentum * Math.cos(radians));
aY = (momentum * Math.sin(radians));

newX = playerX + aX,
newY = playerY + aY

```

I can get skid by introducing a velocity variable; for example:

```
radians = rotation * Math.PI / 180;

aX = (momentum * Math.cos(radians));
aY = (momentum * Math.sin(radians));

velocityX = velocityX + aX;
velocityY = velocityY + aY;

newX = playerX + velocityX;
newY = playerY + velocityY;

```

This introduces far too much skid, like the car is on ice. I've tried reducing the amount I increase the velocity by:

```
velocityX = velocityX + (aX / 3);

```

Which sort of works initially, but still ends up ice skating and uncontrollable after playing around for a few minutes.

Are there any techniques for introducing a slight skid without this extreme side effect?

# Answer
> 1 votes
There are different physical effects of skiding but most probably you want to implement understeering, i.e. that the car turns not enough when in a curve and leaves the road or something like this.

Your car does not seem to have any orientation on the ground, it's probably modeled as a point.

You add the momentum to the position, that must mean that you set the mass to one and also the time interval between position updates.

The way to introduce understeering is keeping a fraction of the old movement vector when applying the new movement vector.

```
skid_factor = 0.5; // adjust that

radians = rotation * Math.PI / 180;
aX = (momentum * Math.cos(radians));
aY = (momentum * Math.sin(radians));

velocityX = skid_factor * velocityX + (1-skid_factor) * aX
velocityY = skid_factor * velocityY + (1-skid_factor) * aY

newX = playerX + velocityX;
newY = playerY + velocityY;

```

Maybe, in order to be more realistic, the skidding factor should be dynamic, i.e. high if the change in direction (angle between velocityX,Y and new direction aX,Y) is large and small if you do not change it.

```
skid_factor = 1 - (velocityX*aX+velocityY*aY)^2/(aX^2+aY^2)/(velocityX^2+velocityY^2)

```

---
Tags: physics, car
---


# Question
Title: Pure functional programming and game state
Is there a common technique to handle state (in general) in a functional programming language? There are solutions in every (functional) programming language to handle global state, but I want to avoid this as far as I could.

All state in a pure functional manner are function parameters. So I need to put the whole game state (a gigantic hashmap with the world, players, positions, score, assets, enemies, ...)) as a parameter to all functions which wants to manipulate the world on a given input or trigger. The function itself picks the relevant information from the gamestate blob, do something with it, manipulate the gamestate and return the gamestate. But this looks like a poor mans solution for the problem. If I put the whole gamestate into all functions, there is no benefit for me in contrast to global variables or the imperative approach.

I could put just the relevant information into the functions and return the actions which will be taken for the given input. And one single function apply all the actions to the gamestate. But most functions need a *lot* of "relevant" information. `move()` need the object position, the velocity, the map for collision, position of all enemys, current health, ... So this approach does not seem to work either.

So my question is how do I handle the massive amount of state in a functional programming language -- especially for game development?

**EDIT:** There are some game frameworks for building games in Clojure. There approach to solve this problem partially is to thread *all* objects in the game as "entities" and put it in a huge bag. A gigant main function is holding the screen and the entities and handle events (`:on-key-down`, `:on-init`, ...) for this entities and run the main display loop. But this is not the clean solution I am searching for.

# Answer
> 10 votes
I have written a few games using F# (multi-paradigm, impure, functional-first language), with approaches ranging from OOP to FRP. This is a broad question, but I'll do my best.

> Is there a common technique to handle state (in general) in a functional programming language?

My preferred way is to have an immutable type that represents the entire game `State`. I then have a mutable reference to the current `State` that is updated each tick. This is not *strictly* pure, but it keeps mutability limited to one place.

> If I put the whole gamestate into all functions, there is no benefit for me in contrast to global variables or the imperative approach.

Not true. Because the `State` type is immutable, you cannot have any old component mutating the world in ill-defined ways. This fixes the biggest problem with the `GameObject` approach (popularized by Unity): it is hard to control the order of `Update` calls.

And unlike using globals, it is easily unit-testable and parallelizable,

You should also write helper functions that receive sub-properties of the state to break down the problem.

For example:

```
let updateSpaceShip ship =
  {
    ship with
      Position = ship.Position + ship.Velocity
  }

let update state =
  {
    state with
      SpaceShips = state.SpaceShips |> map updateSpaceShip
  }

```

Here `update` acts on the whole state, but `updateSpaceShip` only acts on an individual `SpaceShip` in isolation.

> I could put just the relevant information into the functions and return the actions which will be taken for the given input.

My suggestion would be to create an `Input` type that holds the keyboard, mouse, game-pad, etc. states. You can then write a function that takes a `State` and an `Input` returning the next `State`:

```
let applyInput input state =
  // Something

```

To give you an idea of how this fits together, the overall game might look something like this:

```
let mutable state = initialState ()

// Game loop
while true do
  // Apply user input to the world
  let input = collectInput ()

  state <- applyInput input state

  // Game logic
  let dt = computeDeltaTime ()

  state <- update dt state

  // Draw
  render state

```

> So my question is how do I handle the massive amount of state in a functional programming language -- especially for game development?

For simple games you can use the approach above (helper functions). For something more complicated, you might want to try "lenses".

Contrary to some of the comments here, I would strongly suggest writing games in an (impure) functional programming language, or at least giving it a try! I have found it makes iteration quicker, code-bases smaller and bugs less common.

I also *don't* think you need to learn monads to write games in an (impure) FP language. This is because your code will most likely be blocking and single threaded.

This is particularly true if you are writing a multiplayer game. Then things will become much easier with this approach because it allows you to trivially serialize the game state and send it across the network.

As for why more games aren't written this way... I cannot say. However, this is true in all programming domains (except perhaps finance), so I wouldn't use this as an argument that functional languages are ill-suited to game programming.

Also well worth a read is Purely Functional Retrogames.

# Answer
> 9 votes
Side-effects and state in functional programming languages are a broader problem in computer science. In case you haven't encountered them before, maybe take a look at monads. Be warned, though: they are a fairly advanced concept and most people I know (me included) struggle to grasp them. There are many, *many* tutorials online, with differing approaches and knowledge requirements. Personally, I liked Eric Lippert's best.

> I’m a C# programmer with no “functional programming” background whatsoever. What is this “monad” thing I keep hearing about, and what use is it to me?

Eric Lippert on Monads

**Some things to consider, though:**

* *Do you insist on using a purely functional language?* If you're skilled in both functional programming and game development, maybe you could pull it off. (Even though I'd like to know whether the benefits are worth the effort.)
* *Wouldn't it be better to use functional approach only where necessary?* If you're using an object-oriented (or, more likely, a multi-paradigm) language, nothing's stopping you from using functional style to implement sections which profit from it. (Kinda like MapReduce, maybe?)

Some final thoughts:

* Parallelism: While games *do* use it heavily, AFAIK most of it already happens on the GPU anyway.
* Statelessness: Mutations of state are an integral part of games. Trying to get rid of them might just complicate matters unnecessarily.
* Maybe look at how the functional language F# plays with the object-oriented ecosystem of .NET, if you're interested.

All in all, I think even if it could be interesting academically, I doubt this approach is practical and worth the effort.

# Answer
> 5 votes
What your looking for is FRP game development.

**Some Video Introductions:**

It is 100% possible and preferable to make the core game logic in a purely functional way, the industry as a whole is simply behind, stuck in one paradigm of thinking.

Its possible to do it in Unity as well.

To answer the question a new game state will be updated/created every time something moves, as carmack says in his talk, it's not a problem. The drastic reduction in cognitive overhead that comes from a purely functional, highly maintainable, flexible architecture far out ways the performance hit, if it exists at all.

---
Tags: architecture, functional
---


# Question
Title: Assigning relative force to a projectile fired while orbiting a sphere
Projectile Not Correctly Inheriting Parent Velocity (Unity3D)

So I am trying to incorporate the above person's changes into a script I am making although

1. I'm no great coder and
2. I'm not even sure their solution works best for what I am doing.

Essentially what I have right now is a high speed shooter where the player is being pushed around as a physics object on a sphere world rather than using translate for movement. I keep finding solutions that would work really well if I was just translating through xyz space. Using a physics object for my projectile has been working well (I can shoot in one direction and have the projectile hit my in the back after circling around) but once I get up to speed I'm in trouble.

I think I've successfully incorporated the projectile portion into my script but currently it keeps shooting on the positive z axis.

On top of that, I'm not even sure where to start incorporating the second half.

Emitter Script

```
using UnityEngine;
using System.Collections;

public class SpaceShoot : MonoBehaviour
{
public GameObject Bullet_Emitter;
public GameObject Bullet;
public GameObject target; // Player

public float Bullet_Forward_Force = 100;
public float Bullet_Life = 60;
public float fireInterval = 0.05f;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
        InvokeRepeating("Fire", float.Epsilon, fireInterval);
    if (Input.GetKeyUp(KeyCode.Space))
        CancelInvoke("Fire");
}

void Fire()
{
    GameObject Temporary_Bullet_Handler;
    Temporary_Bullet_Handler = Instantiate(Bullet, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation) as GameObject;

    Rigidbody Temporary_RigidBody;
    Temporary_RigidBody = Temporary_Bullet_Handler.GetComponent<Rigidbody>();

    Temporary_Bullet_Handler.transform.Rotate(Vector3.left * 90);

    Rigidbody target_rigidbody;
    target_rigidbody = target.GetComponent<Rigidbody>();

    Temporary_RigidBody.velocity = target_rigidbody.velocity;

    Temporary_RigidBody.AddForce(transform.forward * Bullet_Forward_Force);

    Destroy(Temporary_Bullet_Handler, Bullet_Life);
}
}

```

Edited script as it currently stands. It mostly does what I need although I'm trying to figure out a way to clamp the distance to the origin.

# Answer
> 0 votes
Figured out how to clamp the projectile's distance from the origin. It's 75% of the way there but that'll do for a Game Jam. https://docs.unity3d.com/ScriptReference/Vector3.ClampMagnitude.html

---
Tags: unity, physics, 3d, rigid-body-dynamics, sphere
---


# Question
Title: Problem with nested if elements in batch file (text rpg)
```
@echo off

:An
@echo Everything has a start...
SET /P _inputname= Please enter your character's name:
SET /P _inputgen= Please enter your character's sex:
set /A hp=10
pause
cls
@echo Your name is %_inputname%
@echo You are a teenage %_inputgen%
pause
cls
@echo This story starts here...
pause
cls
@echo You wake up alone in your room, it's still dark.
@echo 1: Get out of bed
@echo 2: Try to sleep
SET /P _1Dec= What you want to do?
cls
if %_1Dec%==1 (
@echo Now you finally got up. You turned the light on. The first thing you saw was a blinding flash of light.
) else (
@echo You lazily closed your eyes again. It's not morning right now. Why would you get up so early. You managed to fall asleep again easily...
@echo When you finally get up, it's already morning and you can feel all the light even through your closed eyes.But you feel rested and in better mood
set /A hp=%hp%+1
)
@echo Your health: %hp%
pause
cls
@echo Now you can see. But there's one problem. You don't like what you see.
@echo Your mom once said, that you have the most untidy room on the whole world.
@echo But nevermind your mom. The room is quite big, but most of the place is taken by your table, bed and a gigantic wardrobe.
@echo 1: Search around a bit
if %_1Dec%==1 (
@echo 3: Get some sleep
@echo Your health: %hp%
SET /P _2Dec= What do you want to do?
) else (
@echo 2: Go out of your room
@echo Your health: %hp%
SET /P _2Dec= What do you want to do?
)
if %_2Dec%==1 (
@echo First you open your wardrobe.
@echo The first thing you notice (apart from the incredible mess) is a little silver flashlight, currently turned on.
@echo 1: Take it
@echo 2: Let it here
SET /P _2.5Dec= Take it?
if %_2.5Dec%==1 (
set /A flsh=1 >inventory.bat
color 0a
@echo Congratulations! You just received your first item!
@echo Altough it seems basic, use it as wisely as possible…
color 0
) else (
@echo You don’t exactly need a flashlight right now, so why to take it and make your pockets heavier?
)
@echo Once you’ve done everything you wanted, you turn your back on the wardrobe.
@echo You sit to your table, right in front of the giant pile of books and papers.
@echo Taking a look at the book on the top, you recognize a cover of your favourite book,
@echo Looks like you’ll have to sit down and read…
) else (
Pause
)

```

As it gets to the line with if %\_2Dec%==1..it just crashes.. Can someone please tell me why?

# Answer
There are multiple problems here, firstly, the parentheses in one of the echo messages messes up the nesting. You need to surround it with double quotes:

```
@echo "The first thing you notice (apart from the incredible mess) is a little silver flashlight, currently turned on."

```

Secondly, for reasons that are beyond me, the variable `_2.5Dec` expands when the `_2Dec` if statement runs. Since it doesn't have a value by then, it fails and the program stops. You need to use `setlocal enabledelayedexpansion` somewhere before the outer if statement and then use `!_2.5Dec!` in the inner if statement.

You'll also run into quite a bit of trouble later if you use the wrong "apostrophe", \` isn't the same as '

My main advice in using batch is don't.
> 1 votes

---
Tags: windows
---


# Question
Title: How do I fix this "identifier is not declared in the current scope" error?
I got this `identifier inputevenmousebutton is not declared in the current scope`; should I use another identifier?

```
func _ready():
    position = get_viewport_rect().size / 2
    direction.x = rand_range(-1, 1)
    direction.y = rand_range(-1, 1)
    direction = direction.normalized()
    width = get_viewport_rect().size.x
    height = get_viewport_rect().size.y

func _process(delta):
    position += direction * speed * delta
    if position.x < 0 or position.x > width:
        direction.x = -direction.x
    if position.y < 0 or position.y > height:
        direction.y = -direction.y

func _on_UFO_input_event( viewport, event, shape_idx ):
    if event is InputEvenMouseButton and event.button_index ==
        BUTTON_LEFT and event.pressed:
        direction.x = rand_range(-1, 1)
        direction.y = rand_range(-1, 1)
        direction = direction.normalized()
        position.x = rand_range(1, width -1)
        position.y = rand_range(1, height -1)
        speed += 5

```

# Answer
The parser tells you that it is not recognizing this word in the current context.

Some keywords are defined by you, others are defined by the language/framework. In this case, it is one defined by Godot. What should be done, here, is that you should re-read the error message it's giving you; you'll realize that "event" is not spelled right.

Changing `InputEvenMouseButton` to `InputEventMouseButton` should fix this error.

If the word had been one of those that you decided, then you'd have to make sure that all the variable names matched with those you defined. This can create headaches sometimes, and one has to be patient.

> Should I use another identifier?

Given what I said, no, you should find the issue with the identifier you're trying to use, because it's defined by Godot.
> 3 votes

---
Tags: godot, gdscript
---


# Question
Title: How do I hide the bug image once it's hit by a bullet?
I have almost solved my problem. I am able to shoot a bullet and hit a bug and it then draws a collision bitmap. but then it redraws a bug, I want to clear the bug bitmap after the collision happens.

```
public Form1()
{
    InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
    timer1.Interval = 20;
    timer1.Start();
    timer2.Interval = 100;
    timer2.Start();
    this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
int x = 0, y = 0;
Bitmap bug_one = new Bitmap("bug_one.bmp", true);
Bitmap ship = new Bitmap("ship.bmp", true);
Bitmap bullet = new Bitmap("bullet.bmp", true);
Bitmap coll = new Bitmap("coll.bmp", true);
Bitmap black = new Bitmap("black.bmp", true);
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Left)
    {
        x-=5;
        if(x<=-350)
        {
            x = -350;
        }
    }
    if(e.KeyCode == Keys.Right)
    {
        x+=5;
        if(x>=375)
        {
            x = 375;
        }
    }
    if (e.KeyCode == Keys.Space)
    {
        if (y <= -530)
        {
            y = 0;
        }
    }
}
int count = 102;
public void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.Clear(Color.Black);
    e.Graphics.DrawImage(ship, 350 + x, 530);
    e.Graphics.DrawImage(bullet, 375 + x, 520 + y);
    e.Graphics.DrawImage(bug_one, 350, 0);
    if (y <= -510 && x >= -15 && x <= 15 && count > 0)
    {
        e.Graphics.DrawImage(coll, 350, 0);
        count = 0;
    }
}
public void timer1_Tick(object sender, EventArgs e)
{
    y -= 5;
    Invalidate();
}
public void timer2_Tick(object sender, EventArgs e)
{
    count--;
    Invalidate();
}

```

---

This attempt almost works: when a bullet hits a bug it draws a collision image, but then all the bugs are cleared. I only want one bug to be cleared at a time.

```
    public void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(ship, x-25, 530);
        e.Graphics.DrawImage(bullet, x, y);
        if (collision)
        {
            return;
        }
        foreach (Bug bug in bugs)
        {
            e.Graphics.DrawImage(bug_one, bug.px, bug.py);
        }
        foreach (Bug bug in bugs)
        {
            if (x >= bug.px && y >= bug.py && x <= bug.px + bug.width && y <= bug.py + bug.height)
            {
                e.Graphics.DrawImage(coll, bug.px, bug.py);
                collision = true;
            }
        }
    }

```

# Answer
I assume that Form1\_Paint is called repeatedly. Why not add some kind of flag indicating that a collision happened, and just avoid drawing the image?

```
public void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.Clear(Color.Black);
    e.Graphics.DrawImage(ship, 350 + x, 530);
    if (collisionHapened) {
        return;
    }
    e.Graphics.DrawImage(bullet, 375 + x, 520 + y);
    e.Graphics.DrawImage(bug_one, 350, 0);
    if (y <= -510 && x >= -15 && x <= 15 && count > 0)
    {
        e.Graphics.DrawImage(coll, 350, 0);
        count = 0;
        collisionHappened = true;
    }
}

```

If you want to really clear the bitmap, which is a relatively slow operation, use MakeTransparent and then set the each of the bitmap's pixels' alpha to zero (see example).

On a side note, consider not relying on global state, and instead pass to each method its required parameters. If the behavior of a method fully relies on its arguments instead of on global state, it's significantly easier to understand why erroneous behavior happens.
> 1 votes

# Answer
```
        public void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(ship, x-25, 530);
        e.Graphics.DrawImage(bullet, x, y);
        foreach (Bug bug in bugs)
        {
            if (bug.collision==false)
            {
                e.Graphics.DrawImage(bug_one, bug.px, bug.py);
            }
        }
            foreach (Bug bug in bugs)
            {
                if (x >= bug.px && y >= bug.py && x <= bug.px + bug.width && y <= bug.py + bug.height)
                {
                    e.Graphics.DrawImage(coll, bug.px, bug.py);
                    bug.collision = true;
                }
        }
    }

```

I finally got my code to work properly it draws a bug then it gets hit by a bullet and then it draws a collision image and then disappears, just like I wanted it to do.
> 0 votes

---
Tags: c#, windows-forms
---


# Question
Title: Error in the order of the target points to be followed. How to set the order of elements in an array?
I have a project where it has **1 NPC** and **3 target points**:

In the project I set the NPC to go to target point 1, then to 2, then to 3.

**Expected path:**

**Path that is occurring:**

This problem did not happen out of nowhere, but first I will explain the **creation of the target points**.

I created the first target point, added the components it needed, and then replicated it. Selecting the first target point and pressing **CONTROL + W**. I positioned the second target point, and then, again selecting the first target point, I again replicated it.

The order of the path was as expected. I modified some code (**none of the codes I modified related to the NPC or target points**). After that I created a new target point (replicating it from the first target point) and then my problem started.

The NPC was initially going to target point 3, to the 4, 1 and then 2.

Even excluding target point 4, the order did not return to the expected (1, 2 and 3).

I inserted a print after the loop that causes the NPC to move toward the target points, so I could figure out the order of the target points, and it is making sense with the order of the path that is taking place.

**Blueprint + Print:**

*3 to 1 to 2.*

**I created 2 more target points, and see how the order changes without any sense:**

*4 to 5 to 1 to 2 to 3.*

**I added another 1 target point to see if it meets a pattern:**

No sense at all.

**I'd like to know how to set the order of target points in the array.**

---

**EDIT 1 (Root of the problem)**

From what I researched, I came to the conclusion that the problem is due to the function **Get All Actors Of Class** (*that I use to make the NPC follow the target point*):

It was also researching that I discovered that I can search for a specific actor using **tags**.

Link where I made the discovery:

https://docs.unrealengine.com/en-us/Gameplay/HowTo/FindingActors/Blueprints

But this feature does not serve me, because I do not want to establish an exact number of target points, I would like the order of the path to be given by the name of the target points or at least by the creation order.

---

**EDIT 2 (today opening the project again, the order is correct)**

**Correct order:**

I suspected that if I added new target points, the problem would come back, but that was not what happened.

**Again the order is correct:**

*Even so, I'd like you to tell me if there is any way to know all the elements of an array, and thus be able to treat, set, and order them. For this problem may occur again at some crucial moment.*

# Answer
> 0 votes
Create an array of type actor.

**Name the target points the way you prefer (I would recommend TP + his number):**

**Use the Get All Actor of Class to receive all the target points and then add to the vector you created:**

From the vector you created, you use a loop. With an integer variable with the initial value of 1 (in my case) you use an append, with the name you put in your target points without the number. The number will be defined by this integer variable.

**Below the loop that defines the target to be followed:**

**When the NPC collides with a target point, just increase the value of the integer variable and restart the loop that defines the target to be followed:**

---
Tags: ai, unreal-4, path
---


title: Destroy chunked block like Minecraft

text:
# Question
Title: Destroy chunked block like Minecraft
I am trying to do a Minecraft-like game (like every one have already tried I guess) and i went across the problem i expected: lag with world Generation. I did lot of searching but i can

I tried to combine them into a bigger mesh, which work, but not i can destroy a single block. So how can I place/destroy chunked (mesh combined) block? If i cant, can someone clearly explain me a solution (i am not fluent in english nor with programming expressions, i can code tho) and how to do it (with a script example if possible :) ) ? Thanks in advance !

I generated my world using 2D perlin noise. Once i have the blocks, i split them into 16x16x100 chunk meshes.

Before Making chunks, i first tried to combine all of them into one block (using the unity manual), but the result is only one cube placed at 0,0,0. Where are all the other cubes ?

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ThisWorldGen : MonoBehaviour {

public GameObject blockPrefab;
public GameObject grass;
public GameObject dirt;
public GameObject rock;
private string[] blockTag;
private GameObject stockin;

public int amp;
public int freq;
private Vector3 mypos;
[SerializeField]
private Material material;
private Vector3 blockLocations;

public List<MeshFilter> meshes = new List<MeshFilter>();

void Start()
{
    Generate();
}

void Generate()
{
    amp = Random.Range(0,100);
    freq = Random.Range(30,100);
    mypos = this.transform.position;
    int cols = 100;
    int rows = 100;
    float startTime = Time.realtimeSinceStartup;
    #region Create Mesh Data
    MeshFilter blockMeshes = Instantiate(blockPrefab, Vector3.zero, Quaternion.identity).GetComponent<MeshFilter>();

    for(int x = 0; x < cols;x++)
    {
        for(int z = 0; z < rows;z++)
        {
            float y = Mathf.PerlinNoise ((mypos.x + x) / freq,(mypos.z + z)/freq) * amp;
            y = Mathf.Floor(y);
            for(float hy = y; y > 0.0F; y -= 1.0F)
            {
                blockMeshes.transform.position = new Vector3(mypos.x + x,y,mypos.z +z);//move the unit cube to the intended position
                meshes.Add(blockMeshes);
            }
        }
    }
    int i = 0;
    MeshFilter[] listMeshes = new MeshFilter[meshes.Count];
    foreach(MeshFilter cubesToAdd in meshes)
    {
        listMeshes[i] = cubesToAdd;
        i++;
    }
    CombineInstance[] combine = new CombineInstance[listMeshes.Length];
    int w = 0;
    while(w < listMeshes.Length)
    {
        combine[w].mesh = listMeshes[w].sharedMesh;
        combine[w].transform = listMeshes[w].transform.localToWorldMatrix;
        listMeshes[w].gameObject.SetActive(false);
        w++;
    }
    Debug.Log (combine.Length);
    transform.GetComponent<MeshFilter>().mesh = new Mesh();
    transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
    transform.gameObject.SetActive(true);
    #endregion
    Debug.Log("Loaded in " + (Time.realtimeSinceStartup - startTime) + " Seconds.");
}
}

```

(the world was generating randomly and perfectly before trying to merge the meshes)

# Answer
If you combined all of your blocks into a single mesh, then in order to remove a single block you'll need to generate a new mesh without the block, or depending on your game engine, adjust the vertices of your mesh to account for the missing block.

Given a large enough mesh, both solutions are likely to be very slow. Combining a lot of objects into a single mesh isn't very performant when each object is individually modifiable. Consider batching several blocks into smaller meshes, thus reducing the cost of the destruction of each block, or profiling your initial world generation in order to understand where is performance bottleneck, and optimizing around it. For example, you could evaluate the world lazily, and thus only compute the minimal set of necessary blocks.
> 1 votes

---
Tags: unity, c#, open-world, block-world
---


# Question
Title: How do I rotate individual shapes on an html5 canvas?
So I am doing a basic Asteroids clone as an intro to HTML5 canvas. I want to be able to rotate the main player while leaving the other objects on screen alone. Currently I am using transform and rotate on the canvas to allow the player to move, which works well.. but since it rotates the entire canvas it affects other shapes on screen. Is the general way to do this, to instead have each shape keep track of its own positions and perform manual transformations on the shape itself while leaving the canvas alone? Can I possibly give my shape a CSS class and control it on its own that way? Should I be using more than 1 canvas so that I can control rotations individually? Not sure what the accepted way is to handle multiple on screen images/shapes all with their own movement and rotation patterns simultaneously. My gut is telling me to have each shape track its own positions and just perform the math on the shape object itself... but then I would not be using the Canvas APIs rotate at all.

My app currently: https://jsfiddle.net/0o2pwLhn/

And a code snippet for the rotation:

```
// player draw test
    function drawShip() {
        ctx.beginPath();
        ctx.moveTo(shipStartX, shipStartY);
        ctx.lineTo(shipStartX + 8, shipStartY + 20);
        ctx.lineTo(shipStartX, shipStartY + 15);
        ctx.lineTo(shipStartX - 8, shipStartY + 20);
        ctx.lineTo(shipStartX, shipStartY);
        ctx.translate(shipStartX, shipCenterY);
        ctx.rotate((Math.PI / 180) * shipMoveDegree)
        ctx.translate(-shipStartX, -shipCenterY);
        ctx.stroke();
        ctx.closePath();
    }

```

Do the save() and restore() methods on the CanvasRenderingContext2D maybe come into play here? I have tried experimenting with it but havent gotten anywhere. I tried using save() and restore() but the issue is that once I restore, the player just gets set right back to its original spot.. since I am never actually changing its position... just rotating the entire canvas. The similar question here Is it possible to rotate an image on an HTML5 canvas, without rotating the whole canvas? explains how to use save() and rotate() which I think is on the right track.. but does not solve the issue I have because the player location is reset back to the start when the key is lifted, because I set the degrees back to 0 on keyup. How can I maintain the current rotation of a single shape regardless of the rest of the canvas?

# Answer
You should not use the translate method to change the position of the player between frames. Change the `shipStartX` and `shipStartY` variables to move the ship and store the current rotation somewhere. This not only gives you a better control over everything, but you won't be able to easily determine collisions with the translate method
> 1 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Smooth shading along edges with duplicate vertices
On this generated mesh, I have sharp edges, because each square has duplicate vertices separate from its neighbours.

I can't remove the duplicate vertices because I'm using them to provide unique UV texture coordinates on each square. If I share the vertices then the texture wraps around the surface in an unwanted way.

Is there a way I can get smooth shading along these edges, even without shared vertices?

# Answer
You don't need to remove duplicated vertices, smooth lighting doesn't come from triangles sharing vertices. You just need to set the normals correctly.

First I'd go through every triangle and set the normals of the vertices of the triangle to the normal of the triangle, then go through every vertex pair, check if their positions are the same and if they are, set their normals to the average of their current ones.
> 0 votes

---
Tags: unity, c#, mesh, shading
---


# Question
Title: On changing a voxel, don't recombine everything again, only modify the changed parts?
I'm working on a **voxel based game**, where **destructible structures** are made out of **cubes**. (Some of them has 3000 voxels)

I solved the **framerate issues by combining them**, but after making it able to handle multiple materials, **calling the method** causes a **framerate drop**.

* And it's annoying during runtime, because currently it **recombines the whole** structure when **a voxel is changed** (changed material, destroyed voxel, etc).

One plan of mine is to decomposite the structures into **smaller chunks**, and only recombine the affected chunks instead of the whole structure.

* This increases drawcalls, but decreases framerate drops. By finding a good chunk size and chunk "making" heuristic, it would work I think.

My other plan is to **modify the combined mesh** based on the affected voxels.

* For example when a voxel is destroyed, find its vertices in the combined mesh, and remove them. Or change those faces' material, etc.
* But I don't know how to do this.

The bottleneck of my mesh combining algorithm is this:

```
private static Mesh CombineMeshes(MeshFilter[] meshFilters, List<Material> materials)
{
    // Each material will have a mesh for it.
    var subMeshes = new List<Mesh>();
    foreach (var material in materials)
    {
        // Make a combiner for each (sub)mesh that is mapped to the right material.
        var combiners = new List<CombineInstance>();
        foreach (var meshFilter in meshFilters)
        {
            // The filter doesn't know what materials are involved, get the renderer.
            var renderer = meshFilter.GetComponent<MeshRenderer>();  // <-- (Easy optimization is possible here, give it a try!)

            // Let's see if their materials are the one we want right now.
            var sharedMaterials = renderer.sharedMaterials;
            for (int i = 0; i < sharedMaterials.Length; i++)
            {
                var sharedMaterial = sharedMaterials[i];
                if (sharedMaterial != material || sharedMaterial == null)
                    continue;
                // This submesh is the material we're looking for right now.
                CombineInstance ci = new CombineInstance();
                ci.mesh = meshFilter.sharedMesh;
                ci.subMeshIndex = 0; //With zero it works; with "i", every voxel in the structure will have every damagelayer.
                ci.transform = meshFilter.transform.localToWorldMatrix;
                combiners.Add(ci);
            }
        }
        // Flatten into a single mesh.
        var mesh = new Mesh();
        mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
        mesh.CombineMeshes(combiners.ToArray(), true);
        subMeshes.Add(mesh);
    }

    foreach (var meshFilter in meshFilters)
    {
        meshFilter.GetComponent<MeshRenderer>().enabled = false;
    }

    // The final mesh: combine all the material-specific meshes as independent submeshes.
    var finalCombiners = new List<CombineInstance>();
    foreach (var mesh in subMeshes)
    {
        CombineInstance ci = new CombineInstance();
        ci.mesh = mesh;
        ci.subMeshIndex = 0;
        ci.transform = Matrix4x4.identity;
        finalCombiners.Add(ci);
    }
    var finalMesh = new Mesh();
    finalMesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
    finalMesh.CombineMeshes(finalCombiners.ToArray(), false);
    return finalMesh;
}

```

Could you recommend something? Thanks!

# Answer
You are on the right track to producing an efficient voxel game by combining meshes into a single mesh, but this approach isn't perfect. You have already encountered one problem, where the relatively large meshes take a noticeable amount of time to regenerate, thus creating an FPS drop. Another problem is that the number of meshes scales with the type of blocks, instead of the rendered area. Additionally, you may be rendering extra faces that aren't visible to the player as they are between blocks. For example, if there is a 2x2x2 cube of blocks, then the inner faces (12 total) won't ever be visible to the player, but it is easy to make the mistake of rendering them anyway. A solution to these problems is to use custom chunk meshes with a texture atlas or texture array instead.

Basically, this technique involves splitting the world into square chunks. Minecraft uses 16x16x256 (ordering x, y, z), but other values can work as well. There is a mesh for each chunk and this mesh contains *all* blocks in that chunk, of every material/type. To accomplish this, a texture atlas is used in combination with texture coordinates to specify different parts of the texture.

To modify your game to use the aforementioned chunking technique, it is necessary that it operate in a particular way. Specifically, the block data must be stored in some sort of data structure other than the objects in Unity's scene graph. A three dimensional array of block types for each chunk is a decent choice, however, it is often easier to reason about the memory layout of a 3D-indexed single dimensional array. Memory layout is important for CPU cache efficiency and can make writing or loading chunks to and from files easier too if the chunk data is ordered in a way that is amicable to compression. In addition to this type of data structure to store block data, you need to write custom code to create the mesh. Usually, this involves looping over the block type array and adding faces to a mesh depending on what blocks you encounter in the loop. Cursorily looking around, this appears to be the relevant class in the free and open source minetest, if you want to see a working example.
> 1 votes

---
Tags: unity, optimization, 3d-meshes, voxels, mesh
---


title: How could I implement an ECS in C?

text:
# Question
Title: How could I implement an ECS in C?
I'm looking into how to do a game engine using only C and wanted to know how to implement ECS in C.

I didn't find any ECS implementation for C, it only seems to exist for C++.

So I'm wondering... Is it possible to implement such a feature?

And if so, how to implement such a pattern in C?

# Answer
> 11 votes
As a pattern ECS and data oriented programming in general are closer to pure C than C++.

Entity component systems consist of three major elements.

* Components are simply holding data; they shouldn't hold any logic. A simple struct should be enough to model them in C.
* Systems is where all your logic lives.
* Finally, Entities don't hold anything (logic or data). They are conceptually just a way of connecting components together. These can be represented as an ID in the component.

As an example you may have a game where your entities can have two components. A position component and a health component. These can be represented as two structs. Both structs hold an entity\_id.

```
struct Position
{
    int entity_id;
    int x;
    int y;
};

struct Health
{
    int entity_id;
    int current_health;
    int max_health;
};

```

For every different type of component you need a list or an array of that component. To make things simpler I put everything in a single struct, sort of the root of the ECS. Also, for simplicity I am using just a member array. You may need to consider a better approach like a binary tree where the key of each node is the id of the component's entity.

```
struct ComponentLists
{
    Health health_components[100];
    Position position_components[100];
    int total_health_components;
    int total_position_components;
};

```

Based on these data structres you could define your systems as simple stateless functions. In ECS systems are meant to represent transformations that change the state of a component.

```
// a simplistic way of creating a new entity
void create_entity(ComponentLists* components)
{
    int id = ENTITIES++;// global number of entities
    components.health_components[id].entity_id = id;
    components.total_health_components++;
    components.position_components[id].entity_id = id;
    components.total_position_components++;
    //initialise any other variable here
}

void update_health_system(Health* h, ComponentLists* components)
{
    if(h->current_health <= 0)
    {
        kill_entity(components, h->entity_id);// this will remove all components that refer to that entity_id
    }
}

void update_position_system(Position* p, ComponentLists* components)
{
    if(p->y <= 0)
    {
        // for simplicity's sake we assume that the id is the index.
        // In a real world example this won't be enough.
        // You may want to use a different data structure instead like a hash map or a binary tree.
        Health* h = components.health_components[p->entity_id];
        h->current_health--;
    }
}

```

Putting everything together, this is how a main loop could look like.

```
void main_loop()
{
    ComponentLists components;

    create_entity(components);
    create_entity(components);

    while(1)
    {
        /*Now you can update each system one by one*/
        for(int i = 0; i < components.total_position_components; ++i)
        {
            update_position_system(&components.position_components[i],components);
        }

        for(int i = 0; i < components.total_health_components; ++i)
        {
            update_health_system(&components.health_components[i],components);
        }
    }
}

```

---
Tags: c, entity-component-system
---


# Question
Title: Shader is distorting a Texture of a sprite it's working on
I've been testing out fragment shaders in SFML, trying to learn how to write and use them and I've run into a recurring problem. Every shader distorts the texture.  Top left is the distorted test texture, top right and bot left are there for comparison along the axis.

The texture is 512x512 pixels in size and the sprite has the same dimensions. I've narrowed down the problem to this line.

```
vec2 texCoord = (gl_FragCoord.xy / sourceSize.xy);

```

Where sourceSize is the resolution. The value I'm passing in being (512,512). I've tested around with different values, the closest to the correct output is when I pass in the values (512, 1086) giving this.

Top left is the distorted texture. The X axis is correct but the Y axis is stretched enough to hide the numbers and enlarge the border.

Currently the shader does nothing for testing purposes.

```
uniform sampler2D       source;
uniform vec2            sourceSize;
uniform float           time;

void main( void )
{
        vec2 texCoord = (gl_FragCoord.xy / sourceSize.xy); //Value between 0.0 and 1.0
        texCoord = vec2 (texCoord.x,1.0-texCoord.y);    //Inverts the y component. GLSL treats bot left corner as the origin, sfml treats top left as it.
        vec4 Color = texture2D(source, texCoord);

        gl_FragColor = Color;
}

```

I'm not sure how to fix this. What I'm trying to achieve is a shader that doesn't distort the base texture so I can build on from there. Thanks for any help you can give.

# Answer
When you're writing a fragment shader, you aren't doing anything in a holistic manner. You don't care about the forest. All you care about is the tree you're looking at right now.

In that sense, if you're doing anything that involves the resolution of a texture or a screen, the relevant calculations (usually) happen outside of the fragment shader. The shader (usually) doesn't care how many pixels a screen has, or how many texels a texture has. It only cares about whatever coordinates it has been provided to render things at this exact pixel on the screen, right now.

I am not well acquainted with SFML, and I don't know how you've set up your scene here, but if you're displaying a quad you've created, then when you create the mesh for it, you typically set "UVs" or "texcoords" for each of the vertices. Texture coordinates are a suggestion to the engine about how it should position a texture over the surface of a mesh. These are not the only way to communicate to a fragment shader where to put a texture, but they are by far the most common way to accomplish this.

In SFML shaders, you would normally find the texture coordinate being rendered at the current position with `gl_TexCoord[0].xy` (as noted here: https://www.sfml-dev.org/tutorials/2.5/graphics-shader.php).

My recommendation is that you:

1. Make sure that you're setting proper texture coordinates on any geometry that you're rendering.
2. Use `gl_TexCoord[0].xy` to do your texture coordinate lookup.
> 2 votes

---
Tags: c++, shaders, glsl, sfml
---


# Question
Title: Unity3D: Efficiently loading chunks in an infinite voxel engine
I'm developing a voxel engine in C# using Unity and I'm currently trying to implement infinite terrain, so I took a look at other Unity voxel engines that have infinite terrain. I've seen three different ways of doing it:

1. Using a dictionary to store the chunks and store the block data in another dictionary
2. Using a dictionary to store the chunks and store the block data on every chunk
3. Using a fixed size array and shifting it every time the player moves

The engines using approach 1 and 2 were pretty slow at chunk loading. The engines using approach 3 were faster but produced lag every time the player entered a new chunk.

I've already tried to implement it using approach 1, but my chunk loading speed got slower by about 10 times, so it was really unplayable.

How is it done in efficient or popular voxel engines like Minecraft or VoxelFarm? Do you have experience with voxel rendering and know a better approach?

Thanks in advance!

# Answer
*Non sequitur*, your question does not entirely make sense. You cannot *store* infinite chunks. You can only ever store the subset that is currently of interest, i.e. those around the player(s).

So how does the infinite part work? You generate chunks according to some global function. For example, Minecraft's use of Perlin noise (a global function) means that any given `[x,y,z]` location can be generated deterministically; changes which were applied at that voxel location are then applied following each deterministic regeneration of that location (more typically, of its parent chunk).

Now we get to the meat of your question -- the Area of Interest (AoI) around the player. Storing these can be done in many different ways, some of which you touch on. Let's look at those.

What is the difference between shifting a 2D array (approach 3) and using a dictionary? A 2D array is used when each of a bunch of **closely-packed** `[x,z]` locations are expected to be filled with valid chunks at all times, representing the current AoI; this is a *dense* collection. Think about that; it may well be all you need (I believe this is how MC works). OTOH, a dictionary is used when you need a *sparse* collection, i.e. *data in memory* is contiguous, but your *chunks in world space* are not, that is they are at non-adjacent chunk coordinates.

As for using chunk values (structs) vs references (pointers) to chunks that are stored elsewhere, this is typically a matter of flexibility. Using an array of values is faster *for reading* than using an array of pointers, because in the second case you have to not only index into the array, but you (or rather the Mono runtime) then still have to JMP to another location in order to get the chunk data; cost thereof may or may not be negligible depending on how well or poorly you have packed your data. Using an array / dictionary of pointers can be better for writing, because all you have to do then is change the pointer to another location, bearing in mind that you then pay a read-performance penalty. The other aspect to using references (for C#, nullable types) is that you can have null chunk references if you require them.

Your approach 1 is probably not very efficient because besides having to do lookups in two dictionaries (why?) you also have to do multiple jumps to get to the chunk data.
> 5 votes

# Answer
A great explanation of a well known voxel chunk system can be found in the minecraft wiki

Regardless of how you want to store the data programmatically, the ability to generate smooth flowing infinite voxel terrain comes down to a smartly optimized neighbouring chunk loading system.

"The exact number of generated chunks varies in single player mode, depending on view distance and movement. In multiplayer mode, a grid with a default inradius of 10 (for a total of 21x21 or 441) chunks is loaded around each player and sent to the player by default, although this can be configured to be between 3 and 15, usually only lowered with a poor connection home server. These chunks may have activity (mobs spawning, trees growing, water flowing, dropped items disappearing etc.), while the other world chunks are inactive, stored on your hard drive. Chunks will not save again if they were saved in the last 30 seconds."

So effectively in a player driven game like minecraft you're only ever creating/loading a small number of chunks around your player at any time.

It's quite tough to troubleshoot your slow chunk loading issue without more information or code examples etc.
> 3 votes

# Answer
I'm also creating a voxel engine in unity, and I found to be most efficient to store blocktype data in struct (and load them from, for example XML or ini file, so you can make mods), and for chunk info, just store BlockID (I use ushort for that). Then create job system for rendering those if you don't really care about custom meshed blocks, since you'll have to store all meshinfo somewhere and somehow, and ECS is not yet recommended.

This way I can get 16^3 chunks of 16^3 blocks generated and rendered in like three or four frames at 10fps, or delayed ~10sec for whole thing to render @60fps

If you go for infinite world, it gets even better, since a single chunk renders at around 200ms and it's multithreaded, so you almost can't feel that there's heavy math in background since it renders instantly.

Edit: chunks are separated gameobjects, they store array of ushort\[chunksize^3\], each chunk generates and renders itself in their own job, so just convert ushort\[\] to NativeArray and back after job's done.
> 0 votes

---
Tags: unity, terrain, voxels
---


# Question
Title: How to disable BoxCollider2D on all prefabs?
I made a prefab that when hitting one object will disable it's box collider2d and enable it after hitting a different object.

It works find when there's one prefab, but when there's move, it only works on a single instance of the prefab and non of the others.

How do I set it to disable every box collider2d on every prefab object of that type? Thank you!

```
public void ChangeGreen()
{
     //Turns box collider2d on
     ColorBlockerController blockerScript = GameObject.FindGameObjectWithTag("PinkBlockerTag").GetComponent<ColorBlockerController>();
     blockerScript.PinkBoxOn();
}

public void ChangePink()
{
     //Turns box collider2d off
     ColorBlockerController blockerScript = GameObject.FindGameObjectWithTag("PinkBlockerTag").GetComponent<ColorBlockerController>();
     blockerScript.PinkBoxOff();
}

```

# Answer
You can use GameObject.FindGameObjectsWithTag which will return all the similar gameobject and iterate though it

```
GameObject[] goWithSameTag = GameObject.FindGameObjectsWithTag("TagNAme");
foreach(go in goWithSameTag)
{
    go.GetComponent<BoxCollider2D>().enabled = false;
}

```

Alternatively you can cache these objects in an array at the start of game so you don't have to run call `GameObject.FindGameObjectsWithTag` everytime you are enabling/disabling the collider.
> 2 votes

# Answer
`FindGameObjectWithTag` works, but it is slow when you have a lot of objects.

You may find this event-based solution useful:

```
public class Whatever {
    private bool state;
    public event Action <bool> onStateChange;

    public bool State {
        get { return state; }
        set {
            state = value;
            onStateChange?.Invoke (value);
        }
    }
}

```

Store it in a static field or make its members static.

When you spawn a prefab, it first reads `State` and decided to enable collider or not, and subscribes to event:

```
whatever.onStateChange += SetColliderState;

```

In that handler you can do anything you want. For example:

```
private void SetColliderState (bool state) {
    boxCollider.enabled = state;
}

```

**Don't forget to unsubscribe in OnDestroy! If you don't, the object will not be garbage collected, and its handler will stay and be called forever!**
> 2 votes

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


# Question
Title: Check if all tagged GameObject are destroyed
Hello im a total noob so please dont blame me. So, I have this code but I cant find a fitting answer on how to check if everything tagged "Target1" is destroyed. Most of the answers are either overcomplicated or ,and most certainly, im too stupid

```
public Transform teleportTarget;
public GameObject thePlayer;
public Transform[] spawnLocations;
public GameObject[] whatToSpawnPrefab;
public GameObject[] whatToSpawnClone;

void spawnTargets()
{
    whatToSpawnClone[0] = Instantiate(whatToSpawnPrefab[0], spawnLocations[0].transform.position, Quaternion.Euler(0, 180, 0)) as GameObject;
    whatToSpawnClone[1] = Instantiate(whatToSpawnPrefab[1], spawnLocations[1].transform.position, Quaternion.Euler(0, 180, 0)) as GameObject;
    whatToSpawnClone[2] = Instantiate(whatToSpawnPrefab[2], spawnLocations[2].transform.position, Quaternion.Euler(0, 180, 0)) as GameObject;
    whatToSpawnClone[3] = Instantiate(whatToSpawnPrefab[3], spawnLocations[3].transform.position, Quaternion.Euler(0, 180, 0)) as GameObject;
}

private void TeleportPlayer()
{
    thePlayer.transform.position = teleportTarget.transform.position;
}

```

Im just looking for a way to check if all GameObjects Tagged "Target1" (in the whole game) are destroyed and then to spawnTargets and TeleportPlayer. Previously I had the bug, that when they respawned it wasnt checking anymore. It has to check all the time.Because else I get stuck, because teleport teleports me all the time. I hope you understand what I mean

I know this is a easy question but im a noob and im sorry for wasting your time, still I hope you can help me.

# Answer
> 2 votes
I want to check if all GameObjects tagged "Target1" have been destroyed, call a function like what you want for example instantiate something and etc...

here is code that you want:

```
void Update(){
    if(GameObject.FindGameObjectsWithTag("Target1").Length <= 0)
        //call your function to spawn targets and teleports
}

```

# Answer
> 3 votes
I'd recommend not using tags for this, as searching for matching tags is an unnecessary cost.

Instead, as I described in this related question, I'd recommend creating a `MonoBehaviour` that marks the objects you want to count, something like this:

```
public class CountedObject : MonoBehaviour {

    public static int count { get; private set; }

    public static event System.Action AllObjectsDestroyed;

    void Start () {
        // Count every object as it's initialized.
        count++;
    }

    void OnDestroy () {
        // Decrement the count when objects are destroyed,
        // and optionally fire an event when the last one is gone.
        if (--count == 0 && AllObjectsDestroyed != null)
            AllObjectsDestroyed();
    }
}

```

The `static int count` variable is shared among all the marked objects. Every time one enters the scene with `Start()` it increases, and every time one is `Destroy()`ed, it decreases.

The only time you ever need to check if all objects have been destroyed is when actually processing the destruction - we don't need a script checking for it every frame in Update.

Another script that's interested in getting called when the last object has been destroyed can subscribe to the event, like so:

```
CountedObject.AllObjectsDestroyed += OnAllDestroyed;

```

Where `void OnAllDestroyed() { ... }` is the function you want to call once the last object is gone.

If you want to track/display a count, you can access it with no searching or extra computation or memory allocations, just by asking for:

```
CountedObject.count

```

# Answer
> 1 votes
You already seem to keep an array of objects you spawned from the script in `whatToSpawnClone`. So you can use that array to check how many of them are still alive. You can check if a game object is destroyed by comparing it to `null`. GameObject has a special overload for the ==-operator which which returns `true` when you compare a destroyed object to `null`.

Here is a method you can add to the behaviour which contains the code snippet from the question which checks if all the spawned objects are destroyed.

```
private bool AtLeastOneCloneAlive() {
     foreach(GameObject o in whatToSpawnClone) {
         if (o != null) return true;
     }
     return false;
}

```

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


# Question
Title: Light settings in UI scene override settings of game scenes loaded additively
I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the game objects and models and ... the light.

So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive).

Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ...

So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override?

# Answer
Maybe this is a kind of workaround.

Keep level scene as principal scene with baked lights. Ignore LoadLevelAdditive that seems useful for other stuff ("This is useful for creating continuous virtual worlds, where more content is loaded in as you walk through the environment.")

Keep the UI scene as for developement but put all the scene tree under a root (say UIRoot) node. When you modifiy UI schene export or store UIRoot as prefab. From level scene reference UIRoot prefab.
> 2 votes

# Answer
I have faced this issue earlier , and found a nice solution too :)

**Procedure:**

* Make different scenes for all the levels.
* Put all the game objects inside an empty parent.(optional)
* Bake the Light Maps for all these individual scenes.
* Unity will create a folder with the scene name in which you can find these light maps.
* Now drag and drop all the light maps and the objects into the resources folder.
* You can now delete the level scenes as they wont be needed anymore.
* Now when you want to LoadLevelAdditive , you instantiate the prefab which holds the object for a particular level and assign the light maps programatically.

Here is the code :)

```
    //Load Level Model
    GameObject prefab = Resources.Load ("LevelPrefabs/Level"+level_name+"Prefab") as GameObject;
    GameObject instance = Instantiate(prefab, Vector3.zero, Quaternion.identity ) as GameObject;

    //Load LightMap
    LightmapData[] lightmapData = new LightmapData[2];

    lightmapData[0] = new LightmapData();
    lightmapData[0].lightmapFar = Resources.Load( "LightMaps/Level" +level_name + "/LightmapFar-0", typeof(Texture2D)) as Texture2D;
    lightmapData[1] = new LightmapData();
    lightmapData[1].lightmapFar = Resources.Load( "LightMaps/Level" +level_name + "/LightmapFar-1", typeof(Texture2D)) as Texture2D;

    LightmapSettings.lightmaps = lightmapData;

```

The light map array length depends upon how many light maps are baked for the scene , accordingly you have to tweak the code.
> 2 votes

# Answer
If you have multiple scenes loaded in the editor, you must change the one from where you want to use the settings to the *active scene*.

So if you have both UI and level scene, and want to bake lights to the level scene, make it active first and bake then.

This is documented in https://docs.unity3d.com/Manual/MultiSceneEditing.html
> 1 votes

# Answer
My experience may be a bit of a corner case but my lightmaps stopped working via additive scene loading when I had a blank skybox (no material set via the editor) that was cached and then set via:

```
_oldBlankSkybox = RenderSettings.skybox; // RenderSettings.skybox was not set

// then, at a later date:
RenderSettings.skybox = _oldBlankSkybox; // the skybox was reset to the blank one from above
// lightmaps following this do not load correctly

```
> 1 votes

# Answer
This has been commented on via

http://forum.unity3d.com/threads/gi-global-illumination-load-level-additive-rendering-issues.310452/

LoadLevelAdditive is supported for lightmaps like in 4.x but currently not for Realtime GI.

We are working on making this work for both lightprobes + realtime GI.

The approach we are going for is: * You load all scenes that you will load together via EditorApplication.LoadSceneAdditive * Then you bake

Unity will then split the data based on which scenes require it and load enlighten systems based on what it needs for the active set of scenes.
> 0 votes

---
Tags: unity, lighting, scene
---


# Question
Title: How to get projectile direction vector in a 2d grid?
I am having trouble figuring out how to trace the path of my projectiles in an Asteroids clone. Currently the ship is locked to the center of the screen and can be rotated a full 360 degrees. I know the angle the ship is pointing at any given time, but I am not sure how to calculate the vector that the projectile should use for its trajectory. I know that I can find the correct vector by subtracting the end point from the start point.. but the issue is that I do not know the end point. Theoretically.. the end point is whenever the projectile touches the edge of the screen or some object. This is the current game code: https://jsfiddle.net/m6sxrk8w/ just using a hardcoded movement vector of {x:-1, y:-1}. Can anyone give some advice on how to dynamically determine the true vector given the current direction of the ship? There must be some simple math I am missing here...

# Answer
To find the unit vector from the angle you want to use cosine(angle) for the x-component and sin(angle) for the y-component. The angle must be in radians. You can convert from degrees to radians by dividing degrees by 180 * PI.

```
radians = degrees / (180 * Math.PI);
x = Math.cos(radians);
y = Math.sin(radians);

```
> 2 votes

# Answer
This is a maths problem that I had myself a few years ago.

You have two 2d vectors in pixel coordinates: shootOrigin=(centerX,centerY); mousePosition=(mouseX, mouseY); shootDirection = Vec2.Normalize(mousePosition-shootOrigin);

The normalization of the 2d vector is very important here to get the bullets to travel at constant speeds. when shooting a projectile you just say bulletPos=bulletPos+shootDirection; every update frame and then check if the Vector2.Distance(bulletPos,enemyPos); from enemy to bullet is smaller than certain value.

I totally recommend you to read the first chapter of the book "Programming Game AI by Example" because its about the maths behind npc agents and basically how to use vectors for game development.

**EDIT**: I just saw its about rotating the ship with keyboard input so you just modify the angle of the ship instead of using the mouse as the shooting direction and therefore need to calculate the direction vector x,y from radians angle like suggested. The principle stays the same: calculate the **normalized** direction vector and apply it every frame to the bullets position. If you spawn a bullet it is even better if you create an bullet object that knows its velocity, direction and has an updateMove method implemented, otherwise your bullets will be rotated while flying because the direction might change through user inout (arrow keys).
> 1 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Handling RPG (rocket launcher) launcher and rocket
In my game, the player has an RPG (rocket launcher). Using this launcher, he can shoot a rocket.

When shown in the inventory, the rocket is stuck in the launcher. Also, when the user walks, the rocket is stuck in the launcher, and the RPG (the combination of launcher and rocket) is placed on his back.

Now when the user shoots, the rocket leaves the launcher, and the launcher pulls the player into a little spin to simulate a recoil.

Since the rocket and the launcher are stuck together most of the time, I was thinking that I should have a main game object named "RPG" with the 2 meshes "launcher" and "rocket". Most of the time, they would be stuck together.

When the user launches the rocket, I would change the position of the rocket in order to simulate it flying away. When it has exploded, I would make the rocket mesh invisible.

I was really proud of that plan until I noticed that the recoil will move the rotation and position of the RPG (launcher). Imagine the recoil of a pistol: The recoil will cause the pistol (and the hands) go up a bit.

Now when I do this with the launcher, the rocket will change its flight path. That would look unrealistic.

Can somebody tell me how this is commonly dealt with?

Thank you!

# Answer
I would not treat the rocket as a part of the rocket launcher. Instead, the rocket is a new entity that is spawned when fired.

**Managing the Rocket Launcher**

When the rocket launcher is loaded, it can be just a graphical change. In other words, you have two models of the rocket launcher - one with a rocket loaded, one without. This works with 3d models, sprites, or basically any other way your game renders the scene.

When the player loads a rocket, switch to the loaded model. When the player fires, switch to the unloaded model then rotate it.

Importantly, until the point where they actually fire the rocket, there is no rocket object yet in the game. It only exists as a number in their inventory: e.g., "int rocket\_count = 5";

If you do have an inventory count, you'll of course not let them load a rocket if the count is zero.

**Managing the Rocket**

Now as to the rocket, you should make it a completely new and separate object with its own model.

When the player fires, spawn a new rocket object , and it can then become completely independent of the rocket launcher and player, and manage itself however it wishes.

Also of course when they fire, you will subtract 1 from the rocket inventory.

**Advantages**

Besides taking care of your animation challenge, it also allows you to have a few other things happen, such as...

* Player can launch more than one rocket at once if a new one is reloaded before a previously fired one has hit something
* If the player switches to a new weapon while a rocket is in flight, it won't immediately also remove the rocket in flight
* Similar to above case, player death will not remove the rocket from the game.
> 1 votes

---
Tags: unity
---


# Question
Title: How to fill a 2d array with elements of a 1d List
I have a 2d array for 'Slots' in my inventory screen (slot width: 150px; total slots is based on width and height of inventory panel currently at 1500x600). The slot holds a reference to the pickupObjects that the player has picked up and added to the inventory (these items have been stored in a list).

So I try to make a method which fills the slots using the List of pickupItems. But the problem is that when I iterate through the inventory it will reach a number higher than the width of the first row of slots. I feel like the answer can be simple, but I just can't seem to figure out how to iterate through them and place it into the 2d array. I've solved this very issue in the past but can't remember how I did it.

Here's the code I have for creating the grid of slots, and then the method for putting the inventory in there (even though this method is pretty much empty right now as I am completely out of ideas):

Any help would be massively appreciated. Thanks

```
void CreateSlotLayout()
{
    panel_rt = GetComponent<RectTransform>();
    panelWidth = panel_rt.rect.width;
    panelHeight = panel_rt.rect.height;
    slotCount_x = (int)(panelWidth / slotWidth);
    slotCount_y = (int)(panelHeight / slotHeight);
    slots = new Slot[slotCount_x, slotCount_y];

    for (int y = 0; y < slotCount_y; y++)
    {
        for (int x = 0; x < slotCount_x; x++)
        {
            Slot slot = Instantiate(slotPrefab);
            slot.transform.SetParent(transform);
            slot.GetComponent<RectTransform>().anchoredPosition = new Vector2(x * slotWidth, -y * slotHeight);
            slots[x, y] = slot;
        }
    }
}

public void FillSlotsWithInventory(Player_Inventory playerInventory)
{
    for (int i = 0; i < playerInventory.GetPickupsList().Count; i++)
    {
          //something like....
          //slots[i?,i?].FillSlot(playerInventory.GetPickupsList[i];
    }
}

```

# Answer
> 2 votes
The typical way to do this is to make use of the fact that integer division truncates (the row, `y`), in combination with modulus operator to get the remainder (the column, `x`). In code, that looks like this:

```
public void FillSlotsWithInventory(Player_Inventory playerInventory)
{
    int pickups_count = playerInventory.GetPickupsList().Count;
    for (int i = 0; i < pickups_count; i++)
    {
        int x = i % slotCount_x;
        int y = i / slotCount_x;
        slots[x, y].FillSlot(playerInventory.GetPickupsList[i]);
    }
}

```

For a 3x3 inventory grid and 9 pickups, the data looks like this:

```
i => [x,y]
-----------
0 => [0,0]
1 => [1,0]
2 => [2,0]
3 => [0,1]
4 => [1,1]
5 => [2,1]
6 => [0,2]
7 => [1,2]
8 => [2,2]

```

If you want to do the opposite calculation (\[x,y\] =\> i), it's also quite straightforward:

```
int i = (y * slotCount_x) + x;

```

For which the data (predictably so) looks like this:

```
[0,0] => 0
[1,0] => 1
[2,0] => 2
[0,1] => 3
[1,1] => 4
[2,1] => 5
[0,2] => 6
[1,2] => 7
[2,2] => 8

```

**Side note**: Generally 2D arrays are indexed as \[y, x\] rather than \[x, y\] because it keeps the data in order in memory. This is not terribly important if you're doing random access into the array, but if you're iterating over it often it may help with performance. As always, profile your code before deciding that this it the most valuable thing to spend your time optimizing.

---
Tags: c#
---


# Question
Title: How do I correctly show both sides of a plane in Unity?
I am trying to show both sides of a mesh. I understand this question has been asked a lot, but all of the answers I've found seem like they're written for Unity 5 and I can't find a "Cull" setting on the shader.

Beyond that, I'm actually okay with extending the mesh to render both sides. In what I've read online, this may actually be the "correct" way to do it in that this should get all the lighting, shadows, etc. to render correctly.

My issue is that, when I make a mesh face two different directions, it's like the materials collide and I get a black appearance instead of the material I'm expecting:

The bottom is what I expect to see, but the top is what I'm getting when I render both faces.

To recreate, create an empty game object. Add a MeshRenderer and a MeshFilter, then add the TestMesh script:

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

public class TestMesh : MonoBehaviour
{
    public float width = 1f;
    public float length = 1f;
    public bool showPlane = true;

    private void OnValidate()
    {
        if(showPlane)
        {
            MeshRenderer rendObj = gameObject.GetComponent<MeshRenderer>();
            MeshFilter meshObj = gameObject.GetComponent<MeshFilter>();
            if((rendObj==null)||(meshObj==null))
            {
                Debug.LogErrorFormat("Error - TestMesh: MeshRenderers and MeshFilters need to be added to {0}", gameObject.ToString());
                return;
            }
            Mesh testMesh = meshObj.sharedMesh;
            testMesh.Clear();
            CreateMesh(testMesh);
        }
    }

    private void CreateMesh(Mesh mesh)
    {
        float x = 0.5f * width;
        float y = 0f;
        float z = 0.5f * length;

        Vector3 origin = Vector3.zero;

        // Make the corners of the plane
        Vector3 corner1 = new Vector3( x, y,  z);
        Vector3 corner2 = new Vector3( x, y, -z);
        Vector3 corner3 = new Vector3(-x, y, -z);
        Vector3 corner4 = new Vector3(-x, y,  z);

        // Rotate them to whatever the orientation of the gameObject is
        corner1 = gameObject.transform.rotation * corner1;
        corner2 = gameObject.transform.rotation * corner2;
        corner3 = gameObject.transform.rotation * corner3;
        corner4 = gameObject.transform.rotation * corner4;

        // Make them into a list for easy iteration
        List<Vector3> corners = new List<Vector3>(new Vector3[] { corner1, corner2, corner3, corner4, corner1}); // Add corner1 again at the end to close the loop

        // Initialize the vertices, uvs, and triangles lists
        List<Vector3> vertices = new List<Vector3>();
        List<Vector2> uvs = new List<Vector2>();
        List<int> triangles = new List<int>();

        // vertices[0] is the origin of the plane, and the plane is comprised of four triangles.
        vertices.Add(origin);
        uvs.Add(Vector3.zero);

        // Add the first corner to the vertices list, so now vertices[1] = corner1
        vertices.Add(corners[0]);
        uvs.Add(new Vector2(corners[0].x, corners[0].z));

        // Loop through the remainder of the corners
        for (int i=1; i<corners.Count; i++)
        {
            vertices.Add(corners[i]);
            uvs.Add(new Vector2(corners[i].x, corners[i].z));

            triangles.Add(0); // Each triangle starts at the origin and links two corners
            triangles.Add(i); // What you're doing here is linking a vertex of a triangle to an entry in the triangles list
            triangles.Add(i + 1); // Adding 0 means you want the first vertex to be vertices[0] - the origin. Adding [i] means
                                  // you want cornerI, because remember that vertices[0] is origin, so vertices[1] is corner1,
                                  // vertices[2] is corner2, etc.

            triangles.Add(0);       //
            triangles.Add(i + 1);   //   <------- HERE IS THE TROUBLE
            triangles.Add(i);       //
                                    // I would have thought I can add the vertices in reverse order to flip the auto-calculated face normal, but
                                    // what I'm getting is a black material where it looks like maybe I'm seeing a doubling of the material even though
                                    // I should only see one face.

        }

        // Convert the lists to arrays and send them to the mesh.
        mesh.vertices = vertices.ToArray();
        mesh.uv = uvs.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.RecalculateNormals();
    }
}

```

You can use any material if you want, but here's the .mat file for the laser material I've got (it's a generic material that's slightly transparent and red):

```
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
  serializedVersion: 6
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_Name: LaserPlane
  m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
  m_ShaderKeywords: _GLOSSYREFLECTIONS_OFF _SPECULARHIGHLIGHTS_OFF
  m_LightmapFlags: 4
  m_EnableInstancingVariants: 0
  m_DoubleSidedGI: 1
  m_CustomRenderQueue: -1
  stringTagMap: {}
  disabledShaderPasses: []
  m_SavedProperties:
    serializedVersion: 3
    m_TexEnvs:
    - _BumpMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _DetailAlbedoMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _DetailMask:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _DetailNormalMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _EmissionMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _MainTex:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _MetallicGlossMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _OcclusionMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    - _ParallaxMap:
        m_Texture: {fileID: 0}
        m_Scale: {x: 1, y: 1}
        m_Offset: {x: 0, y: 0}
    m_Floats:
    - _BumpScale: 1
    - _Cutoff: 0.5
    - _DetailNormalMapScale: 1
    - _DstBlend: 0
    - _GlossMapScale: 1
    - _Glossiness: 0
    - _GlossyReflections: 0
    - _Metallic: 0
    - _Mode: 0
    - _OcclusionStrength: 1
    - _Parallax: 0.02
    - _SmoothnessTextureChannel: 0
    - _SpecularHighlights: 0
    - _SrcBlend: 1
    - _UVSec: 0
    - _ZWrite: 1
    m_Colors:
    - _Color: {r: 1, g: 0.027406208, b: 0, a: 0.58431375}
    - _EmissionColor: {r: 257.00394, g: 0, b: 0, a: 1}

```

All I'm doing is flipping the order of the triangles, so I do

```
triangles.Add(0);
triangles.Add(1);
triangles.Add(2);

```

to make the forward-facing triangle and then do:

```
triangles.Add(0);
triangles.Add(2);
triangles.Add(1);

```

to make the backwards-facing triangle.

Again, I would expect each to get culled appropriately such that all I see is the correctly rendered material, but that's not happening. I've tried all kinds of settings in the material, but I can't find a cull setting (not that I want to go that route anyways) and I can't find anything that gets the material to render correctly.

# Answer
> 1 votes
RecalculateNormals (and normals in general) work on vertices. That is, each vertex has a single normal value. The problem you are seeing is due to the fact that each vertex is shared between two triangles that are facing opposite each other. The normal is just not going to work.

The solution is to duplicate your vertices, one set for the front face, and another for the back face.

---
Tags: unity, rendering, mesh
---


# Question
Title: How to know which child collider triggered in parent?
I have parent object with 3 children. Each children has one collider (BoxColliders actually) marked as triggers each one.

**I want to know in a OnTriggerEnter on the parent side which collider was hit.**

Similar to this question: How can I determine which Trigger is hit? But for 3D Colliders (not 2d). As you can see in the accepted answer they used `Collider2D.IsTouching` but it doesn't seem to exist any analogue method for a 3D Collider

If is not possible, what other solutions are there? What would be the recommended way? I would like to avoid the overhead from methods like `CompareTag` and `SendMessage` if possible.

http://answers.unity.com/answers/1206114/view.html

# Answer
> 2 votes
You can give the parent class a `public` method that takes two arguments, a `Collider` and some form of identification for which child was hit (e.g. a `Transform` or `Vector3` or `int id`, depending on what layout the children are in). Then, in each child object, give them a script like

```
using UnityEngine;

public class ChildCollider : MonoBehaviour {
    void OnTriggerEnter(Collider other) {
        transform.parent.gameObject.GetComponent<ParentScript>.OnChildTriggerEntered(other, transform.position);
    }
}

```

and in the `ParentScript` script

```
public void OnChildTriggerEntered(Collider other, Vector3 childPosition) {
    //Do stuff
}

```

---
Tags: unity, collision-detection, collider
---


# Question
Title: Unity: Edge of quad is dark. How do I avoid this?
I have four quads together like this

These are just the default Unity quad from create\3d object\quad

the texture is white with grey borders on two sides and a black border on other two sides..

Lets zoom in..

How do I get rid of these black lines?

I am generating these bigger shapes out of quads and applying the texture using code... I noticed that If I didnt change the material in code then there were no black lines. So I made prefabs for each material, and am now spawning those in instead of changing a material on a quad. But I still get the same lines. Also, if I drag the prefabs into the scene when the game is running they appear perfect. I have no idea whats going on.

# Answer
Ok I changed the texture wrap mode to clamp (it was repeat by default) and that fixed the black lines...

At the edges it was fading into the color at the opposite edge.
> 1 votes

---
Tags: unity
---


title: Parse JSON in Unity

text:
# Question
Title: Parse JSON in Unity
I've this JSON code like below. How do I parse it to the objects on code below?

```
{
  "data": [
    {
      "level": 1,
      "map": {
        "width": 16,
        "height": 16
      },
      "startLocations": [
        {
          "x": 1,
          "y": 0,
          "z": 1
        }
      ],
      "endLocation": {
        "x": 14,
        "y": 0,
        "z": 14
      },
      "pathPoints": [
        {
          "x": 1,
          "y": 0,
          "z": 1
        },
        {
          "x": 2,
          "y": 0,
          "z": 1
        }
      ],
      "waves": []
    }
  ]
}

```

```
public class Data
{
    public Level[] levels;
}

public class Level
{
    public int level;
    public Map map;
    public List<Vector3> startLocations;
    public Vector3 endLocation;
    public List<Vector3> pathPoints;
    public List<Wave> waves;
}

public class Map
{
    public int width;
    public int height;
}

public class Wave
{ }

```

I've tried all this but nothing doesn't work:

* Using `JsonConvert` but can't install it. I've got this error:

> Could not install package `Newtonsoft.Json 11.0.2`. You are trying to install this package into a project that targets `.NETFramework,Version=v3.5,Profile=Unity Subset v3.5`, but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
* Using next code but this always returns `null`.

```
JsonUtility.FromJson<Data>(myJsonCode)

```

I know this from this answer on the Unity forum.

> That's not possible with Unity's `JsonUtility`. You have to understand that the `JsonUtility` is not a general purpose JSON serializer / parser. It is build on top of Unity's serialization logic.

Are there other ways to parse JSON to objects in Unity?

# Answer
> 0 votes
After searching for a while, I've found an asset from the asset store named JSON.NET. Just install this and use this code to convert the JSON code.

```
using Newtonsoft.Json; // on the top of the file.
JsonConvert.DeserializeObject<Data>(myJsonCode);

```

# Answer
> 2 votes
It will simply done with `JsonUtility.FromJson<JsonClass>(jsonString)`

> Use `[Serializable]` before each class for serialization and use `Array[]` instead of `List<>`.

According to given json your class should like this

```
using System;

[Serializable]
public class JsonClass
{
    public Data[] data;
}

[Serializable]
public class Data
{
    public int level;
    public Map map;
    public StartLocation[] startLocations;
    public EndLocation endLocation;
    public PathPoint[] pathPoints;
    public Wave[] waves;
}

[Serializable]
public class Map
{
    public int width;
    public int height;
}

[Serializable]
public class StartLocation
{
    public int x;
    public int y;
    public int z;
}

[Serializable]
public class EndLocation
{
    public int x;
    public int y;
    public int z;
}

[Serializable]
public class PathPoint
{
    public int x;
    public int y;
    public int z;
}

[Serializable]
public class Wave
{

}

```

# Answer
> 0 votes
Put a `[Serializable]` tag on each of your classes that correspond to JSON. This will indicate that these can be serialized.

This might fix the `JSONUtility`, as I can't see any of the nested arrays that cause the problem in the mentioned link.

# Answer
> 0 votes
I see that you are using the DotNet 3.5 framework, so I’m guessing it’s Mono framework. If you can upgrade your project to DotNet 4.5 or above, it will allow you to use JSON.NET without issues. As far as I remember, JSON.NET is not supported for mono framework.

If you can not however upgrade your project, you can try using MiniJSON, which is a free JSON parser. It’s easy to serialise and deserialise stuff, and it works well with mono framework. I’m not sure if you will be able to parse the JSON into the object directly though, you might have to assign each field.

# Answer
> 0 votes
I was also facing problems in JSON parsing. Finally I learnt JSON parsing. Now I can parse any JSON. So I did tutorial on it. I am requesting you to check out. First of all I have covered Newton JSON Plugin and then without plugin using JSON Utility class. Json Parsing in Unity By using Newton json Plugin(JSON .Net) and Jsonutility

Steps for Newton JSON:

1. Search on Asset store Newton JSON or JSON .Net and install it.
2. If you get errors, change .Net version to .Net4
3. Copy your json and go on site of json2csharp and paste there. It will create a json class. Copy json class AND paste it in your class.
4. Create Object of RootObject class and get data whatever you want.

For JsonUtility follow till steps 3 and then from classes remove get set and just add semicolon with variable and on each class created by json2csharp site write \[Serializable\]. It will be on top of class.

Hope it will help you.

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


# Question
Title: Why can we use planes and military vehicles, but not other things?
Something sounds a little odd. It seems to me the status quo that if I wanted to put a real car or motorcycle into a video game, say a Toyota or a Ferrari, everyone would say that the default position is that you're not allowed, and that you'd need to ask permission first, and that most likely permission wouldn't be granted, and that the license to place such a thing in my game would cost a fortune.

On the other I've noticed that people are much more confident about placing planes and military vehicles into a game, or display or render. I guess I'll start off with WW2 examples, and move from there. If we take the example of the P-51 Mustang fighter plane, it was manufactured by North American Aviation. That company doesn't exist anymore exactly, but was merged into North American Rockwell, which then became named Rockwell International, and now is part of Boeing.

OK, so there's no problem including a P-51 Mustang in your production. I guess you might say that the rights ownership transitioned so many times and over such a long period that Boeing really doesn't care if you include a P-51 Mustang in your production.

Let's take another example, Boeing P-26 Peashooter, a 1930s fighter plane. In this case the manufacturer was all along Boeing. I am confident there is still no problem in including this in your production. In this case you might say that the plane is so old Boeing doesn't care if you include it in your production.

You might say the same about the Mitsubishi and Kawasaki WW2 era planes.

Even more recently, with the F-16 you'd think rights holders would be General Dynamics or Lockheed Martin. I'm pretty sure you won't have a problem with including an F-16. One of the designers of the F/A-18 Hornet was McDonnell Douglas (now Boeing). Same thing goes here.

In fact you can fast forward all the way to the present to the F-35 Lightning II, which was designed and built by Lockheed Martin. I doubt very much there would be issues with including this plane in your production.

So the thing in common with all the above planes is that they're military.

If we consider civilian planes like the 737 and 747, I feel there is no problem displaying these and putting them into productions. GPL'd flight simulators have been taken and commercialized (sold), with these models in it, and I doubt very much either that permission was sought, or in the case that it was sought I'm almost sure they didn't pay for any license to have them in their game.

So with civilian planes I feel this is very much the same thing. Correct me if I'm wrong.

On the other hand if I said I was I going to include a Porsche 912 from the 60s in my production, you would say I would be crazy to do so without permission, and to get a license to do so would cost me a fortune. However I'd expect a completely different reaction to for example the Porsche 597 from the 50s.

So I'm noticing two things:

1. Military vehicles seem to be able to be used more permissively (a lot a more permissively).
2. Civilian aircraft seem to be able to be used more permissively) than civilian land vehicles.

As for boats and ships, it's something I haven't thought of that much. And in the case of VERY old civilian land vehicles, such as maybe the first Chevrolet from 1913, though I'd be guessing, I imagine wouldn't be a problem using its likeness in a production such as a film or game or something. It's very interesting, I feel if someone used the likeness of one of the earliest Ford motor cars, the problem would be to a much greater extent using the trademarked Ford logo than that the likeness of the actual Ford model. Does anyone know roughly speaking why there are these differences in the status quo?

# Answer
> 2 votes
I think this all boils down to Intellectual Property Laws. As I understand it (former dev, not a lawyer), there are several kinds of intellectual property.

1) Trade Secrets. As long as you keep it a secret, it's yours... but once it's out, it's out. Not terribly relevant.

2) Patents. The government protects your right to a particular implementation of a particular idea for a particular length of time. Not terribly relevant.

3) Trademarks. Defending your name, avoiding confusion, blah blah blah... I don't know much about trade marks. Somewhat relevant to the conversation at hand.

4) Copyrights. Pretty sure this is what applies. The right to copy. In exchange for enriching the world by publishing your thing (book, song, whatever), the government will protect your right to say who is or isn't allowed to make copies of your work.

The important thing about copyright law in the US is that the government will only back you up **as long as you continue to defend it**. If, for example, an author runs across some fan fiction containing characters they've created, they're legally obligated to defend their ownership of those characters. Folks who write fan fic are usually rabid fans, so authors often turn a blind eye to such things... either by actively avoiding such things, or by claiming they do. ;)

If they don't defend it, they lose the copyright. This is what I think applies here.

Copyright is also limited by what is called "fair use". You can reproduce part of a work to critique it, or for educational purposes, or parody, for examples. The fourth fair use metric is "**Effect on the work's value**", and I think this is the meat of the argument against inclusion of Thing X (whatever that might be) in a game. The value of a fighter jet is not (just) it's price tag, but in it's ability to Blow Shit Up.

On the other hand, precedent carries a great deal of weight. If other games have reproduced X, Y, and Z, in the past without paying for it, you can reproduce it too. See also "you have to defend your copyright".

In hunting down those links, I learned about two new categories of IP, "Industrial Design", and "Trade Dress", both of which may be relevant. Do your research.

---
Tags: copyright, licensing
---


# Question
Title: How can I fix my project after upgrading to Unity 2019 / .NET 4.x?
My Unity version was about a year out of date. After upgrading it to Unity 2019.1.5f1 through the Unity Hub, my project started throwing hundreds of errors. The most prominent one seemed to be:

```
Feature `out variable declaration' cannot be used because it is not part of the C# 4.0 language specification

```

How can I fix my project so that it runs again?

# Answer
Go to **Edit** \> **Project Settings** \> **Player** and change the **Scripting Runtime Version** to `.NET 4.x Equivalent`.

Restart Unity and the project should compile again, unless you have other errors as well.
> 2 votes

---
Tags: unity, .net
---


# Question
Title: Why can I not open the desktop and core folders in libGDX?
I think the problem is caused beacuse I have two JDK's. One dedicated one and another integrated from Android Studio. Before, when I start the bulid it gave me a warning:

`[options] bootstrap class path not set in conjunction with -source 1.6`

There is only one search I found online that did not help me.

But I can no longer reproduce this. Can anyone help me? I dont know what I am doing wrong. I cannot run the project, nor browse the folders in Android Studio.

Here is a screenshot:

# Answer
The project doesn't appear to be imported into android studio.

```
Select File -> Close
Import project (gradle)

```

Alternatively if you've already imported it you may just be opening it wrong.

```
File -> Close
Open existing Android Studio project (selecting the project at the root level)

```
> 1 votes

---
Tags: java, libgdx
---