# Question
Title: Unknown error when trying to register a Minecraft ArmorItem
The error in question is \[***Inferred type 'I' for type parameter 'I' is not within its bound; should extend 'net.minecraft.item.Item'***\]

on the following snippet of code

```
// Armor Items
public static final RegistryObject<ArmorItem> RINGMAIL_HELMET = ITEMS.register("ringmail_helmet",
        new ArmorItem(DnDCraftArmorMaterial.RINGMAIL, EquipmentSlotType.HEAD, new Item.Properties().group(DnDCraft.TAB)));

```

I have tried many things like what I do here

```
public static final RegistryObject<Item> RING = ITEMS.register("ring", ItemBase::new);

```

by putting the **ItemBase::new** snippet in the last paramter. I've also tried seeing what IntelliJ suggests is best in-context action but none of those approaches seemed to fix the issue.

I'm not super familiar with Java or Minecraft modding so this may just be something simple that I am missing but any help or recommendations would be nice. Thanks!

Also this is the ItemBase class, in case that helps.

```
package com.fire.dndcraft.items;

import com.fire.dndcraft.DnDCraft;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;

public class ItemBase extends Item {
    public ItemBase() {
        super(new Item.Properties().group(DnDCraft.TAB));
    }
}

```

# Answer
> 1 votes
I had the same problem, try adding `() ->` after the comma that's after the `ringmail_helmet` but don't add another comma

```
public static final RegistryObject<ArmorItem> RINGMAIL_HELMET = ITEMS.register("ringmail_helmet", () ->
        new ArmorItem(DnDCraftArmorMaterial.RINGMAIL, EquipmentSlotType.HEAD, new Item.Properties().group(DnDCraft.TAB)));

```

---
Tags: java, minecraft-modding
---


title: Touch control pan 3D map

text:
# Question
Title: Touch control pan 3D map
I'm working on recreating the board game "Hex" as a mobile game. I'm working on implementing zoom and pan features using two fingers. I feel like I managed to get the zoom to work, but the pan moves more than I want it to and I feel like it is because I'm missing something and must be somewhere in the conversion to World Space coordinates. if I could get some help it would be greatly appreciated.

For reference, oldMidpoint is initialized to 0 earlier on.

```
        Touch touchA = Input.GetTouch(0);
        Touch touchB = Input.GetTouch(1);

        Vector3 midpoint = (touchA.position + touchB.position) / 2;
        if(midpoint != oldMidpoint)
        {
            if(oldMidpoint == Vector3.zero)
                oldMidpoint = midpoint;

            Vector3 moveDistance = oldMidpoint - midpoint;
            moveDistance.y = 0;

            Camera.main.transform.Translate(moveDistance, Space.World);

            oldMidpoint = midpoint;
        }

```

# Answer
> 1 votes
I believe what you're looking for is what I refer to as "Google Maps" style panning. This is where the pointer stays perfectly locked on the exact place in the world where you started the pan.

Like @DMGregory mentioned, you need to do everything in world space. You start by caching the pointer's position in world space when the drag begins. Then every frame while dragging, calculate a vector from the pointer's current world position back to its starting world position. Then offset the camera's world position by that amount. You can think of it as constantly moving the camera such that the cursor's world position stays fixed.

Here's a simple implementation. Obviously you won't use the mouse, but as long as you're panning based off of a single point (in your case the average of two touches) it should work just the same:

```
public class CameraPan : MonoBehaviour
{
    private bool _isDragging;

    private Vector3 _pointerWorldStart;

    private static Vector3 GetPointerWorld()
    {
        var plane = new Plane(Vector3.up, Vector3.zero);
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        plane.Raycast(ray, out var enter);
        var pointerWorldCurrent = ray.GetPoint(enter);
        return pointerWorldCurrent;
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            _pointerWorldStart = GetPointerWorld();
        }
        _isDragging = Input.GetMouseButton(0);

        if (!_isDragging)
        {
            return;
        }

        var pointerWorldCurrent = GetPointerWorld();
        transform.position += _pointerWorldStart - pointerWorldCurrent;
    }
}

```

# Answer
> 0 votes
Your `moveDistance` is measured in screen pixels. If you want to convert that to a world space unit, you need a function a bit like this:

```
float ScreenToWorldDistance(float screenDistance, Camera camera, float depth) {
    float visibleHeightAtDepth;

    if (camera.orthographic) {
        visibleHeightAtDepth = 2f * camera.orthographicSize;
    } else {
        visibleHeightAtDepth = 2f * depth * Mathf.Tan(Mathf.Deg2Rad * camera.fieldOfView/2f);
    }

    return visibleHeightAtDepth * screenDistance/Screen.height;
}

```

---
Tags: unity, c#, 3d, touch, hexagonal-grid
---


title: Minecraft style world generation

text:
# Question
Title: Minecraft style world generation
I want to generate a world like minecraft's with an algorithm that treats every block separately. I want the world generator to be a single large function that takes in the x,y,z coordinates and returns what block should be placed in that spot.

It should work without knowledge of what the adjacent blocks are. It should be able to generate terrain with biomes, trees, caves, ore deposits and structures like villages.

Is it possible to make such a world generator and if so, can I get some pointers to how it can be done and what topics to research? If somebody wrote a tutorial about doing that it would be perfect. I hope this isn't a duplicate question because I am specifically interested in generating each block completely independent from its surroundings.

# Answer
> 10 votes
What you are looking for is Fractal Noise generation algorithms, the most popular of which being Perlin noise with successive octave noise generation (in addition to simplex noise, which is patented by Nokia, however the patent expires in a 2021 and if you want to take the risk, technically doesn't apply to terrain generation (only that which "generates an image")).

I'm not going too in-depth into perlin noise here, but I'll give a rough overview to how it is really the closest thing that solves your problem.

Perlin noise is a type of Gradient Noise algorithm, which smooths out visual artifacts compared to Value Noise. Both of these types of fractal noise generation techniques work via *pseudo random hashing of grid coordinates* which then create a *pseudo random value* at that grid point implicitly, which can be **independently accessed and repeatedly generated with the same value regardless of the existence of values around the point**. All these techniques need to know is the index you are trying to generate, and how many *octaves* you want to generate on top of it. Values at each point are interpolated between each value that corresponds to grid intersections, this creates noise.

Octaves are what create the fractal, correlated patterns you see in the wiki articles (the cloudy images). Octaves are successive application of the same algorithm but summed up with some weight applied to each level. You start out with a very high frequency octave (which is to say, high resolution grid, acting as if the discrete points you generate are actually several sub points within that grid, higher resolution means the less points correspond to a single cell of the grid) and succesively sum up lower frequency versions of that grid until you get what would look like the images above.

These values end up just being numbers, so they can map to anything you like, people often use this to generate terrain quickly.

Value noise just means at each octave, or run of the algorithm, you act like the corner point number you've generated with a hash is just a value (integer, float or otherwise). In Gradient noise, this value becomes a *direction*, you will end up generating hills which give you values based on their height, interpolating where you are on the hill based on the directions at each point. This creates a Gaussian smoothing effect of features, in addition to creating less directional artifacts visible by people on successive octave generations.

These techniques are not limited to 2D or even 3D, this type of generation can be used to create moving 3D clouds by using 4D noise generation, where the 4th dimension is the *time* location instead of a spacial index location. These techniques can work on Ndimensional data (but are obviously slower at higher dimensions)

Again, you can generate any point independently from any other with these methods, there is no interdependence on adjacent values.

Now how would you use this to generate like you say?:

> terrain with biomes, trees, caves, ore deposits and structures like villages.

I am unsure of the specifics on minecraft, but I do know Notch says that the game uses perlin noise generation.

For 3D height maps this is easy. You can easily generate hills and mountains with this using the output value from summed octaves as the height you want, and this can all be done with 2D perlin noise.

If you want different physical characteristics of the noise (like sharp spine ridges or more bubbly appearances) you can modify your output, or change your indexing formula to warp space and create such characterstics. See here for visual examples of what gradient noise is capable of

Caves on the other hand are a bit tricky. Have you even wondered why minecraft has floating islands? Well part of the reason it exists is likely how horizontal concave terrain generation is handled, for example what is required to create caves and cliffs.

One way to handle this is to use 3D noise generation ***and*** the 2D surface generation together, and only fill in blocks that exist within the 2D initial surface and pass the "empty" threshold value that you will use to interpret the 3D noise output with. The issue with this approach is that, in some instances, this will produce the artifacts you see in minecraft. Floating islands can happen in part because the "floating" part may have passed the threshold, and despite the empty part being inside the initial 2D surface, it didn't pass the threshold and was left empty.

This can be partially mitigated with out block interdependence via using the height map value you are generating at to also determine the empty threshold (making it harder to be an empty block the further up you are generating at). However, with out some block dependent post processing fix up this is usually not completely fixable.

The good news is that from this point, if you understood how to do the previous stuff, the rest is pretty easy. For deposits, like combining 3D and 2D to create caves with height maps, we can simply apply another perlin noise function to figure out whether or not to place a deposit and what type of deposit it should be. Biomes can be handled similarly, either with a single noise function, or multiple functions that produce different biomes based on overlapping values, in addition to incorporating elevation. Trees can be handled similarly, with another noise function which simply places the tree on the surface generated as the height map is generated and biome calculated. Villages will be a bit harder, but in general you can at least place the spawn place of a village in a similar way. You may have to move away from block independence to create a logical structure, something like cellular automata may work. Village place is spawned, and then generated outwards from that location later. But of course you may be able to find a way to independently generate it with via perlin noise like everything else, the issue is how to generate the structures themselves, one compromise is using predefined structures, and connecting them online, or even having entire predefined villages.

For an additional resource awesome redblog article goes over tree and biome generation in this style but in 2D and with actual code.

# Answer
> 2 votes
I would highly recommend you to watch Sam Hogan's I Made Minecraft in 24 Hours. He has talked about how to procedurally generate trees and water, and also different terrain.

And if you want to know more about Procedural Landmass Generation check out Sebastian Lague's playlist on Procedural Terrain Generation

This is a part of the description from Sam's video which I think would be of help. It is like an overview of the video.

> I started off with basic terrain generation, using cube game objects arranged in a grid, whose heights are varied by a Perlin noise function. This, however, led to not great performance, but luckily I knew of a way to significantly optimize things.
>
> This was using terrain chunks - which is what the actual Minecraft does as far as I can tell. This meant using voxel data to only build faces of blocks that are facing air blocks. And because the voxel data is 3D, it's possible to have much more interesting procedural terrain generation, like caves, overhangs, trees, etc.
>
> It's super fun to play around with the different noise functions and see what type of terrain is generated. I ended up doing some simple stuff which looks pretty good: A base layer of simplex noise at a large scale + another layer at a smaller scale that is multiplied by yet another layer for terrain variety. This is the heightmap. Then 3D simplex noise cuts pieces out to create cave systems.
>
> Procedurally generating trees and water were both a little tricky. For trees, I used a Perlin noise value at each chunk coordinate to determine how many trees would be in each chunk. Then, a random number generator seeded with the chunk's coordinates was used to build the specific trees. This way, the exact same random numbers are produced each time for a specific chunk, and the same trees are generated.
>
> Water had to form around the terrain, so you don't have weird stuff like finding water when you did straight down. What I ended up doing was creating a separate mesh for the water. To build it up, just loop through each xz coordinate in the chunk, for each starting at the max y position and move down through the voxel data, checking if land exists. If the water level is reached before the first land block, build a square at the water level.
>
> There's some boring stuff cut out of the video, like optimization. I did things like adding an object pool for reusing terrain chunks and add a timer to load chunks one at a time instead of all at once. The performance is still not great, which is mostly due to all the noise function calculations. This could probably be fixed with multithreading, but there's no way I could figure that out without internet help.

---
Tags: procedural-generation, perlin-noise
---


# Question
Title: Character Controller and Reverse Gravity
So I have a Game object with Rigid Body, a Character controller and my Movement script. On a specific condition I am reversing gravity. The problem is that the velocity.Y when the gravity is reversed, keeps increasing to the infinity. If I try to reset it like in the first if statement (which works for normal gravity) the object keeps bouncing from the ground. Gravity scale is either 1 or -1 in order to reverse gravity and movement.

This is the code:

```
 void Update()
    {

        _isGrounded = Physics.CheckSphere(groundCheck.position, 0.4f, whatIsGround);
        Move();
    }

void Move(){
//Reseting States for new cycle , unless the object is falling
        if ((_isGrounded && velocity.y < 0))
        {
            velocity.y = -2f;
            _isRunning = false;
            _isJumping = false;
            _isFalling = false;
        }else if (velocity.y < 0 && !_isGrounded)
        {
            _isFalling = true;
        }
        //Moving on X axis
        float x = Input.GetAxis(KeyInputMove);
        if (x != 0)
        {
            _isRunning = true;
        }
        moveDirection = gravityScale*_transform.right * x;
        _controller.Move(moveDirection * moveSpeed * Time.deltaTime);

        //Perfoming jump
        if (Input.GetButtonDown(KeyInputJump) && _isGrounded)
        {
            velocity.y = (float) Math.Sqrt(1 * -2f * globalGravity);
            _isJumping = true;
        }

        velocity.y += gravityScale * globalGravity * Time.deltaTime;
        _controller.Move(velocity * Time.deltaTime);
//Updating animation states
        _animator.SetBool("Grounded",_isGrounded);//^This is the idle state
        _animator.SetBool("Running",_isRunning);
        _animator.SetBool("Jumping",_isJumping);
        _animator.SetBool("Falling",_isFalling);

    }

    private void OnTriggerExit(Collider other)
    {
       //Reverse Gravity and Model Rotation
        if (other.gameObject.tag == "Portal")
        {
            _transform.Rotate(0,0,gravityScale*180);
            gravityScale *= -1;
        }
    }

```

# Answer
> 0 votes
> The problem is that the velocity.Y when the gravity is reversed , keeps increasing to the infinity.

That's what your code tells it to do:

`velocity.y += gravityScale * globalGravity * Time.deltaTime;`

Perhaps you are forgetting to check if the gravity is negative or positive when determining whether the object is falling. Here's what you probably want:

```

if (gravityScale > 0 && velocity.y < 0)
    || (gravityScale < 0 && velocity.y > 0))
{
    _isFalling = true;
} else {
    _isFalling = false;
}

if (_isGrounded && _isFalling) {
    velocity.y = -2f * gravityScale; //maybe you should just set it to 0?
    _isRunning = false;
    _isJumping = false;
    _isFalling = false;
}

```

I assume that `gravityScale` is 1 when gravity is normal (objects fall downward) and -1 when gravity is reversed (objects fall upward?). I'm not really sure why you are setting the velocity to -2 in the first `if` condition; you might want to try setting it to 0.

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


# Question
Title: How can I load and store data for a large map in Unity
I'm working on a tower defense game. I have this structure:
`int array (public int[,,,] gridArray = new int[2000, 2000, 9, 9];)`
that I'm using as a map-bible; by map-bible I mean that the array holds all the cell data that the game uses to build its map form.

What I am specifically asking for is a way to store that data in any file format without needing to massively rework my game.

The first two dimensions of the array store x and y, while the last two dimensions hold cell-specific data. In most cases, this cell-specific data stores building health or ammo. But the vast majority of the 81 cells are empty to accommodate more things down the line. It should be noted that all this data is simply integers that are passed on to game objects, for example:
`newbuilding.health = gridArray [x,y,0,1];`

It should be noted I am a novice level programmer and in way over my head, so detail would be appreciated.

# Answer
> 3 votes
> What I am specifically asking for is a way to store that data in any file format without needing to massively rework my game.

> It should be noted I am a novice level programmer and in way over my head, so detail would be appreciated.

No offense, but the clumsy way you're storing your data is just making things worse for you. You should seriously consider changing it, even if that means you need to rework some of your game. If you start from a bad foundation and just keep building on that bad foundation, you're just going to end up with code that is more and more of a mess until it gets to the point that it's impossible to make any progress. This often means giving up on the project and sometimes giving up on game development altogether.

In the engine, your data should probably be stored more along the lines of something like this:

```
[System.Serializable]
public struct Cell {
    [SerializeField] private int x;
    [SerializeField] private int y;
    [SerializeField] private BuildingInfo buildingInfo;
    [SerializeField] private int ammo;

    public int X{ get => x; set => x = value; }
    public int Y{ get => y; set => y = value; }
    public Vector2Int Position => new Vector2Int(x, y);
    public BuildingInfo BuildingInfo { get => buildingInfo; set => buildingInfo = value; }
    public int Ammo { get => ammo; set => ammo = value; }
    //etc
}

//if most cells will have data, we can consider a 2D table:
private Cell[,] cells = new Cell[2000, 2000];
//to retrieve a cell
var cell = cells[x,y];

//or if most cells will not have data, we should not waste an enormous amount of
//space populating a 2D table with empty cells
private Dictionary<Vector2Int, Cell> cells = new Dictionary<Vector2Int, Cell>(100);
//to add a cell:
var cell = new Cell();
cell.X = x;
cell.Y = y;
//etc
cells.Add(cell.Position, cell);

//to retrieve a cell
if (cells.TryGetValue(new Vector2Int(x, y), out var cell) {
    //do something with the cell here
}
//to loop through all cells
foreach (var cell in cells.Values) {
    //do something with the cell here
}

```

Because the struct in my example is serializable, you can put the structs into a ScriptableObject:

```
[CreateAssetMenu(menuName = "Saved Map")]
public class SavedMap : ScriptableObject {
    [SerializeField] private List<Cell> cells = new List<Cell>(100);

    public List<Cell> Cells { get => cells; set => cells = value; }

    public void SaveFromDictionary(Dictionary<Vector2Int, Cell> dict) {
        cells.Clear();
        foreach (var cell in dict.Values) {
            cells.Add(cell);
        }
        //special code that only runs in the Editor to make sure the Editor recognizes that the data changed and needs to be saved to disk
#if UNITY_EDITOR
        EditorUtility.SetDirty(this);
#endif
    }

    //this is very expensive, only call it once when you start the game and save the result to a variable
    public Dictionary<Vector2Int, Cell> ToDictionary() {
        Dictionary<Vector2Int, Cell> dict = new Dictionary<Vector2Int, Cell>(cells.Count);
        foreach (var cell in cells) {
            dict[cell.Position] = cell;
        }
        return dict;
    }
}

public class MapLoader : MonoBehaviour {
    [SerializeField] private SavedMap map;
    private Dictionary<Vector2Int, Cell> cells;

    private void Awake() {
        Assert.IsNotNull(map);
        cells = map.ToDictionary();
    }

    public Dictionary<Vector2Int, Cell> Cells => cells;
}

```

A ScriptableObject class defines a type of asset file that you can create, edit, and save in the Unity Editor. You can edit a ScriptableObject asset in the Inspector in the same way you edit any GameObject. In this case manually editing the cells in the Inspector would be a nightmare, so you'd probably want to have a script pass the data into the ScriptableObject to save.

If you don't know how to use Dictionaries or ScriptableObjects or anything else I've mentioned, please do a web search and read the official documentation. This is the best way to learn!

You might also want to eventually make a custom `Editor` or `EditorWindow` script for easily editing a SavedMap in the Unity Editor.

---
Tags: unity, c#, data-structure
---


# Question
Title: 2d gravity simulator - smaller object orbiting towards center of bigger object
In my libgdx test game, I have initially created 2 circle objects (stellar) about which I will say more in details below. However, my goal is to simulate gravity in 2d, where smaller object orbits towards center of bigger object (just like earth orbits sun) but closer and closer to the center of bigger.

So, I have created the following:

* stellar1: smaller, 10px radius, 10 mass, dynamic (can move), initial position -160x90, velocity (0,0), accelerator (0,0)
* stellar2: bigger, 30px radius, 30 mass, static (cannot move), initial position 0x0, velocity (0,0), accelerator (0,0)

Here is also a screenshot, just to have a picture:

I will give the full code below of what I did so far, before that I want to mention I have 2 approaches, StellarTest1 and StellarTest2.

First **StellarTest1**, I've tried to add some extra values like 1000f to both x and y just to see something in action like:

```
velocity.x += 1000f * acceleration.x * deltaTime;
velocity.y += 1000f * acceleration.x * deltaTime;

```

Resulting in - smaller object gets towards the center of the bigger object, but once it reaches the center of bigger, the smaller object gets evicted to the opposite side. Not to mention how 1000f is not the correct value in the size of this coordinate system, but I am concerned about following computation:

```
acceleration.x = gravityForce * (diffX / distance)
acceleration.y = gravityForce * (diffY / distance)

```

Code StellarTest1:

```
public class StellarTest1 extends AbstractTest {

    private Stellar stellar2, stellar1;

    public StellarTest1(Game game) {
        super(game);
    }

    @Override
    public void create() {
        game.getCartesianGrid().setEnabled(true);

        // smaller  stellar
        float startX = -160;
        float startY = 90;
        float radius = 10;
        float mass = 10;
        stellar1 = new Stellar(
                startX, startY,
                radius, mass,
                new Color(102, 188, 217, 100f)
        );

        // bigger stellar
        startX = 0;
        startY = 0;
        radius = 30;
        mass = 30;
        stellar2 = new Stellar(
                startX, startY,
                radius, mass,
                new Color(252, 236, 3, 100f)
        );
        stellar2.updatable = false; // bigger object will not update, in other words no motion

        stellar2.setOther(stellar1);
        stellar1.setOther(stellar2);
    }

    @Override
    public void update(float deltaTime) {
        if (!updatable) {
            return;
        }
        stellar2.update(deltaTime);
        stellar1.update(deltaTime);
    }

    @Override
    public void draw() {
        if (!drawable) {
            return;
        }
        stellar2.draw();
        stellar1.draw();
    }

    private class Stellar {

        Circle circle;
        Vector2 velocity;
        Vector2 direction;
        Vector2 acceleration;
        float mass, radius;
        boolean updatable;
        Stellar other;

        public Stellar(
                float startX, float startY,
                float radius, float mass,
                Color color) {
            this.radius = radius;
            this.velocity = new Vector2(0, 0);
            this.acceleration = new Vector2(0, 0);
            this.mass = mass;
            this.radius = radius;

            circle = new Circle(game,
                    color,
                    startX, startY,
                    radius);

            this.updatable = true;
        }

        public void update(float deltaTime) {
            if (!updatable) {
                return;
            }
            float diffX = other.circle.x - circle.x;
            float diffY = other.circle.y - circle.y;

            float G = 2f;
            float mass = G * (other.mass - this.mass);
            float distance = (float) Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2));
            float gravityForce = (float) (mass / Math.pow(distance, 2));

            acceleration.x = gravityForce * (diffX / distance);
            acceleration.y = gravityForce * (diffY / distance);

            velocity.x += 1000f * acceleration.x * deltaTime;
            velocity.y += 1000f * acceleration.y * deltaTime;

            circle.x += velocity.x * deltaTime;
            circle.y += velocity.y * deltaTime;
        }

        public void draw() {
            game.getShapeRenderer().begin(ShapeRenderer.ShapeType.Filled);
            circle.draw();
            game.getShapeRenderer().end();
        }

        public void setOther(Stellar other) {
            this.other = other;
        }
    }

}

```

Second StellarTest2, in this example, you will see same code, except I am using here angle in degrees:

```
float angleInDegrees = MathUtils.atan2(diffY, diffX) * MathUtils.radiansToDegrees;
...
acceleration.x = gravityForce * MathUtils.cos(angleInDegrees * deltaTime);
acceleration.y = gravityForce * MathUtils.sin(angleInDegrees * deltaTime);

```

In this test, I did not have to add some extra velocity to move smaller object. Also I achieved that smaller object will make a solid curve, but will not get dragger in the center. Instead, after some time it will evict out. However, still I face the issue that smaller object keeps curving in and out and towards center. Yet, I am curious if cos and sin is necessary here, and perhaps StellarTest1 is right approach.

Code StellarTest2:

```
public class Stellar2Test extends AbstractTest {

    private Stellar stellar1, stellar2;

    public Stellar2Test(Game game) {
        super(game);
    }

    @Override
    public void create() {
        game.getCartesianGrid().setEnabled(true);

        float startX = -160;
        float startY = -90;
        float radius = 10;
        float mass = 30;
        stellar2 = new Stellar(
                startX, startY,
                radius, mass,
                new Color(102, 188, 217, 100f)
        );

        startX = 0;
        startY = 0;
        radius = 30;
        mass = 30;
        stellar1 = new Stellar(
                startX, startY,
                radius, mass,
                new Color(252, 236, 3, 100f)
        );
        stellar1.updatable = false;

        stellar1.setOther(stellar2);
        stellar2.setOther(stellar1);
    }

    @Override
    public void update(float deltaTime) {
        if (!updatable) {
            return;
        }
        stellar1.update(deltaTime);
        stellar2.update(deltaTime);
    }

    @Override
    public void draw() {
        if (!drawable) {
            return;
        }
        stellar1.draw();
        stellar2.draw();
    }

    private class Stellar {

        Circle circle;
        Vector2 velocity;
        Vector2 acceleration;
        float mass, radius;
        boolean updatable;
        Stellar other;

        public Stellar(
                float startX, float startY,
                float radius, float mass,
                Color color) {
            this.radius = radius;
            this.velocity = new Vector2(0, 0);
            this.acceleration = new Vector2(0, 0);
            this.mass = mass;
            this.radius = radius;

            circle = new Circle(game,
                    color,
                    startX, startY,
                    radius);

            this.updatable = true;
        }

        public void update(float deltaTime) {
            if (!updatable) {
                return;
            }
            float diffX = other.circle.x - circle.x;
            float diffY = other.circle.y - circle.y;
            float angleInDegrees = MathUtils.atan2(diffY, diffX) * MathUtils.radiansToDegrees;

            float G = 2;
            float mass = (G * (other.mass * this.mass));
            float distance = (float) Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2));
            float gravityForce = mass / distance;

            acceleration.x = gravityForce * MathUtils.cos(angleInDegrees * deltaTime);
            acceleration.y = gravityForce * MathUtils.sin(angleInDegrees * deltaTime);

            velocity.x += acceleration.x * deltaTime;
            velocity.y += acceleration.y * deltaTime;

            circle.x += velocity.x * deltaTime;
            circle.y += velocity.y * deltaTime;
        }

        public void draw() {
            game.getShapeRenderer().begin(ShapeRenderer.ShapeType.Filled);
            circle.draw();
            game.getShapeRenderer().end();
        }

        public void setOther(Stellar other) {
            this.other = other;
        }
    }

}

```

# Answer
> 1 votes
Implement continuous collision detection.

Inverse square law means the velocity while approaching an imminent collision is asymptotically high. One frame the object is on one side, and translating it to a new position will place it on the far side of the object, as if there were no collision. This is called tunneling. Continuous collision detection is for fast moving objects for this exact reason.

https://box2d.org/files/ErinCatto\_ContinuousCollision\_GDC2013.pdf

https://docs.unity3d.com/Manual/ContinuousCollisionDetection.html

https://digitalrune.github.io/DigitalRune-Documentation/html/138fc8fe-c536-40e0-af6b-0fb7e8eb9623.htm

https://pybullet.org/Bullet/phpBB3/viewtopic.php?t=11591

https://link.springer.com/article/10.1007/s00371-019-01718-2

---
Tags: java, 2d, libgdx, physics, movement
---


# Question
Title: How to get an OnClick Event in Unity to action?
I am new to Game Dev and I am following a Tutorial. Within this tutorial, we create a quest system, that allows you to accept or decline a quest. This tutorial is based on Unity 5 and I am using 2020.1 so there could be version differences that could be causing the issue.

I have a script called:

**Quest001Buttons.cs**

```
public class Quest001Buttons : MonoBehaviour {
    public GameObject ThePlayer;
    public GameObject NoticeCam;
    public GameObject UIQuest;
    public GameObject ActiveQuestBox;
    public GameObject Objective01;
    public GameObject Objective02;
    public GameObject Objective03;

    public void AcceptQuest() {
        Debug.Log("Accept Registered");
        ThePlayer.SetActive(true);
        NoticeCam.SetActive(false);
        UIQuest.SetActive(false);
        StartCoroutine(SetQuestUi());
    }

    IEnumerator SetQuestUi() {

        ActiveQuestBox.GetComponent<Text>().text = "My First Weapon";
        Objective01.GetComponent<Text>().text = "Reach the Clearing";
        Objective02.GetComponent<Text>().text = "Open Chest";
        Objective03.GetComponent<Text>().text = "Get Weapon";
        QuestManager.ActiveQuestNumber = 1;
        yield return new WaitForSeconds(0.5f);
        ActiveQuestBox.SetActive(true);
        yield return new WaitForSeconds(1);
        Objective01.SetActive(true);
        yield return new WaitForSeconds(0.5f);
        Objective02.SetActive(true);
        yield return new WaitForSeconds(0.5f);
        Objective03.SetActive(true);
        yield return new WaitForSeconds(9);
        ActiveQuestBox.SetActive(false);
        Objective01.SetActive(false);
        Objective02.SetActive(false);
        Objective03.SetActive(false);

    }
}

```

I have an Empty GameObject called "QuestButtonManager" which I have assigned the above script to. I also have a UI GamObject called "Accept" and I have attached the QuestButtonManager GameObject to the OnClick() Event within that component. I have selected: "Runtime Only" and the function of "Quest001Buttons.AcceptQuest".

When I run the game and press the Accept Button...the game seems to not function after that and is stuck on that screen, with the button highlighted...not even the `Debug.Log` text is printed in the console.

Any help is greatly appreciated before I give it up and look for a more updated version to learn on.

# Answer
After trying to resolve the issue and to understand why it was doing what it was doing. I removed the script component, copied the code within and deleted the script. I closed down VS2019 and created a new script, pasted the code and re-added the component.

I did try to Remove the component and re-add first, but that had no affect.

Not sure why closing down VS2019 and re-creating the script worked, perhaps VS2019 was returning a cached script and did not have the full code..though it was showing the correct code in the inspector.

If anyone else has a similar issue, it maybe the integration of VS2017/2019 with Unity that could cause issues.
> 0 votes

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


# Question
Title: Unity Raycast works only once-Ignores NavMeshAgents
I'm new to unity and just trying to build a game.

I've been trying to use Raycast to detect if an enemy is next to the player and I can't seem to get the Physics.Raycast working properly.

Everything works fine in the scene mode and at the beginning of the start mode.But then it stops responding.

I checked threads with similar issues, but it seems I have all those covered(the most common issue is also addressed-the objects I am attempting to detect have rigidbodies and box colliders attached to them)

This is the script I'm working with.

```
public class hitPlayer : MonoBehaviour
{

    public GameObject player;
    public Transform m_transform;
    Animator playerAnimator;
    int layerMask;
    RaycastHit m_Hit;
    float maxDistance = 5f;

void Start()
{
    layerMask = 1 << 8;
    layerMask = ~layerMask;

    playerAnimator = player.GetComponent<Animator>();
}
public void onTouch()
{

    bool isHit = Physics.Raycast(m_transform.position, -m_transform.right, out m_Hit, maxDistance, layerMask);

    if (isHit)
    {
        playerAnimator.SetTrigger("leftHit");
    }
    else
    {
        playerAnimator.SetTrigger("rightHit");
    }

}
void OnDrawGizmos()
{

    bool isHit = Physics.Raycast(m_transform.position, -m_transform.right, out hit, maxDistance,layerMask);
    Debug.Log(isHit);
    if (isHit)
    {
        Gizmos.color = Color.red;
        Gizmos.DrawRay(m_transform.position, -m_transform.right * hit.distance);
    }
    else
    {
        Gizmos.color = Color.green;
        Gizmos.DrawRay(m_transform.position, -m_transform.right * maxDistance);
    }
}
}

```

Would highly appreciate your assistance in fixing this issue which is to get the raycast working right throughout the game. Thanks in advance.

# Answer
I don't know why this works, but this is how I got my problem fixed. I believe the problem occurs when you have both a navmesh agent on the object as well as a rigidbody. Remove the rigidbody and it should work pretty well.

But in my case I changed the Collision Detection on the rigidbody component of my Nav Mesh Agent GameObject from 'Discrete', to 'Continuous' instead.This gave me the best results and the Raycast works just as expected.
> 0 votes

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


# Question
Title: Nav Mesh Agents are not moving along the mesh
I'm fairly new to unity.I've been playing with Nav Mesh Agents lately.I have encountered this problem twice.The first time I didn't bother redoing my project all over again.But now its bothering me too much.

I initially had a NavMesh baked along the road in my game.But later I had to change the layout of the roads, hence I had to rebake the Nav Mesh.

But now I'm having the problem where the agents are not moving along the Nav Mesh to Reach the destination, but instead they "try" to move along the shortest path.As a result of this all agents gather to a point rather than moving along the track.I've shown below a picture to better illustrate my problem.

They try to move along the red line instead of going along the road and then getting to the destination.

I'm pretty confident that nothing's wrong with my code because it worked earlier and works well in other scenes.Is there anything I missed when re-baking the Nav Mesh?Any help to get the agents to move along the road is much appreciated? Thanks in advance.

# Answer
> 1 votes
To make your NavMesh agents walk only on roads you have a few choices:

1. Only make roads walkable. This can be done by setting only road GameObjects to use Navigation Area "Walkable" and make terrain use "Not Walkable" area. Check "Navigation Static" for both to include both in NavMesh generation. These settings can be found in Navigation panel's "Object" tab.
2. If you have separate road mesh and it isn't intersected by any other object (which you would consider to be an obstacle for an agent), I think you could possibly only set road GameObject as Navigation Static and set its Navigation Area as "Walkable" and ignore the terrain GameObject completely.
3. Make both roads and terrain use Navigation Area "Walkable" but set the terrain to have higher cost. You can define areas and set their costs from Navigation panel's "Areas" tab. Define a new area for terrain and make it have higher cost. Also set your terrain meshes to use this area from Navigation panel's "Object" tab (Navigation Area dropdown). Note that if your path along road is very long and target is near agent, agent might take the short path across terrain mesh.

---
Tags: unity, path-finding, navmesh
---


title: Managing shared dll correctly in Unity

text:
# Question
Title: Managing shared dll correctly in Unity
I'm developing a dll that is to be used in two Unity projects.

I've read that the way to reference a dll is to drag it into a 'plugins' folder so that it is added to the Unity project's dependencies, as their is no "add reference" available for this project in Visual Studio.

But doing that the Unity project does not take into account that the dll evolves (as it is still in development).

What I'd like (if possible) is to set up an automatic way so that the Unity projects update their dependencies when the shared dll is updated.

I've try the reimport option (right click on the dll in Unity) but it seems that it is not working.

What is the best way to manage this situation?

# Answer
You can edit the msbuild config of the dll to have it automatically be placed in the plugins folder on compilation. InfallibleCode has a video on this somewhere on YouTube
> 1 votes

# Answer
It seems like less an issue with Unity, more one with Mono not handling updated dlls very well. It's been discussed on Unity Answers.

It looks like the two options for solving this are:

1) Restart Unity each time a dll is updated 2) Implement a wrapper around your library that uses `LoadLibrary/GetProcAddress` instead of `DllImport`
> 2 votes

---
Tags: unity, dll
---


# Question
Title: How to handle normal vector when duplicating vertex?
I'm currently developing a UV mapping, such as the UVW Map Modifier in 3ds Max (Not Unwrap UVW Modifier).

I split the vertices of the model in the form of a primitive shape (Box, Plane, etc.) and set UV coordinates. However, in the process of duplicating the normal vector, i ran into a problem.

For example, there is a box model with 8 vertices. We need to split the vertices into 24 in order to mapping texture to the 6 sides of the box and set normal vectors separately. In the case of the box, the normal vector calculation is simple. After splitting the vertices, calculate the normal vector for each triangle.

The problem is when this algorithm is applied to the Sphere model. Split the vertices of the sphere model into a Box Shape. (Box Shape is one of the functions of UVW Map modifier). Setting the UV coordinates is fine. The problem is the normal vector setting of the seam vertices.

Simply calculating the normal vector for each triangle, the normal vector of the vertices of the seam is different. (duplicated vertices have the same position). If the normal vector is different, the lighting is not applied properly. Of course, this is solved by calculating the normal vector of the Sphere model before splitting the vertices. However, this method could not be applied to a box model with 8 vertices. The three split vertices of the box must each have a different normal vector.

In summary, split vertices may have different normal vectors or may have the same normal vector. How would you like to solve this? (I used the Box and Sphere model as an example, but in practice it should be applicable to a variety of models.)

# Answer
> 1 votes
Add an angle parameter. Compute the normal for each triangle, if the angle between adjacent triangles is more than the parameter angle, duplicate the vertex between them. Each copy gets the normal of its triangle, creating a seam.

---
Tags: directx11, uv-mapping, vertex, normals
---


# Question
Title: How can I let the user choose his own background image?
Dear Stackoferflow Fourm I would like to have a function in my Android Game Programming that allows the user to choose his own background image (I would like to let the user change the plane image) Unfortunately I have no idea how I could do that. If someone knows how to do it I would be very happy.!

# Answer
At it's most fundamental, you need to load an image into a texture and then apply that texture to a material. You can do that as follows:

```
 public void SetImage(string filePath) {
     // Create a variable to hold the texture
     Texture2D tex = null;
     byte[] fileData;

     // Check file exists
     if (File.Exists(filePath)) {
         // Read contents into a byte array
         fileData = File.ReadAllBytes(filePath);

         // Create a new texture and load the image data
         tex = new Texture2D(2, 2);
         tex.LoadImage(fileData);
     } else {
         Debug.LogWarningFormat("{0} not found", filePath);
     }
     // Set the main texture for the material on the current object's renderer
     this.GetComponent<Renderer>().material.mainTexture = tex;
 }

```

The more interesting part comes when you want to do this with a user-selected file.

First of all, you need to work out which platforms you want to support. A file browse dialog on Windows is radically different to one on Android.

Next, you need to decide how long this will persist. If it's just until the game closes, you're fine.

If, on the other hand, you want to persist across game restarts then you need to do one or two things:

* Pick/develop a mechanism to allow you to remember which file (the|each) user chose.
* Optionally make a "safe" copy of the image somewhere in your application's data directory, so that if the original is deleted, you can continue to show it in-game. \[again, this will depend significantly on which platforms you support\]
> 1 votes

---
Tags: unity, c#, android, image, visual-studio
---


# Question
Title: Is Dedicating A Thread To Inputs A Good Idea In Game Design?
Say I design my game targeting a specific PC to run it on 120 frames per second. And say I need to get Input data from the controller at a frequency of 800 times per second, and feed that input data to the game thread for it to choose whatever manipulation it wants to do with that data.

Is that a really good option for me to try to design, or are there major negative aspects to that concept at face value?

End of the question.

Additional notes of relevance: In a highly competitive online action game. I would like to handle inputs much more frequently than 120, 140 or 60 fps of game thread. For two reasons, one inside the game thread itself I would like to know very frequent input data calculated to help give the desired input value for pure game design reasons. The second reason is that the input thread will have close functionality to networking logic where I want to send inputs prior to when they will be implemented in the local game logic itself (some 20-25 ms prior) and I want to send them the moment I see fit despite at what point in the game frame we currently are. A frame of 8 ms, 16ms, or 30 ms is a very long period for our game logic to tolerate over a network. The game is built sufficiently well as an offline prototype and now it is being put under the hammer of online limitations and specifications. Threading inputs and networking outside of the game main thread seems on paper a very promising option. I want to know whether it is feasible to pursue. I really need an opinion from an expert, or at least a knowledgeable programmer because the issue is such a pivotal decision in my work.

# Answer
You don't gain any benefit from polling for input faster than you act on it.

Even if you read the input early on your input thread, it's just going to sit in queue for the next game update step to pick it up, accomplishing nothing in the meantime.

So the situation is equivalent to the game update thread just reading all the input since the last update, and applying it directly to the current update step.

Keeping input on the game update thread is architecturally simpler, and avoids the risk of variations in thread timing making your controls feel inconsistent. (eg. with a 200 hz input loop and a 120 hz game update loop, sometimes your update loop gets 2 input samples, sometimes it gets 1, creating a beat frequency in your control responsiveness)
> 2 votes

---
Tags: architecture, input, multithreading
---


# Question
Title: How to remove or disable an extension asset in Unity 2020
I've been running Unity 2020.1 on Ubuntu 19.04 without any problems for a while now. Today, I installed the VSCode extension asset and now Unity just crashes during startup. I choose my project from Unity Hub, the splash screen and progress bar pops up, and then everything just shuts down.

I've already submitted a crash report but I'd rather just revert the extension entirely so I can get working again. I've tried deleting the files from disk but Unity just downloads them again during startup.

How can I either remove or disable the VSCode extension completely without starting Unity?

# Answer
> 0 votes
Back up your project. Don’t open unity until the end of these steps.

Then, You can delete the library folder. Then, in the packages folder, open manifest.json and delete the entry for the vscode add on. Careful you don’t make a syntax mistake. Then do the same in package-lock.json in the same folder. Then make sure unity is up to date. And reopen.

This solution assumes you are using a relatively new unity version \>= 2019

---
Tags: unity
---


# Question
Title: Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spin : MonoBehaviour
{
    public Vector3 targetRotation;
    public float duration;
    public bool spinInUpdate = false;

    // Start is called before the first frame update
    void Start()
    {
        if (spinInUpdate == false)
        {
            StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration));
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (spinInUpdate == true)
        {
            transform.Rotate(new Vector3(0, 1, 0));
        }
    }

    IEnumerator LerpFunction(Quaternion endValue, float duration)
    {
        float time = 0;
        Quaternion startValue = transform.rotation;

        while (time < duration)
        {
            transform.rotation = Quaternion.Lerp(startValue, endValue, time / duration);
            time += Time.deltaTime;
            yield return null;
        }
        transform.rotation = endValue;
    }
}

```

slant I mean this is how it's rotating with the Coroutine the small cube that rotate is in slant :

When using the Update way it's rotating fine and this is how it should rotating also with the Coroutine for example on the X only :

The small cube when rotating either in update or in the Coroutine should not be slant. but it's slant in the Coroutine.

And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ?

About controlling the speed in the Update I just added a global float variable and in the Update :

```
transform.Rotate(new Vector3(0, Time.deltaTime * rotationSpeed, 0));

```

and it's working for the speed.

# Answer
The coroutine is adjusting the world rotation, not the local rotation. Try using local cords.

If this is not the case you might need to include more information about what you are trying to accomplish, and what is going wrong. As is it’s a little unclear.
> 1 votes

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


# Question
Title: How can I load assets dynamically on user's input in LibGDX HTML?
I am working with LibGDX and GWT and I am trying to publish my app as a HTML webapp, it has many assets with around hundred of folders, now I want to load them dynamically (user input is sent to JSNI, and security issues set aside), I want to be able to add more assets later without having to recompile the entire thing or creating new assets.txt file.

Here is how the app works. A user select a `foldername` from an HTML dropdown, this will trigger an javascript function created by JSNI: `load(foldername)`. The app then load the files inside `foldername` and use it by accessing `FileHandle file` provided by `Gdx.files.internal(file)`

My goal is to be able to add more assets later on without recompiling/touching the java source code, and to eliminate load time so as not to preload hundreds of assets

I was unable to find similar problem anywhere on the Internet and I am fairly new to this field.

Workaround can be accepted too. I am using LibGDX 1.9.12 and GWT 2.8.2

# Answer
> 0 votes
I settled with this solution. Be sure to checkout the example project at the bottom of the article to have things work properly

---
Tags: libgdx, input, html5, assets, preload
---


title: The gameloop is stucking the window

text:
# Question
Title: The gameloop is stucking the window
I tried to display a player image in a 800x600 window using PyGame but when I try it, the window just gets stuck (immovable with mouse drag, minimize,maximize and close button is stuck and not clickable).

I have no Idea for the reason.

**Here's the code:**

```
from pygame.locals import *
pygame.init()

fps = pygame.time.Clock()

WINDOW_SIZE = (800, 600)
pygame.display.set_caption("Game")
screen = pygame.display.set_mode(WINDOW_SIZE, 0, 0)

player_image = pygame.image.load("Witch.png")
location = [0,0]

while True:

    screen.blit(player_image, location)

    pygame.display.update()
    fps.tick(60)

pygame.quit()

```

Please help me where I have made a mistake or what I should do. Thanks in advance.

# Answer
You need to handle events regularly. Usually that is calling `pygame.event.get()`. For example:

```
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

```

If you are doing nothing with the events, you can call `pygame.event.pump()` instead.
> 1 votes

---
Tags: python, game-loop, pygame, image, mouse
---


# Question
Title: Why one `colorKey` in `ParticleSystem` cannot be changed without a new Gradient?
My question is partly a continuation of this question. So, why I can't change just one `GradientColorKey` this way (without replacing the whole `Gradient` instance):

```
ColorOverLifetimeModule colorOverLifetime = _particle.colorOverLifetime;
MinMaxGradient color = colorOverLifetime.color;
color.gradient.colorKeys[1] = new GradientColorKey(new Color(1, 0, 0), 0.5f);
colorOverLifetime.color = color;

```

`colorOverLifetime.color` is `MinMaxGradient` struct, so I copy its value in a variable `color`.

The `colorOverLifetime.color.gradient` property is `Gradient` class and there is no need to copy it.

The `colorKeys` property is just an array of `GradientColorKey` struct. So, I assign a new `GradientColorKey` value to the array element that already exists.

Why shouldn't this work?

# Answer
Well, while I was writing this question, I think I found the answer along the way. If you look into the implementation of the `ColorOverLifetimeModule` struct `color` property it should be clear why my code doesn't work:

```
  public ParticleSystem.MinMaxGradient color
  {
    get
    {
      ParticleSystem.MinMaxGradient gradient = new ParticleSystem.MinMaxGradient();
      ParticleSystem.ColorOverLifetimeModule.GetColor(this.m_ParticleSystem, ref gradient);
      return gradient;
    }
    set
    {
      ParticleSystem.ColorOverLifetimeModule.SetColor(this.m_ParticleSystem, ref value);
    }
  }

```

in the getter *they return a reference to a copy* of the `MinMaxGradient` instance.

So, I tried to fix my code this way:

```
ColorOverLifetimeModule colorOverLifetime = _particle.colorOverLifetime;
MinMaxGradient color = colorOverLifetime.color;
var gradient = color.gradient;
gradient.colorKeys[1] = new GradientColorKey(new Color(1, 0, 0), 0.5f);
color.gradient = gradient;
colorOverLifetime.color = color;

```

but this still didn't work. I noticed that `colorKeys[1]` hadn't changed after the assignment. I could find only this piece of implementation of the `Gradient` class `colorKeys[]` property:

```
extern public GradientColorKey[] colorKeys
{
    [FreeFunction("Gradient_Bindings::GetColorKeys", IsThreadSafe = true, HasExplicitThis = true)] get;
    [FreeFunction("Gradient_Bindings::SetColorKeys", IsThreadSafe = true, HasExplicitThis = true)] set;
}

```

so I can't say what's going on in there. Likely, they use the same pattern - return a copy of the array.

If so, it should work this way:

```
ColorOverLifetimeModule colorOverLifetime = _particle.colorOverLifetime;
MinMaxGradient color = colorOverLifetime.color;
var keys = color.gradient.colorKeys;
keys[1] = new GradientColorKey(new Color(1f, 0f, 0f, 1f), middleColor.time);
color.gradient.colorKeys = keys;
colorOverLifetime.color = color;

```

and it really does!

*Summary: we don't need to explicitly recreate the `Gradient`, but we need to copy all these properties to variables and then copy them back.*

**P.S.** To me this looks like a very unintuitive approach that makes C# developers stumble over such things and spend extra time trying to figure out what's wrong (thanks we've got decompiled Unity sources, otherwise we could only guess). I think methods might be better candidates for such tricks - at least developers won't have certain expectations as they have about properties.
> 1 votes

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


# Question
Title: Is it a bad idea to store functions inside components in ECS?
Say I have three entities: `Player`, `Spikes`, and `Zombie`. All of them are just rectangles and they can collide with each other. All of them have the `BoxCollision` component.

So, the `BoxCollison` system would look something like this:

```
function detectCollisions () {
  // for each entity with box collision
    // check if they collide
      // then do something
}

```

The issue is, the sole purpose of the `BoxCollision` component is to detect collision, and that's it. Where should I put the game rules, such as "if the Player collided with Spikes, diminish its health" or "if the Zombie collided with Spikes, instantly kill the Zombie"?

I came up with the idea that each `Entity` should have its `onCollision` function.

Programming languages such as Javascript and F# have high-order functions, so I can easily pass functions around. So when assembling my `Player` entity, I could do something like:

```
function onPlayerCollision (player) {
  return function (entity) {
    if (entity.tag === 'Zombie') {
      player.getComponent('Health').hp -= 1
    } else if (entity.tag === 'Spikes') {
      player.getComponent('Health').hp -= 5
    }
  }
}

const player = new Entity()
player.addComponent('Health', { hp: 100 })
player.addComponent('BoxCollision', { onCollision: onPlayerCollision(player) }
// notice I store a reference to a function here, so now the BoxCollision component will execute this passing the entity the player has collided with

```

```
function detectCollisions () {
  // for each entity with box collision
    // check if they collide
      onCollision(entity)

```

`onPlayerCollision` is a curried/closure function that receives a player, and then returns a new function that wants another Entity.

Are there any flaws with this? Is it okay for components to store references to functions? What are other ways of avoiding game rules in components? Events?

Thanks!

# Answer
> 2 votes
A common pattern in ECS is to add a single-use, disposable tag component after a collision.

So you have a collision detection system. If you detect a collision between say a spikes and a zombie, you add a WalkedOnSpikes component to your zombie, and a ZombieWalkedOnMe component to your spike.

Then you have separate systems that query for any zombies with the tags or and spikes with the tags on them to handle the result. This means your collision system doesn’t “care” what happens. It just registers the collision. Then your specialized systems actually handle the result.

# Answer
> 2 votes
When you do "ECS by the book", then all logic belongs into systems and all data belongs into components. That means a component should never have a function.

What's a rather common architecture in ECS for collision handling is one system which detects collisions and other systems which then react on the collisions detected by the first system. This could be implemented by adding a `Collisions` component to your entities which contain a list of objects they collided with this tick. Another common option would be to use an event queue. Your collision detection system fills that queue and your collision response system(s) then consume them.

But another question is if "ECS by the book" is actually the right approach for you. Most of the performance advantages of ECS shine in programming languages like C++ where the developer has a lot of control over when and how memory is allocated. But JavaScript is no such a language. You can really only hope that the JS engine (of whatever browser the player prefers to use) figures out how to represent your data in a way which minimizes cache-misses. So when you feel that adding logic to components makes your code more readable and maintainable, don't let me stop you.

---
Tags: javascript, entity-system, entity-component-system
---


title: No shadow on custom model

text:
# Question
Title: No shadow on custom model
I have custom low poly model ,the thing is it is not receiving shadows.

Unity's default plane do receive the shadow but not my low poly plane.

Here is image that demonstrate more,

# Answer
Few things you might want to check:

1. Your custom plane has a mesh renderer with "Receive shadows" checked.
2. Your second cube has "cast shadows" checked
3. Your light's culling mask.
> 0 votes

# Answer
From description and image the first thing I'd check are normals. First check if normals are *imported* by selecting your model file (Model panel). If so, in the **Normals** section try to change from **Import** to **Calculate**. Alternatively, check in your 3D editing software if the normals are properly distributed; if not, fix and reimport. It could also be a geometry problem; make sure you don't have overlapping faces or misplaced vertices. (What happens if you import a sphere from the same software and with the same format?)
> 0 votes

# Answer
There is another possiblity.

One use a custom shader with no `ShadowCaster` pass, while doesn't have a fallback to "Diffuse" or other Unity built in shaders which have the `ShadowCaster` pass.

Or someone don't like the fallback and comment it out, no aware of the shadow issue.
> 0 votes

---
Tags: unity
---


# Question
Title: LibGDX How can I draw a line at a specific angle
I'm working on a 2D platformer, shooter game and I'm attempting to draw a line to serve as a guide to indicate where the player is shooting. The line should be drawn from the player's sprite to the mouse's position. I need to draw a line between the player and the mouse, at the angle from the player to the mouse, how can I do something like this? Here is a concept picture to explain what I'm talking about:

# Answer
you should use ShapeRenderer for this.

In your draw loop

```
batch.begin();
// Draw sprites and stuff here so the line will be draw on them and not under
batch.end();

shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(1, 0, 0, 1); // Red line
shapeRenderer.line(player.x, player.y, mouse.x, mouse.y);
shapeRenderer.end();

```

This will let you draw a red line between the player and the mouse, the angle will be determined automatically by the x,x2 and y,y2. (You can still compute it if you want to).

I let you the implementation part (draw only on some conditions etc)
> 4 votes

# Answer
Accepted answer is good, but I couldn't use ShapeRenderer as it need to be used on closed batch.

In that case you can use ShapeDrawer which is ShapeRenderer that can be used on open batch.
> 2 votes

---
Tags: libgdx, trigonometry, lines
---


# Question
Title: How do I procedurally generate rivers on a tilemap with thickness?
I have read numerous articles on the subject but can find none that can explain to me how it is that procedural river generation achieves a certain amount of thickness to the river. I have managed to pice together that I must search for perpendicular vectors to the one I use to construct the river, but am not sure how that is implemented. I am working on a 2D game with tilemaps implemented and don't know how I iterate through the tiles to achieve the intended result.

I am fairly intermediate when it comes to game development and have just started proc-gen games. Please try to answer simply as to how to do this. I know that others have figured it out and want an answer.

How do I set the thickness of procedurally generated rivers?

**EDIT**

I am able to code simple straight lines and have access to an astar algorithm to connect two points together, but my river is literally one tile thick. I want to increase its size and I am not proficient in other programming languages enough yet to be able to read through source code.

The rivers I want just need thickness to them. I just need whatever technique others might use to produce rivers or roads thicker than a single tile.

# Answer
If your only requirement is plotting out a thicker line of river tiles along a path of points, you can simply do the following:

To get a river of width `w` then for each `(x,y)` position along the path:

```
for(Point p : path){
   for(int a=0; a<w; a++){
      for(int b=0; b<w; b++){
         mapTile[p.x+a][p.y+b] = river;
      }
   }
}

```

This is a brute force approach in that it will blindly set the same tiles to the same value multiple. In my situation I only used it during initialization & found that it executed fast enough that it wasn't worth optimizing.
> 2 votes

---
Tags: 2d, algorithm, procedural-generation, vector, tilemap
---


title: How do I set up unit tests in Unity?

text:
# Question
Title: How do I set up unit tests in Unity?
I have followed the Unity Test Framework documentation to create an EditMode test assembly and a test script. When I try to test a function like `Utils.SomeMethod()`, the class is not recognized.

My IDE gives me the option to `Reference Assembly-CSharp and use Utils` which seems to successfully import the class as I gain autocomplete ability on the function names. But as soon as I try to run the test, the text changes back to red and I get a message that `The name Utils does not exist in the current context`.

What do I need to do to be able to test my class?

# Answer
You should create an Assembly Definition for your main code. By default, Unity creates a predefined one called `Assembly-CSharp`, but this can't be manually referenced. The docs give a good understanding of what Assembly Definitions are.

Then you can right-click the project folder and choose to create a test assembly, adding your main assembly as a reference. You do this by clicking the little plus under the References section. I always make sure the test assembly is set to only the Editor, so it gets excluded from builds.

If you use Nsubstitute, you’ll need to reference that dll as well if it’s in your Plugins folder.

To see if it works, create a test; it should appear in the Unity Test Runner window and be able to run.
> 0 votes

---
Tags: unity, testing, unit-testing
---


# Question
Title: What is the hardest thing in game development process?
I am new to the game-dev area, although I have professional experience in programming and some other qualities like making graphics in Photoshop or 3D modelling. Currently I am learning one widely used game engine connected with another free 3D modeling tool and my problem is that from my beginner's perspective, it all seems relatively easy and I know that this is not true. Right now It seems I can find all knowledge I need in some online tutorials, courses and if something is missing I can still ask a question on websites such as this one.

I plan to do an FPS multiplayer game as my first game and I wonder what is the hardest (most time, energy or money consuming) stage of game development in 2020?

I am asking because right now I think I can make 30-50% (prototype and some assets like 3d models) of the game myself in around year period of time and maybe later get more money to finish the project, but I know it is not true and this is only my beginner's unexperienced imagination, because similar games are usually being done by a team of experienced developers and their games still have bugs, glitches and other issues and I know some other similar but amateur projects that were started by one or two people and eventually were abandoned due to unknown reason (mostly lack of time I assume). So I am wondering what are the stages that cause most amateurs to fail and abandon their ideas, is it modeling, programing, networking, debugging?

# Answer
**Polishing** because it's the biggest unknown. And don't forget **Game Design** ;)

It's generally said that the first 90% of a game take half your development time, the other half is spent on the remaining 10% (at least i was taught that at university). The hardest stage is polishing, because - as you said - creating the core game mechanics and assets is all doable and relatively plannable.

But when it comes to how exactly those mechanics interact with each other, there is just some unpredictability and it can be very hard to "get it right" and make the game "feel" right.

Performance / optimization / debugging can also be an issue here. There are a lot of well known (and arguably good) games which were released because the developer ran out of money but could have been so much better with a few more months of polishing (e.g. Stalker).

I think most abandoned amateur projects were abandoned during polishing aswell.

However, if you know exactly what kind of game you want to make and how your concept will work out (which you usually don't and probably shouldn't), or you are making a game where performance won't be much of an issue (like some 2d pixel art), polishing phase can also be very short.

Also, if this is your first game ever, try something very small in scope and focus on finishing it. Probably do a few very simple games as practice before you devote a year of your time, or do a prototype of your game containing some core game mechanics.
> 2 votes

---
Tags: game-design, content-generation, workflow, time-management
---


# Question
Title: How to move one Game unit with every key press?
I have a tile board set up with 500 x 500 pixels = 1 unit. I have code that will move the object over time.

```
    void Update()
{
    Vector2 pos = transform.position;

    if (Input.GetKey("w"))
    {
        pos.y += speed * Time.deltaTime;
    }
    if (Input.GetKey("s"))
    {
        pos.y -= speed * Time.deltaTime;
    }
    if (Input.GetKey("d"))
    {
        pos.x += speed * Time.deltaTime;
    }
    if (Input.GetKey("a"))
    {
        pos.x -= speed * Time.deltaTime;
    }
    transform.position = pos;
}

```

I want to move 1 unit after each button press and only by integer values. Speed is a public variable that sets how fast the object moves.

Thanks for the help.

# Answer
> 0 votes
This solution is for grid based games. The idea is to have "turns". A turn will happen regardless of whatever or not there is input or not. At the end of the turn the avatar will be aligned to the grid, and a turn always takes the same time.

Pseudo-code:

```
var current_time = get_current_time();
var elapsed_time = current_time - start_time;
var got_input = get_input();
input = got_input ?? input;
if (elapsed_time > turn_duration)
{
    elapsed_time -= turn_duration;
    start_time += turn_duration;
    start_position = end_position;
    end_position = compute_next_position(start_position, input);
}

current_position = interpolate(start_position, end_position, elapsed_time);

```

---

The duration of the turn can be computed from the velocity and the size of the grid. We know that `speed = distance / time`, solve for time:

```
speed = distance / time

=>

time * speed = distance

=>

time = distance / speed

```

Thus:

```
turn_duration = grid_side_length / speed;

```

---

We are storing where it was at the start of the "turn", and where it will be at the end of the turn. Those positions should be aligned to the grid. We use the elapsed time since the start of the turn to compute the current position via interpolation.

When, the turn ends, we use the input and the last position to compute the next position. That would be the position plus the size of the grid in the direction dictated by input, if any.

You can buffer input if you like. You can treat no input as going in the same direction if you like.

---

We can make the `end_position` nullable (declare it `Vector2?` instead of `Vector2`), and take that as signal that no movement is happening at the moment. We can also work with `end_time` instead of `elapsed_time`. *Similarly make `end_time` nullable.*

```
var current_time = get_current_time();
var got_input = get_input();
input = got_input ?? input;

if (input != null && end_position == null)
{
    start_time = current_time;
    end_time = start_time + turn_duration;
    start_position = current_position;
    end_position = compute_next_position(start_position, input);
}

if (end_time == null || end_position == null)
{
    return;
}

if (current_time > end_time.Value)
{
    current_position = end_position.Value;
    end_position = null;
    end_time = null;
}
else
{
    current_position = interpolate(start_position, end_position.Value, elapsed_time);
}

```

The above code differs in that it will move when it gets some input, and stays there until new input arrive. Note, however, that it will not interrupt the current motion. I do not know what you may want to happen when a key is pressed while the object is moving, it varies from game to game. However, the key to interrupt the motion is to drop the check for `end_position == null`, and be careful to set the new `end_position` still on the grid.

---

In my implementation for Unity and Godot, I made a `Motion` struct to encapsulate some of this. It holds start and end position, and also duration, and will do the interpolation given the elapsed time since the start of the motion. I also ended up accumulating delta time (`Time.deltaTime`) instead of using current time.

My code looks something like this (this is Unity code):

```
if (!_motion.HasValue)
{
    var nextMotion = NextMotion(transform.position, GetNewTarget(), speed);
    if (nextMotion != null)
    {
        _motion = nextMotion;
        _time = 0.0f;
    }
}

if (!_motion.HasValue)
{
    return;
}

_time += Time.deltaTime;
var motion = _motion.Value;
if (_time > motion.Duration)
{
    _motion = null;
    transform.position = motion.End;
}
else
{
    transform.position = motion.GetCurrent(_time);
}

```

`GetNewTarget()` computes a target position based on input. In your case, it should check the input, and if there is any, add to the current position the length of the side of the grid in the appropriate direction.

`NextMotion` creates a new motion, given the current position, the target position, and the speed.

As you can imagine `GetCurrent` is a linear interpolation. Its code is simply:

```
return Start + ((End - Start) * time / Duration);

```

Where `Duration` is pre-computed as:

```
var diff = end - start;
var length = diff.magnitude;
Duration = length / speed;

```

---

If you want to allow interrupting motion, the code should look something like this:

```
var target = GetNewTarget();

if (!_motion.HasValue || _motion.Value.End != target)
{
    var nextMotion = NextMotion(transform.position, target, speed);
// ...

```

And `GetNewTarget` would work from the start position of the current motion if any, if there is no current motion the use the current position.

# Answer
> 0 votes
When you want to do a thing each time the player presses a key and not all the time while they are holding a key, use `Input.GetKeyDown`. This method only returns true on the first Update when the player starts pressing a key.

```
if (Input.GetKeyDown(KeyCode.W))
{
    pos.y += 1.0f;
}

```

But perhaps you don't want that movement to be instantaneous and instead animate a smooth movement to the new destination. You can to that by having keypresses not set the new position directly but instead change the position where the object *should* be. And then you add some code to Update which slowly moves the object form its current position to the desired position. You could implement that by adding a new variable `Vector3 desiredPosition` to the object. Then you add additional code in `Update` which moves the object from its current `transform.position` towards `desiredPosition`. The simplest form would be to just have linear movement with constant velocity, which can be done with `Vector3.MoveTowards`:

```
transform.position = Vector3.MoveTowards(transform.position, desiredPosition, speed * Time.deltaTime);

```

But you might also want to experiment with some fancier ways of animating that move, like using some interpolation or tweening algorithm, perhaps by using a 3rd party library like DOTween.

---
Tags: unity, 2d, movement
---


title: Self-sorting objectives list in Unity

text:
# Question
Title: Self-sorting objectives list in Unity
I'm new to Unity and C#, so I'll try to be as thorough as possible. I'm working on an objectives menu for my game (in Unity) and I'm not sure how to implement a behavior I'd like it to have (the sorting part).

**Desired behavior:**

* List all the current objectives
* When an objective is completed, it disappears from the list
* Sort objectives such that they're all in a column with no extra rows between them (this is the part I can't figure out)

**Current setup and behavior:**

Objective information (name, description, visibility) is stored as public strings in a script attached to empty gameobjects.

I set up 10 TextMeshPro text boxes I'm calling "slots". 5 for objective names, 5 for objective descriptions.

I have a script called ObjectiveHandler that takes information from the Objectives scripts attached to it and "writes" it to the slots. Here's what that looks like in the inspector.

And the script itself.

```
using UnityEngine;
using TMPro;

public class ObjectiveHandler : MonoBehaviour
{

private TextMeshProUGUI[,] slots = new TextMeshProUGUI[2, 5]; //Column 0 is for names, column 1 is for descriptions

[Header("Name")]
public TextMeshProUGUI name1;
public TextMeshProUGUI name2;
public TextMeshProUGUI name3;
public TextMeshProUGUI name4;
public TextMeshProUGUI name5;
[Header("Description")]
public TextMeshProUGUI desc1;
public TextMeshProUGUI desc2;
public TextMeshProUGUI desc3;
public TextMeshProUGUI desc4;
public TextMeshProUGUI desc5;

private bool[] slotInUse = new bool[5];
//Indicates if the slot is in use.

private Objective objectiveInfo; //a sort of "go between" between the Objective script and this one.

public GameObject [] objList = new GameObject[5]; //array of objective gameobjects
private bool[,] objStatus = new bool[2, 5]; //Column 0 is objective visibility, column 1 is if the objective is in use
private int index = 0;
private string objectiveName; // Holds the current indexed objective's name
private string objectiveDesc; // Holds the current indexed objective's description

private void Start()
{

//Load names UGUI into slots array
    slots[0, 0] = name1;
    slots[0, 1] = name2;
    slots[0, 2] = name3;
    slots[0, 3] = name4;
    slots[0, 4] = name5;
    //Load desc UGUI into slots array
    slots[1, 0] = desc1;
    slots[1, 1] = desc2;
    slots[1, 2] = desc3;
    slots[1, 3] = desc4;
    slots[1, 4] = desc5;
}
private void Update()
{
    Sort();
}
void Sort()
{
    for (index = 0; index < 5; index++)
    {
        objectiveInfo = objList[index].GetComponent<Objective>(); //variables in Objective
        objectiveName = objectiveInfo.objectiveName;
        objectiveDesc = objectiveInfo.objectiveDescription;
        objStatus[0, index] = objectiveInfo.visibility;
        if ((objStatus[0,index] == true && objStatus[1,index] == false) && slotInUse[index] == false) //if the obj is visible and not in use
        {
             WriteUI(objectiveName, objectiveDesc, slots[0, index], slots[1, index]);
             objStatus[1, index] = true; //this obj is now in use
             slotInUse[index] = true;
        }
        else if ((objStatus[0, index] == false && objStatus[1, index] == false)) //if the obj is not visible and not in use
        {
            //Do nothing
        }
        else if ((objStatus[0, index] == false && objStatus[1, index] == true) && slotInUse[index] == true)
        {
            //ERASE
            EraseUI(slots[0, index], slots[1, index]);
            objStatus[1, index] = false; //this obj is now in use
            slotInUse[index] = false;
        }
    }
}
void WriteUI(string Name, string Desc, TextMeshProUGUI uiName, TextMeshProUGUI uiDesc) //writes ui text to TMP UGUI and indicates that the slot is in use
{
    Name = objectiveName;
    Desc = objectiveDesc;
    uiName.SetText(Name);
    uiDesc.SetText(Desc);
}

void EraseUI(TextMeshProUGUI uiName, TextMeshProUGUI uiDesc)
{
    uiName.SetText("");
    uiDesc.SetText("");
}
}

```

So far the objective names, descriptions and visibility are being read by the script, they're erasing when the objective is set to !visible and writing when it's set to visible.

**What I can't figure out**

I'd like to make it so that when an objective is set to !visible and the info in its slot is erased (and therefore, the slot is set to !inUse) the information in the boxes below it are shifted up.

**Example scenario**

There are currently 5 objectives. The objective in slot 3 is completed, so its visibility parameter is set to false (!visible, or "invisible"). Slot 3 is now empty, so the information in slots 4 and 5 shift into slots 3 and 4, respectively.

I concede that there may be better ways of doing this and I'm open to suggestions for improvement. If you can think of a way for me to do this with the setup I already have I'd be elated.

Many thanks in advance!

# Answer
> 2 votes
Per @DMGregory Unity's "Vertical Layout Group" component handles this natively.

I created an empty gameObject and made all of the "slots" for objective names/descriptions children of it. I added the Vertical Layout Group component to the new parent gameObject.

Now, when my objectives are set to !visible, I've scripted it such that they'll disable the gameobject for that slot (the empty gameobject whose children are the name and description TMP text fields), and Vertical Layout Group will automatically rearrange the remaining objectives. I've removed the ObjectiveHandler script and now the Objective script attached to each objective gameobject handles toggling visibility and writing to UI.

```
using TMPro;
using UnityEngine;

public class Objective : MonoBehaviour
{
public string objectiveName;
public string objectiveDescription;
public bool visibility;
public GameObject parent;
public TextMeshProUGUI objectiveNameUI;
public TextMeshProUGUI objectiveDescriptionUI;

void Start()
{
    objectiveNameUI.SetText(objectiveName);
    objectiveDescriptionUI.SetText(objectiveDescription);
}
void Update()
{
    if (visibility == true)
    {
        parent.SetActive(true);
    }
    else
    {
        parent.SetActive(false);
    }
}

}

```

---
Tags: unity, sorting
---


# Question
Title: Is there a way to allow for design-time math on a scriptable object in Unity?
Sorry for the title, I did not know how else to describe the question. I am writing a turn-based strategy game and am looking for a way to enable design-time additions of game mechanics where the mechanics each require some different math.

What I'd like to do is to be able to create a ScriptableObject and then modify it with the formula and various descriptions (all through the inspector), then add it to the game.

As an example, my game has cities where each city has several attributes such as population and various technology levels. I'd like to be able to add various "resource generators" at design-time via the inspector with the formula for how the resource is generated per turn.

Some examples of resource generators:

* A "gold" resource generator with the "population * 0.025" formula to indicate that, each turn, the city generates 2.5% of it's population as gold.
* A "research" resource generator with "assigned population * 0.5" as the formula to indicate that, each turn, the population assigned to research generates 0.5 pts of research per person.
* A "production" resource generator with the "assigned population * production tech level * 0.75" with a max value of "1000 * city level" where excess production gets dumped to gold.

And so on. These are examples, but the formulas should allow for arbitrary interactions with other values in the game.

Some of the simpler formulas seems pretty easy, i.e. create a scriptable object attached to a primary value (say population) and then a simple modifier. But I'm stuck on how to do the more complex ones.

Anyone have an idea about how to accomplish something like this?

# Answer
> 1 votes
I would really recommend to implement mechanics like this in code. There is a limit to how much you can "soft-code" until your soft-coded logic becomes just as complex as hard-coded logic.

But if you really want to go that route, then I have two alternatives for you.

---

The first you might want to look into is a C# feature called reflection. This allows you (among other things) to acquire the value of a variable when you have the name of that variable in a string at runtime.

Example:

```
// these would come from the ScriptableObject
string inputResource = "population"
float factor = 0.025f;
string outputResource = "gold"

// obtaining the value of a variable with the name only known at runtime
FieldInfo inputFieldInfo = city.GetType().GetField(inputResource);
int inputValue = inputFieldInfo.GetValue(city) as Integer;
FieldInfo outputFieldInfo = city.GetType().GetField(outputResource);
int oldOutputValue = outputFieldInfo.GetValue(city) as Integer;

// using the value in your program and writing it back also using reflection
outputFieldInfo.SetValue(city, oldOutputValue + inputValue * factor);

```

One problem you see here is that you have no design-time check that the variable of the class city was entered in the inspector of the ScriptableObject actually exists. So when someone misspelled populaiton, then it would only fail at runtime when `Type.GetField` returns `null`. Another is that reflection can be rather expensive performance-wise, so when you need to do this very often, it might become an FPS hog.

---

But there is also another way which gives you more type-safety and *should* be faster, but has more wide-ranging consequences for your overall software architecture. Instead of writing your class City like that:

```
public class City : MonoBehaviour {
     public int population;
     public int gold;
     public int tech_level;

     void Start() {
         population = 10;
     }
}

```

Put all the properties into an array, and define an enum which can be used as an index to that array:

```
public class City : MonoBehaviour {
     public enum ResourceType {
         POPULATION,
         GOLD,
         TECH_LEVEL
     }

     public int[] resources = new int[3];

     void Start() {
         resources[ResourceType.POPULATION] = 10;
     }
}

```

Now you can refer to individual resource types by values of an enum, and you don't need reflection to do that at runtime.

```
// these would come from the ScriptableObject
City.ResourceType inputResource = City.ResourceType.POPULATION;
float factor = 0.025f;
City.ResourceType outputResource = City.ResourceType.GOLD;

// obtaining the value of a variable with the enum known at runtime
city.resources[outputResource] += city.resources[inputResource] * factor;

```

Yes, *this* piece of code got a lot simpler. But the cost is that any *other* code using city resources which does not need that level of flexibility will get more complicated.

# Answer
> 1 votes
> Just to be able to iterate on the game with various resource generators and resource spenders. I was trying to think of a way to architect the game such that it didn't care how many generators/spenders there were

You can do something like this:

```
public enum Resource {
    Gold, Research, Production
}

public struct ResourceValue {
    private readonly Resource resource;
    private readonly float value;

    public ResourceValue(Resource resource, float value) {
        this.resource = resource;
        this.value = value;
    }

    public Resource Resource => resource;
    public float Value => value;
}

public abstract class ResourceGenerator : ScriptableObject {
    //Generates and returns a resource for the given city based on
    //that city's current properties
    abstract public ResourceValue Generate(City city);
}

[CreateAssetMenu(menuName = "Gold Generator")]
public class GoldGenerator : ResourceGenerator {
    [SerializeField] private float populationFactor = .025f;

    override public ResourceValue Generate(City city) {
        return new ResourceValue(Resource.Gold, city.Population * populationFactor);
    }
}

[CreateAssetMenu(menuName = "Research Generator")]
public class ResearchGenerator : ResourceGenerator {
    [SerializeField] private float assignedFactor = .5f;

    override public ResourceValue Generate(City city) {
        return new ResourceValue(Resource.Research, city.AssignedResearchers * assignedFactor);
    }
}

public class City : MonoBehaviour {
    [SerializeField] private List<ResourceGenerator> resourceGenerators;
    [SerializeField] private int population;
    [SerializeField] private int assignedResearchers;

    public int Population => population;
    public int AssignedResearchers => assignedResearchers;

    //call this function each turn to generate resources according to the resource generators we've assigned tot his city
    public void GenerateResources(Player player) {
        //iterate through each generator, run its formula, and apply the generated
        //resources to the player
        foreach (var generator in resourceGenerators) {
            ResourceValue generated = generator.Generate(this);
            player.AddResource(generated);
        }
    }
}

```

Here we create several ScriptableObject classes representing resource generators. Their formulas are coded, but key values that the formulas use are serialized properties that can be edited in the Inspector. We can assign resource generators to a city, and the city will loop through all of its resource generators when generating resources. This way the city doesn't need to know or care the type or quantity of resource generators it has.

---
Tags: unity
---


# Question
Title: All enemies destroyed when only one gets hit
I am trying to implement a new attack into my project. I can get the projectile to spawn and deal damage to an enemy, however, once it deals damage, every enemy gets destroyed instead of just the one that was hit. I am not using any static variables and I cannot figure out why this issue is happening.

Here is the projectile script:

```
 public GameObject HeavyExplosion;
 public GameObject LightExplosion;
 public float HeavyMissileSpeed = 1;
 public float LightMissileSpeed = 1;
 public float HeavyLaserSpeed;
 public float LightLaserSpeed;
 public float HeavyBulletSpeed;
 public float LightBulletSpeed;
 Rigidbody RB;
 public int HeavyMissileDamage;
 public int LightMissileDamage;
 public int HeavyLaserDamage;
 public int LightLaserDamage;
 public int HeavyBulletDamage;
 public int LightBulletDamage;
 public float ProjectileTimeout;
 float TimeElapsed;
 bool HasExploded;
 void Start()
 {
     RB = gameObject.GetComponent<Rigidbody>();
     HasExploded = false;
 }
 void Update()
 {
     TimeElapsed += Time.deltaTime;
     if(TimeElapsed >= ProjectileTimeout)
     {
         Destroy(gameObject);
     }
 }
 void FixedUpdate()
 {
     if (gameObject.CompareTag("HeavyMissile") && !HasExploded)
     {
         RB.velocity = HeavyMissileSpeed * gameObject.transform.forward;
     }
     if (gameObject.CompareTag("LightMissile") && !HasExploded)
     {
         RB.velocity = LightMissileSpeed * gameObject.transform.forward;
     }
     if (gameObject.CompareTag("HeavyLaser"))
     {
         RB.velocity = HeavyLaserSpeed * gameObject.transform.forward;
     }
     if (gameObject.CompareTag("LightLaser"))
     {
         RB.velocity = LightLaserSpeed * gameObject.transform.forward;
     }
     if (gameObject.CompareTag("HeavyBullet"))
     {
         RB.velocity = HeavyBulletSpeed * gameObject.transform.forward;
     }
     if (gameObject.CompareTag("LightBullet"))
     {
         RB.velocity = LightBulletSpeed * gameObject.transform.forward;
     }
 }
 private void OnCollisionEnter(Collision collision)
 {
     if (collision.gameObject.CompareTag("Enemy") && gameObject.CompareTag("HeavyMissile"))
     {
         collision.transform.parent.GetComponent<EnemyHealth>().DealDamage(HeavyMissileDamage);
         GetComponent<MeshRenderer>().enabled = false;
         GetComponent<Collider>().enabled = false;
         RB.velocity = new Vector3(0, 0, 0);
         Instantiate(HeavyExplosion, transform);
         HasExploded = true;
         Destroy(gameObject, 1);
     }
     else if (collision.gameObject.CompareTag("Enemy") && gameObject.CompareTag("LightMissile"))
     {
         collision.transform.parent.GetComponent<EnemyHealth>().DealDamage(LightMissileDamage);
         GetComponent<MeshRenderer>().enabled = false;
         GetComponent<Collider>().enabled = false;
         RB.velocity = new Vector3(0, 0, 0);
         Instantiate(LightExplosion, transform);
         HasExploded = true;
         Destroy(gameObject, 1);
     }
     else if (collision.gameObject.CompareTag("Enemy") && gameObject.CompareTag("HeavyLaser"))
     {
         collision.transform.parent.GetComponent<EnemyHealth>().DealDamage(HeavyLaserDamage);
         Destroy(gameObject);
     }
     else if (collision.gameObject.CompareTag("Enemy") && gameObject.CompareTag("LightLaser"))
     {
         collision.transform.parent.GetComponent<EnemyHealth>().DealDamage(LightLaserDamage);
         Destroy(gameObject);
     }
     else if (collision.gameObject.CompareTag("Enemy") && gameObject.CompareTag("HeavyBullet"))
     {
         collision.transform.parent.GetComponent<EnemyHealth>().DealDamage(HeavyBulletDamage);
         Destroy(gameObject);
     }
     else if (collision.gameObject.CompareTag("Enemy") && gameObject.CompareTag("LightBullet"))
     {
         collision.transform.parent.GetComponent<EnemyHealth>().DealDamage(LightBulletDamage);
         Destroy(gameObject);
     }
     else
     {
         Destroy(gameObject);
     }
 }
 private void OnTriggerEnter(Collider other)
 {
     if (other.CompareTag("Enemy") && gameObject.CompareTag("HeavyMissile"))
     {
         other.transform.parent.GetComponent<EnemyHealth>().DealDamage(HeavyMissileDamage);
         GetComponent<MeshRenderer>().enabled = false;
         GetComponent<Collider>().enabled = false;
         RB.velocity = new Vector3(0, 0, 0);
         Instantiate(HeavyExplosion, transform);
         HasExploded = true;
         Destroy(gameObject, 1);
     }
     else if (other.CompareTag("Enemy") && gameObject.CompareTag("LightMissile"))
     {
         other.transform.parent.GetComponent<EnemyHealth>().DealDamage(LightMissileDamage);
         GetComponent<MeshRenderer>().enabled = false;
         GetComponent<Collider>().enabled = false;
         RB.velocity = new Vector3(0, 0, 0);
         Instantiate(LightExplosion, transform);
         HasExploded = true;
         Destroy(gameObject, 1);
     }
     else if (other.CompareTag("Enemy") && gameObject.CompareTag("HeavyLaser"))
     {
         other.transform.parent.GetComponent<EnemyHealth>().DealDamage(HeavyLaserDamage);
         Destroy(gameObject);
     }
     else if (other.CompareTag("Enemy") && gameObject.CompareTag("LightLaser"))
     {
         other.transform.parent.GetComponent<EnemyHealth>().DealDamage(LightLaserDamage);
         Destroy(gameObject);
     }
     else if (other.CompareTag("Enemy") && gameObject.CompareTag("HeavyBullet"))
     {
         other.transform.parent.GetComponent<EnemyHealth>().DealDamage(HeavyBulletDamage);
         Destroy(gameObject);
     }
     else if (other.CompareTag("Enemy") && gameObject.CompareTag("LightBullet"))
     {
         other.transform.parent.GetComponent<EnemyHealth>().DealDamage(LightBulletDamage);
         Destroy(gameObject);
     }
 }

```

Here is the enemy health script:

```
     public int MaxHealth = 1;
     int HP;

     public GameObject Explosion;
     public EnemySpawnerEternal SpawnReference { get; set; }

     void Awake()
     {
         HP = MaxHealth;
     }

     public void DealDamage(int Damage)
     {
         HP -= Damage;
         if(HP <= 0)
         {
             if(SpawnReference != null)
             {
                 SpawnReference.ResartSpawner();
             }
             GameObject.Instantiate(Explosion, transform.position, Quaternion.identity);
             Destroy(gameObject);
         }
     }
 }

```

# Answer
This is a bit of a guess, but based on my experience with pooling:

You have this line in your enemy health script:

```
SpawnReference.ResartSpawner();

```

I'm guessing that `EnemySpawnerEternal` is some type of spawn-pool system. Perhaps calling `RestartSpawner()` returns all spawned objects to the pool?
> 1 votes

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