title: Game engine with javascript scripting

text:
# Question
Title: Game engine with javascript scripting
Javascript is my favorite language and a few years ago Unity had a options to create JS scripts but its removed for now. So is here any strong engine like Unity wich still support JS for scripting?

# Answer
> -1 votes
As a side note Unity never supported JavaScript as a language. It was UnityScript which was basically a look-alike language.

There is actually quite few alternative to Unity today and none of them support JS. So if you serious about going into game development you sould not limit yourself to JavaScript.

---
Tags: javascript
---


# Question
Title: Allow a game object to pass out of a collider but not back in - Unity
In my game I have enemies that shoot projectiles out at the player, the only way for the player to get rid of them is by guiding them into a structure.

An example of my enemy shooting a projectile.

The problem I have is that sometimes the enemy spawns on top of one of these structures as seen below.

This results in the projectile exploding/colliding with the structure the moment it is spawned.

I'm not entirely sure how to go about fixing this issue.

I have tried to find a way to disable the collider on the projectile for a few seconds but I couldn't get the timer right. I also think this might cause some odd game-play issues.

The second thing I tried was a platform effector, however I could only get it to form a circle and this didn't work out because my structures are of all different sizes and shapes.

If anyone could point me into the right direction or even help me find a better solution I'd be extremely grateful. Thanks

```
ublic class MultiBullet : MonoBehaviour {

    public float speed = 1f;

    private Rigidbody2D rb;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody2D>();

    }

    // Update is called once per frame
    void Update () {
        rb.velocity = transform.up * speed;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        ////Add explosion Effect
        //if (collision.gameObject.tag == "Player")
        //{
        //    // Add game over screen here
        //    Debug.Log("Player Killed");
        //    Destroy(gameObject);
        //}
        ////Debug.Log("BOOM");
        ////Destroy(gameObject);
        if(collision.gameObject.tag != "BulletIgnore" && collision.gameObject.tag != "Cloud")
        {
            //Debug.Log("BOOM");
            Destroy(gameObject);
        }
    }
}

```

Just a simple class to handle when projectiles collide with objects.

# Answer
Overview: immediately after instantiation, check what objects the projectile overlaps. Disable collisions between those objects. Then, on each frame, re-check that list and when it no longer overlaps a collider, reenable collisions between those objects.

Warning: untested

```
public class ProjectileOverlapCheck : MonoBehavior {
  private Collider2D[] overlapping;
  private Collider2D[] testOutput;
  private Collider2D collider;
  private int overlappingCount;

  private void Start() {
    int max = 4; //Note: if it could be overlapping more than 4 things on the first frame, increase this number
    overlapping = new Collider2D[max];
    testOutput = new Collider2D[max];
    collider = GetComponent<Collider2D>();
    ContactFilter2D filter = new ContactFilter2D().NoFilter();
    overlappingCount = collider.OverlapCollider(filter, overlapping);
    if (overlappingCount == 0) {
      Destroy(this);
      return;
    }
    for (int i = 0; i < overlappingCount; i++) {
      Physics2D.IgnoreCollision(collider, overlapping[i], true);
    }
  }

  private void FixedUpdate() {
    ContactFilter2D filter = new ContactFilter2D().NoFilter();
    int newOverlappingCount = collider.OverlapCollider(filter, testOutput);
    for (int i = overlappingCount - 1; i >= 0; i--) {
      bool found = false;
      for (int j = 0; j < newOverlappingCount; j++) {
        if (overlapping[i] == testOutput[j]) {
          found = true;
          break;
        }
      }
      if (!found) {
        Physics2D.IgnoreCollision(collider, overlapping[i], false);
        if (--overlappingCount == 0) {
          Destroy(this);
        } else {
          overlapping[i] = overlapping[overlappingCount];
        }
      }
    }
  }
}

```
> 4 votes

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


# Question
Title: How to animate abstract 2d top down water texture?
I currently implement a game with a top down view of the ocean. I use the following, a little abstract texture:

The actual texture is transparent, I added the green-like color for clarity.

The problem I now have is, that I don't know how to animate this texture so the water looks nice. I tried to move the texture with a sin wave: `texture.y += sin(angle)`. Of course now the whole texture is moving which looks kind of unrealistic. The next thing I tried is to add another layer and implement a parallax effect. So that reflections under the water surface would also move, but much slower. It looks a little better but still not... nice enough.

I think the best looking animation would be, if the individual cells would expand and contract, kind of like a web or piece of cloth. Imagine if someone would slightly pull at one vertex of these cells and the neighbored cell would expand and the cell I pull towards to (or push to) would contract. Kind of like a web of springs(?). But I have no clue how to implement something like this:

* Whats the math-model for this? Something with springs, where forces push/ pull?
* And if so, how do I map this model to the given texture? Keeping all the curves and what not...

(I'm also open to different ideas/answers on how to animate the given texture. Realism is not the point here, just some nice looking water like movements...)

# **Solution from DMGregory**

I posted a libgdx example in this post: 2d water animation is jagged and not smooth (see answer about texture filtering)

# Answer
> 42 votes
A common way this is done is using an indirect texture lookup in the shader to distort the display texture:

Here I'm using a texture with some low-frequency colour noise (tiling smooth blobs of random colours), and scrolling it across the display geometry over time.

Instead of drawing the colours from this texture, I instead take the red & green channels and subtract `0.5f` to turn them into a pseudorandom 2D vector that changes smoothly over time & space.

I can then add a small multiple of this vector to my UV coordinates, before sampling from the main water texture. This shifts the part of the texture we're reading & displaying, warping it around.

By averaging two samples from this noise, scrolling in opposite directions, we can hide the direction of movement so it just looks like aimless sloshing.

In Unity the shader would look like this - it should be simple enough to translate to the shader language of your choice:

```
fixed4 frag (v2f i) : SV_Target
{
    float2 waveUV = i.uv * _NoiseScale;
    float2 travel = _NoiseScrollVelocity * _Time.x;

    float2 uv = i.uv;
    uv += _Distortion * (tex2D(_Noise, waveUV + travel).rg - 0.5f);
    waveUV += 0.2f; // Force an offset between the two samples.
    uv += _Distortion * (tex2D(_Noise, waveUV - travel).rg - 0.5f);

    // Sample the main texture from the distorted UV coordinates.
    fixed4 col = tex2D(_MainTex, uv);

    return col;
}

```

# Answer
> 6 votes
This is called a caustic effect, and generating these effects at runtime is fairly time consuming, so this is traditionally done with pre-rendered frame-by-frame animation. There are tools that will generate caustic animation frames for you, such as Caustics Generator, which has a free version for non-commercial use. There are also some pre-made ones that you can buy for significantly cheaper than the pro version of the tool I mentioned.

Note that caustic effects are also usually an effect applied as a light cookie on an underwater terrain, or on the underwater surface. That is, putting it on the surface of the water while looking down into it is not normally what water looks like.

# Answer
> 4 votes
This looks like a texture you could generate from a voronoi graph, e.g.:

You can make small, smooth adjustments to the graph by moving the points; re-drawing the graph each frame would be quite expensive, so you'd likely want to pre-render the animation.

# Answer
> 0 votes
There is a oldschool method, involving a bottom texture layer, and two half transparent textures for reflection on top.

If you want to go all the way and want the water to not look full of cloned waves or samish blue soup- flowmaps are the got to goal.

https://steamcdn-a.akamaihd.net/apps/valve/2010/siggraph2010\_vlachos\_waterflow.pdf

---
Tags: 2d, libgdx, animation, water
---


title: Simple animation text color change

text:
# Question
Title: Simple animation text color change
I apologize in advanced if this is a trivial ask, but I am wondering if it is possible to use an animation to change the color of a Text element from teal -\> white without any lerp, i.e the color instantly changes. My current animation is only the one frame at 0:00 where I do the switch, but you can still see that the color is lerping even though it is the first and only frame. Am I missing something simple or should I just script the change? Fixing the problem is easy (Trivial to script), but I am just curious if there is something in the animation I can change to not have the color lerp?

I posted the question here as well, but I never have any luck posting on the Unity forums.

# Answer
Inside your animation timeline, right-click on your keyframes and set their tangents to **Broken -\> Constant**, as described in the docs on editing curves.

This ensures there's a discrete jump from the old value to the new when the animation reaches the keyframe, instead of a blend in between.
> 3 votes

---
Tags: unity, animation
---


# Question
Title: Unity - Duck volume of audio source inside a boxed area
I'm trying to lower the volume of an outside ambient wind sound while the player is inside a building or room. Is there any way in Unity to do this without scripting? Or would I have to script this to check whether the player is in a certain collider to duck (or lowpass filter) the sound?

The room is seamlessly in the scene's outside environment.

Any ideas on this?

# Answer
> 1 votes
I don't know if there is a way without scripting, but you can have a Collider as trigger around the room or building, so that it covers the inside but not the outside. OnTriggerEnter you lower the volume and OnTriggerExit you raise it again. So yes, try option two, it shouldn't be much effort. :)

---
Tags: unity, audio, sound-effects
---


# Question
Title: How can I find an agent that would help me get my foot into the door of a publisher?
I have submitted my game for review at couple of game publishers with zero response.

My game is very specific and unusual, so maybe I need to find very specific publisher, or maybe it hasn't been noticed in the sea of submissions, maybe the game is not worth publishing. In any case, I need to know for sure which reasons it is and I need to try all the options available before giving up.

Therefore I've been looking for a professional who knows how and where to try these options, but I'm at a loss on what would be the process to find such a person.

What would be the process to find such an agent?

# Answer
> 0 votes
First off, the options are somewhat limited. In a 2003 interview with Gamasutra, Mark Long states: "shopping for an agency is a pretty simple task right now, since only a handful exist". Unlike other fields, game development is comparable new. Also, there's the theory offered in a NY Time's piece on game agencies that "a deep cultural divide between the slick, Armani-suit-wearing agent crowd and rumpled computer-code-writing gamers has proven difficult to bridge." Both these pieces are a bit dated, but there doesn't seem to have been a huge amount of growth since then.

That being said, there are some agents & agencies out there. Starting with a web search for "game development agents" I was able to find one agency straight off. It turned up a couple of articles (such as those linked above) that in turn lead me to a few more. In short, you're going to need to grind the web & do some professional networking to work up some leads.

That being said, I also want to address what seems to be a bit of a disconnect in the question comments. You state that you're not looking for any money or funding because your app is already finished. That may be true, but marketing your game to a publisher still represents an expense to *somebody*. Your "future profit sharing" proposition requires the agency to take a calculated risk their expenses for finding you a deal will be offset by future revenue. There's often a considerable financial gap between developing a game & its profitable release - even previously successful AAA studios struggle with this.

---
Tags: publishing, business
---


# Question
Title: Is it possible to tile box colliders without causing "false" collisions in Unity3D?
This is in regards to something like a sidescroller where you have a tiled map where each tile uses a 2d box collider.

If you use a 2d circular collider as an example for your character, as it rolls across a series of tiled 2d box colliders, it will occasionally collide with the seams between tiles rather than rolling smoothly across them.

In my scenario here, the tiles are 1x1 units snapped directly adjacent to each other. When rolling a 2d circular collider across a row of tiles, it goes mostly smooth but the more force applied, the greater chance of the circle flying up into the air rather than it's y staying the same as it rolls across them.

The obvious conclusion I had was to use edge colliders instead which works fine, but I'm hoping to find a way to completely eliminate this problem even with just 2d box colliders.

Thanks, Tim

# Answer
Edge colliders are likely to have better performance characteristics for this type of situation, since this is exactly the type of use case they were meant for.

That said, if you want to do it with box colliders, you can have a script that simplifies the world collision representation by grouping adjacent boxes. Say after scanning the tiles in your level it detects 5 identical floor tiles in a row; it could delete those 5 colliders and create a new, larger box collider that occupies the same space. Then there are no seams within that 5-tile span (and fewer collision objects to check - bonus!)

This could be done as an offline process via an Editor script (though this may interfere with subsequent editing of the level), or as a runtime preprocessing step when the level is loaded (which may delay the loading somewhat, but profile to see if it's noticeable).
> 2 votes

# Answer
for anyone still reading this adding a composite collider 2d to the tilemap and checking used by composite on the tilemap collider will fix this problem. :)
> -1 votes

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


# Question
Title: Should I add new players to my mailing list?
I wonder if it's ok for me to add new player's emails to my mailing list. Should I display a notice or something before doing so? I don't see these a lot in popular mobile games, but they send emails anyway from time to time.

# Answer
> 4 votes
You should ask before signing users up for a email list. Doing so doesn't harm the users who are interested, but *can* make the users who aren't interested upset with you. So it's generally the "nice" thing to do.

In some jurisdictions, there may be law that *require* you to only offer opt-in email lists, or require you to present opt-out notices in certain ways, et cetera. The most recent such law I'm aware of is the EU's GDPR, which has some sections pertaining to email marketing.

You should consult your lawyer for specific legal advice regarding your situation and the game you plan to ship.

# Answer
> -3 votes
yes.. you can as the email is the only way to connect with people around the world nowadays. but another reminder is to make sure that your email notification won't be like a spam to others. make sure to send the information email only.

---
Tags: marketing
---


# Question
Title: How to change the time dilation using C++ in Unreal Engine?
I searched a bit and found a blueprint solution which does this but I've just started using Unreal and I prefer C++ instead of this visual programming thingy.

I'm looking for a Unity-like `Time.timeScale` property which could be easily set during runtime.

Is there a thing like that in Unreal? I just want to play with changing the speed of time of the whole world.

# Answer
I think you can use `SetTimeDilation` on the world settings.
> 4 votes

---
Tags: c++, unreal-4, unreal
---


# Question
Title: Run playing game in full-screen on one display, Unity IDE in another
I have multiple monitors (\*). If the Unity (2018.1) IDE is open and maximized in one of them, is there an easy way to have it use one of the OTHER displays to run the game full-screen whenever I launch 'play' mode? Or alternatively, to undock the "Game" tab from the IDE & turn it into a normal window that can be moved to an adjacent display & maximized?

---

(\*) If it matters, I'm running Windows 10, with the desktop extended across all three. The left and middle (main) displays are connected via DVI, the right display is my laptop (Dell Precision m4800 with Quadro K2100M). All three are 1920x1080.

# Answer
> 1 votes
Tabs in the editor, including the game and scene tabs, can be detached and moved via drag&drop. If moved outside the editor window, e.g. onto another screen, they become separate windows and can be maximized/restored or closed.

---
Tags: unity
---


title: Designing Snake AI

text:
# Question
Title: Designing Snake AI
I'm new to this gamedev stackechange but have used the math and cs sites before.

So, I'm in a competition to create AI for a snake that will compete with four other snakes in 5 minute rounds where the rules are much like the traditional Nokia snake game except that there are five snakes, the board is 30x30 and there are a number of small obstacles on the field.

Like the Nokia game, your snake grows when you get to the fruit and if you crash into yourself, another snake or the wall you die. The game runs with a 30ms delay between moves and the server sends the new game state every 50ms which the code must analyze and what not and output the next move.

The winner is the snake who had the longest length at any point in the game. Tie breakers are decided by kills.

So far what I have done is implemented an A\* graph search from each snake to determine if my snake is the closest to the apple and if it is, it goes for the apple. Otherwise, I made a neat little algorithm to determine the emptiest area of the board, which my snake goes for, to anticipate the next apple.

Other than this I have some small survivability checks to ensure my snake isn't walking into a trap that it can't get out and if it does get stuck, I have something to give it a better chance of getting out.

...

Anyway, I've tested my snake on a test server and it does quite well. Generally, my strategy of only going for the apple when its a sure thing and finding space when its not makes it grow faster than any other snakes (some snakes do a similar thing but often just go to the middle or a corner) sometimes it wins these trial games but is more often than not beaten by the same snake who seems to have the edge on survivability (my snake grows quicker but then dies somehow and this other snake just plods slowly along and wins on consistency.

So I was wondering about any ideas anyone has to try and improve my snake. Or maybe ideas at a new approach to take. My functions and classes are good so changes that might seem drastic shouldn't be too bad. I encourage all ideas.

Any thoughts?

# Answer
> 5 votes
A good defensive strategy could be to do a perfect **shape** (so your head and backside are always 1 space away from each other, and you make a full square or whatever is possible to form at your given length), this would make you pretty much immortal since no snake could ever get into your enclosed area and you will never run into yourself (unless an apple somehow spawned in your mouth, but I'd imagine that's impossible if there's no space).

This would make it so if the apple actually appear in your enclosed area you could be programmed not to go for it and the other snakes will probably die trying to get it, then after some time elapsed you could get it in such a way to transition back into your shape as best as possible (could be a bit of a tricky algorithm but seems doable)

When do go for apples would just depend on how far away they are, maybe if you are the closest by a good margin you could go for it, but otherwise stay conservative, hard to say would probably need to tweak it based on trial and error, but I think it would be a good strategy.

# Answer
> 0 votes
The snake should adapt its strategy to its current length.

A very long snake can use its body to fence in opponents. This means that it should make a seal with a wall.

If the snake is traveling east, with an apple north-east of it, it should travel all the way to the wall before turning north, so the possible routes for other snakes is severely limited.

```
  0123456789
a ··········
b ··········
c ········A·
d ··········
e ooooooC···
f o·········
g o·········
h oooooooo··
i ··········
j ··········

```

This snake with head C, should turn north at e9, not at e8, so that any opponent below it, will be trapped, and unable to eat any apples that get spawn above the 'e' line.

The larger the area you can cut off and the longer you can hold it, the better.

---
Tags: ai, snake
---


# Question
Title: Setting a jump counter in my 2d platformer built with phaser
I have a platforming game, written in javascript with the Phaser.js framework, where my character collects objects. I thought trying to collect all objects in the least amount of jumps would be interesting, so I tried to implement a jump counter. Relevant pieces of code:

```
var jumpCount = 0;
var jumpText;

function create (){
    jumpText = this.add.text(16, 48, 'Jumps Used: 0', {fontsize: '32px', fill: '#000'});
}

function update (jumpCount){
    if (cursors.space.isDown && player.body.touching.down){
        player.setVelocityY(-630);
        jumpCount++;
        jumpText.setText('Jumps Used: ' + jumpCount);
    }
}

```

This is displaying the counter and incrementing it *sort of* correctly, but it seems to count the amount of time that the spacebar is held down and is leading to jump counts that are floats well into the thousands.

Is there a more reasonable way to handle counting the number of times a player has manually jumped?

Thanks!

# Answer
Instead of checking in the `update` you can instead add a binding to the key itself. In Phaser 2, which it looks like you might be using:

```
jumpButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
jumpButton.onDown.add(jump, this);

function jump() {
    // Add your existing logic here.
}

```
> 0 votes

---
Tags: javascript, phaser, jumping
---


title: Depth sorting issue

text:
# Question
Title: Depth sorting issue
I've been working on a custom tile-based map editor for a while now, and everything works as expected, or so I thought until I've tried rendering the actual map including the dynamic objects as well.

As it currently works, it's saving data into a buffer in a format of: \[ground layer\] \[on-ground layer\] (flowers/rocks) \[wall layer\] \[on-wall layer\] (windows/torches/bookshelves)

So basically there's a total of 4 layers. The tiles are rendered from top left corner to bottom right corner in the following order: \[ground layer\] -\> All tiles \[on-ground layer\] -\> All tiles \[wall layer\] Does an instance exists on that spot? in case it does the instance gets rendered first, and then the tile itself. \[on-wall layer\] renders normally right after that.

This system seems perfectly fine it the game has a grid-based movement, as well as if all the dynamic sprites are the same size like the tile size. Why? Well, you'd just walk anywhere and get covered with a certain tile or be drawn over a certain tile. On the other hand, if any of the dynamic instances has let's say a sprite height which is bigger than the actual tile size the depth sorting issues appear.

Example: We've got a pillar which is 16x48 in size. The very bottom of the pillar has a collider of 16x16 and it can't be stepped on, but the mid and top part don't have any colliders. Now if a player for example steps on the topmost tile of the pillar everything gets rendered normally. On the other hand if the steps on the mid tile, the "player's head" would be rendered over the topmost tile..

I'm wondering if there's an actual solution for depth ordering in a case like this.

# Answer
> 0 votes
For this scenario, simply have your oversized sprite take up multiple tiles (e.g. create a virtual tile for the oversized sprite one above the actual tile). This way, when you go about checking for what to draw, you'll see there's a wall and a ground object to draw. At this point, to figure out which overlaps which, check the ending vertical tile of each. Assuming vertical indices increment from top to bottom (top tile row is index 0, bottom tile row is index X), the one with the higher ending vertical tile is in front of the other. On a tie, you'll have to figure out which one you want to use, but in theory it shouldn't happen with proper collision.

---
Tags: 2d, rendering, tilemap, draw-order, depth
---


# Question
Title: Unity: "inconsistent line endings" dialog shows up ever time I open VS with unity
Everytime I open a script file from unity with visual studio this dialog shows up about normalizing the line endings? What does this mean? I click Yes every time but still can't get rid of it. It only happens when I open a file from unity.

# Answer
In Visual Studio, you can disable this check (and thus the warning) by looking in `Tools -> Options`, navigating to the `Environment -> Documents` section of the tree, and unchecking "Check for consistent line endings on load."

This suppresses the warning but doesn't actually solve the problem; the source files will still have inconsistent line endings. Ideally you'd solve this problem by configure all the editors you use to insert the same kind of line ending, or to autodetect the existing style and preserve it. Unfortunately not all text editors support such behavior; VS, for example, doesn't have a controllable default (although it will let you configure the style used on a per file basis on `File -> Advanced Save Options`, but this is really tedious).
> 5 votes

# Answer
## **End-of-file (EOF) | Line ending, end of line (EOL)**

As Josh Petrie mention, you can solve the problem by changing the line endings of each script you open. First, you need to close the script in Visual Studio. Then go to Unity and double click in the Unity console `line ending warning` message. Visual Studio will open the script with the missing and a line ending dialogue window will show up. Go to the Line endings section and choose `Windows` or the OS platform that you are using. Now save the script and next time you open VS, the message will not pop up for this script.

**Visual Studio 2019**

If it is not working as a workaround you can force normalize using

* **Edit \> Advanced \> Set New line \> CRLF** (for Windows).

This will replace all LF to CRLF.

## **DEFAULT TEMPLATE**

When you make a new script the template can have an incorrect line ending. So if you change the Unity template, each time you make a new script you will not encounter this common problem. To change the default template go where Unity was installed and search for the ScriptTemplates folder:

C:\Program Files\Unity... Hub\Editor\20xx.x... Editor\Data\Resources\ScriptTemplates

In Windows, the default template script can be modified as administrator or using admin password. Now open this script template with VS (file: 81-C# Script-...). In VS with the script selected, go to `File -> Advanced` Save Options, the window will pop up and choose `Windows` or the platform OS that you are using. Now save the script and next time you make a new C# script in Unity, the message will not pop up for all this new scripts.

## **INSTALLING Strip'em for VS 2010-2017**

Now you can also test if you wish this other tools for VS. This old video (at 10m32s) can help you in the process, but the rest of the video is already outdated. Warning, don't follow this tutorial, it doesn't work anymore. It helps you in the process of using Strip'em (after 10m32s)

https://youtu.be/2PVPz8Pnnrw?t=10m32s

To activate Strip'em in VS 2015, after the installation, press `Tools > Strip'em` and select your OS. Strip'em in VS Community 2017, you just double-click the installer and that is all.

http://www.grebulon.com/software/stripem.php
> 8 votes

# Answer
Unless you're extremely committed to Visual Studio, I've found that literally just opening the file in another text editor (like Sublime or VS Code) and then saving it immediately fixed the issue. I've had poor experiences with Visual Studio in the past, and it's always extremely hard to debug weird editor errors.
> 2 votes

---
Tags: unity, visual-studio
---


# Question
Title: How do I make a game object appear on the other side when it leaves the screen?
I'm doing an assignment for a course and what's required is to include a moving asteroid in the game that starts moving in a random direction and when the asteroid leaves the bottom of the game window it should re-appear at the top of the game window ,so I wrote the script for warping and I applied it to the asteroid and a ship in my game ,then built it to WebGl game. the warping worked fine in the editor for both the ship and the asteroid, while it only worked for the ship in the built game, and I can't figure out what's wrong

this is the script

(ScreenUtils gives the borders of the screen)

```
float Radius;

void Start () {
    Radius = GetComponent<CircleCollider2D>().radius;
}
void OnBecameInvisible()
{
    // Make the ship wrap
    Vector3 position = transform.position;
    if (position.x - Radius >= ScreenUtils.ScreenRight || position.x + Radius <= ScreenUtils.ScreenLeft)
    {
        position.x *= -1;

    }
    if (position.y -Radius >= ScreenUtils.ScreenTop || position.y + Radius <= ScreenUtils.ScreenBottom)
    {
        position.y *= -1;
    }
    transform.position = position;
}

```

# Answer
Use the built-in Screen.width and Screen.height instead of using your own code. As suggested in the comments, your bug is probably in there.

Alternatively, you can use 8 players, and wrap it around the screen, as scene in this tutorial: https://gamedevelopment.tutsplus.com/articles/create-an-asteroids-like-screen-wrapping-effect-with-unity--gamedev-15055.
> 1 votes

---
Tags: unity
---


# Question
Title: How to get the point of collision in Separating Axis Theorem?
I'm interested in the relatively precise point (not line) of collision for calculating angular velocity on impact for use in a impulse calculation. At first I thought, perhaps naively, that I could use the closest point along the shortest overlapping axis, but closest to what exactly?

# Answer
> 1 votes
The axis with the smallest overlap is not necessarily a good guide to where the collision occurred.

Imagine a small cube translating to the right at high speed, entering a larger prism from the side and penetrating a fair distance into the middle:

```
 ┌──────┐              ┌──────┐
 │      │ ---------→   │      │
 │      │       ┌──────┼──────┼───────┐ ↑
 └──────┘       │      └──────┘       │ ↓
                └─────────────────────┘

```

Here the smallest overlapping axis is vertical, perpendicular to the incident velocity. Displacing the cube according to this penetration axis will resolve the overlap, but it won't tell us where the collision occurred (ie. on the left side of the object). The behaviour will look like the cube nicked the corner of the platform and skipped upward, rather than slamming into it side-on as it should have.

Many physics engines deem this result "good enough," and leave it up to devs to use a shorter timestep, continuous collision detection methods, or explicit raycast/sweep tests to get finer precision for the cases where they're needed.

What you can do instead is compute, for each axis, the (signed) speed of approach along that axis. Then you can look at the projections you get along that axis, and measure how much time you'd need to rewind at that speed until the two intervals just kiss.

The smallest such result tells you the last axis to lose its separation during the approach along this velocity vector. Backtrack along the velocity vector by this time-since-penetration you've calculated to position the objects the way they were at the moment of contact. You can then find the point, line, or surface common to both shapes at this moment.

(Assuming neither object is rotating relative to the other - if they are, then the axis overlaps you computed for the end of the movement aren't necessarily valid for moments earlier in the movement, and things get more complicated still... The best approach I can think of there is to use the method above as an estimate of contact time, then re-run your overlap checks at the estimated timestamp to get a refined estimate, and close in by binary search. There are probably more sophisticated approaches you could use though.)

# Answer
> 0 votes
I ended up taking one vertex from each shape that provided the maximum part of the smallest overlapping axis. Then, I subtracting one from another and averaged them, providing a highly accurate result.

---
Tags: physics, mathematics, physics-engine, rigid-body-dynamics, separating-axis-theorem
---


# Question
Title: workload not availble on visual studio 2017 setup
i use vs2017 with unity but now when io want to install it on new pc there is a message says: workload unavailable right now. required conditions are not satisfied. not win10 threshold number1 and number2 build number

# Answer
> 0 votes
its all about windows Version.visual studio plugin for unity depends on new updates of windows. i just updated the windows and it worked.

---
Tags: unity, visual-studio
---


# Question
Title: Design pattern for turn based strategy game in C++
I'm studying computer science at university. So far I've created several programs for school projects and homeworks in C++. They were usually smaller programs up to 1000 lines of code.

Now I want to create a simple 2D turn-based strategy game (TBS game) similar to Advance War.

If I decide to use OOP principle, then game design would seem quite straightforward in some aspects. I'd create class such as Unit, Tile, GameBoard... But several questions are arrising in a moment.

Tile should probably contain:

* information about type of terrain (probably enum type),
* information if there is a unit (probably pointer to unit)
===\> needed for searching possible moves in a map of tiles

Unit should probably contain:

* information about type of unit (probably enum type)
* where unit is standing (probably pointer to Tile / position coordinate?)
===\> if I want to search space for a specific unit I must know where searching should start.

Should I use pointer to Tile or (x,y) coordinates for Unit class? Is it bad to have circular dependency (Unit\<--\>Tile) in this specific situation?

However I am not so sure whether OOP is good way to go after watching several videos. I've seen videos about:

In the video about data oriented design you can hear sentences like:

> 00:09:20 "Multiple inheritance... that's not even a guestion. That's just dumb. Runtime type information... that's off the table."
>
> 01:16:00 "Show me your code, I won't know what you're doing. Show me your tables (how you organise your data), I won't need to see your code"
>
> 01:18:00 "You don't care how long it takes. Great. But People who don't care about how long it takes are also a reason why I have to wait 30 seconds for Word to boot."

Since methods like attack and move for individual units (infantry, mech, transporter) differ only with values I can avoid using virtual functions for attack/move quite trivially and have only one universal class Unit.

```
#include <iostream>
#include <string>
#include <array>
#include <bitset>

enum class TerrainType   { Grass, Mountain, Forest, size};
enum class TransportType { Foot, Boot, Tread, size  };
enum class UnitType      { InfantryType, MechType, TransporterType, size };

const size_t COUNT_UNIT = (size_t) UnitType::size;
const size_t COUNT_TRANSPORT = (size_t) TransportType::size;
const size_t COUNT_TERRAIN = (size_t) TerrainType::size;
const size_t UNREACHABLE = 100;

const size_t damageTable[COUNT_UNIT][COUNT_UNIT] =
{
    {5, 2, 1},    // infantry
    {50, 20, 10}, // mech
    {0, 0, 0}     // transporter
};

const size_t moveCostTable[COUNT_TERRAIN][COUNT_TRANSPORT] =
{
    {1, 1, 1},              // Grass
    {2, 1, UNREACHABLE},    // Mountain
    {1, 1, 2}               // Forest
};

const size_t numberOfMovesTable[COUNT_UNIT] =
{
    3, // infantry
    2, // mech
    6  // transporter
};

struct CUnit
{
    size_t health;
    size_t fuel;
    UnitType type;

    //------------------------------------------------------------
    CUnit(size_t hpParam, size_t fuelParam, UnitType typeParam)
        : health(hpParam), fuel(fuelParam), type(typeParam) {}

    void attack(CUnit& unit) const
    {
        size_t baseDamage = damageTable[(size_t)type][(size_t)(unit.type)];
        unit.health -= baseDamage;
    }
};

int main(int argc, char const *argv[])
{
    CUnit inftry {99, 99, UnitType::InfantryType};
    CUnit mech {99, 99, UnitType::MechType};

    std::cout << "inftryHP: " << inftry.health << std::endl;
    std::cout << "mechHP: " << mech.health << std::endl;

    inftry.attack(mech);
    mech.attack(inftry);
    std::cout << "after attack\n";
    std::cout << "inftryHP: " << inftry.health << std::endl;
    std::cout << "mechHP: " << mech.health << std::endl;

    return 0;
}

```

But there are units that behave distinctly and have additional moves such as transporting and supplying other units. Then I have to create somewhere for example additional information about what units can a tranporter load, create information about its capacity, array where to save transported units and so on. Then my universal class Unit immediately create extra memory overhead because Infantry or Mech do not need those additional information.

I've come up with an idea creating somewhere a constant tuple of unique unitSheets (infantrySheet, TransporterSheet...). Each unitSheet would contain specific behaviour and values. Then CUnit would have ID and health,fuel... just like before, but specific behaviour would be access via tuple using CUnit's ID. Unfortunately it is only possible call get(tuple) with specific ID in compile-time.

So I do not know which direction should I go? I've spent several days on thinking about how to implement the game but the results are minimal. You can argue that TBS games is not area where I should worry with performance. However I'd like to experiment with the game using evolution algorithm and neural network to train AI in the future. So quick operations might come in handy.

EDIT #1 (after @Philipp answer):

> Does a tile need to know its unit? (So only unit knows its tile)

Definitely yes. But let's assume "no". How could I check if an unit standing on a tileA can enter a tileB? Is a different unit already standing on the tileB? I am unable to examine the tileB directly because of its absence of pointer to unit. I am forced to go through every unit and its tile to check if it is the tileB.

> Does a unit need to know its tile? (So only tile knows its unit)

Probably not. If player wants to choose a unit, he is still clicking on a tile. So we can determine unit via tile's pointer quite easily. How to find player's unit on a game map? If I store array of units, it won't tell me nothing about their position because of absence of pointer to tile. If I store array of tiles (probably pointer to tile) where player's unit stand, I will know unit's position. However it creates also several drawbacks... I am accesing unit indirectly via another pointer. If an unit moves to other tile, I must reflect that in player's array of tiles. Is "only tile knows its unit" better than having circular dependency? I don't know...

# Answer
First things first: If this is your first game and you dont plan to expand on it (except maybe for Neural Network Learing), then use your learned OOD. There is nothing wrong in doing it a certain way. Your first game wont be a Battlefield or Dota, not even a Final Fantasy Tactics. So dont worry about the performance and whatnot before even having a design plan. Why worry about memory overhead, if you have not implemented a single class.

i would suggest to go with either one, OOD or ECS, but dont mix them. For you OOD might be the more natural way, so if making a game is just a stepping stone for more complex topics, stick to OOD. If you want to make a game to lear new concepts and work with those, go ECS. Any hybrid thingy may make it worse.

Now second, do you understand why polymorphism and inheritance is arguably bad for games? You cited the videos (which i couldnt watch yet) and some quotes, but just after that you want to have a certain table filled with every detail, and possibly link it --\> Cache miss. If you want a good read about these topics, i advice you to look for Game Programming Pattern.

Maybe im wrong - quite possible that i am - but even then you should plan some designs you could implement and gather pros and cons for them. If you think you are done, post them here and ask others what they think.

After you thought about those two things, you can start concepting if your tiles need to know the units and the units need to know the tiles.
> 1 votes

# Answer
> Should I use pointer to Tile or (x,y) coordinates for Unit class?

When looking up the tile of a coordinate-pair is cheap (which it usually is if your map is an array of tiles with array indexes mapping to coordinates), then it does not make much of a difference if you get the tile from the coordinates or the coordinates from the tile. So the unit knowing its coordinates and the unit knowing its tile is pretty much the same thing.

> Is it bad to have circular dependency (Unit\<--\>Tile) in this specific situation?

The real question here is "does a unit needs to know its tile" and "does a tile need to know its unit"? I could imagine cases where both navigations might be useful. So I would recommend to maintain that circular dependency. However, in order to avoid inconsistencies, make up your mind about who is "the boss in the relationship". When a unit moves from one tile to another, are the tiles responsible for updating the unit or is the unit responsible for updating the tiles? Both are reasonable approaches, but you need to decide on one and stick to it, or there is a high risk of bugs if tile and unit do not agree with each other.

There are two special cases which might or might not be relevant for your game:

1. Can a unit occupy more than one tile?
2. Can a tile host more than one unit?

If either is the case, then it might not be a good idea to have the `1` in the `1..n` relationship know its `n`, because it might be ambiguous.

> I've come up with an idea creating somewhere a constant tuple of unique unitSheets (infantrySheet, TransporterSheet...). Each unitSheet would contain specific behaviour and values.

This sounds like you just reinvented classes. You won't get around the performance problems you get from performance-critical code using polymorphism by inventing your own polymorphic system and calling a class a "Unit Sheet".

Units with unique abilities appears like a good application for the Entity - Component - System (ECS) pattern. A unit which can transport, gets a `Transporter` component. A unit which can supply gets a `Supplier` component, and so on.

The components are separate objects which contain all the data relevant to that functionality. So the `Transporter` component would contain the information about the loaded units, while the `Supplier` component contains what resources it can supply to which units and the remaining stock.

The memory overhead problem you mentioned can be avoided by not instantiating any component objects for entities which do not have them.

In a pure ECS, you don't actually have a `class CUnit`. All the data is in the components and all the code is in the systems. An entity is just a `size_t id` which is used to find out which components belongs to the same entity. But if you don't want to go that far, you can also have components without systems. In such an architecture, your `class CUnit` has a pointer for every possible optional component an unit can have. When a unit does not have a specific component, that pointer gets the value `null` (or points to a static NULL-object if you want to avoid runtime errors caused by accidentally dereferencing null pointers).

I am looking forward to playing your game.
> 0 votes

---
Tags: c++, design-patterns, turn-based, oop, data-oriented
---


# Question
Title: Is it efficient to have a only-data MonoBehaviours on lots of game objects?
I'm working on a **voxel based game** and this solution would make the implementation of networking and other features a lot more easier, it is less error-prone, easier to edit in the Editor, etc.

So the question is:

* **How bad is it performance-wise to have lots of MonoBehaviours in the scene, if they don't implement any of the MonoBehaviour methods?**
* (So they only have primitive data stored in them)

# Answer
Unless you are saving massive amount of information on those scripts, there is nothing performance-wise that you should worry about. If the only thing they do is have some getters/setters or something like that, the responsibility of performance is passed on who is calling them.

In most cases, it's not going to be a problem, but you did mention this is a voxel based game. The only thing I could see going wrong, is if you attached those scripts in every single voxel in the game, and had the game run getters and setters for multiple data, on every single voxel. This could potentially be quite expensive.

If you give some more information about what exactly you have in mind, maybe I can go into more detail. Also don't fall into the trap of Premature Optimisation. If you have an idea, implement it, if it runs slow, profile it and optimise the slow parts.
> 1 votes

---
Tags: unity, monobehaviour
---


title: Effect Replacement System

text:
# Question
Title: Effect Replacement System
I'm working on a turn based rpg and have an action/queue system setup that I'm happy with. However, I am having trouble implementing a feature and I am here for some advice. I want to have effects/abilities that alter other outcomes of actions/effects and am not sure how to structure things to allow for this.

I'll provide an example to illustrate what I am trying to achieve.

Say we have two characters in combat. The attacker needs to roll 1d20 and add the result to their current strength to see if they make a hit. If that value is equal to or greater than the defender's toughness the attack is successful and the defender takes damage.

```
def Attack(attacker, defender):
    roll = Dice.roll()
    roll += attacker.strength

    if roll >= defender.toughness:
        defender.damage(attacker.weapon.power)

```

Now lets say the attacker has a piece of gear on that says if they get a critical hit (a roll of 20) they hit the monster no matter what and deal one point of damage. How do I inject this code into the attack function and have it ignore the portion of the function after the dice is rolled (the armor's effect is replacing the rest of the attack)?

I've thought of breaking the code into chunks

```
def Critical_Hit_Buff(roll, defender):
    if roll == 20:
        defender.damage(1)
        return False
    return True

def Attack(attacker, defender):
    do_continue = True
    roll = Dice.roll()

    #check if any buffs from armor/etc. activate
    for buff in attacker.buffs('attack'):
        do_continue = buff(roll, defender)

    if do_continue:
        roll += attacker.strength

        if roll >= defender.toughness:
             defender.damage(attacker.weapon.power)

```

But I really don't like having to carry around the continue variable everywhere and further I don't know if an action is not continuing because the action failed (some buff/debuff prevents the attack from being successful) or if it was because some effect replaced the attack event (this might be relevant if I give the player notifications that about if the action was successful or not).

Any advice?

# Answer
> 3 votes
Split the actions, such as "main weapon melee attack" in the OP's example into smaller actions and conditions. Recombine them using a behaviour tree. For example:

Normally the purpose of a behaviour tree is to implement AI scripting and to allow easily composing AI behaviour. Here we will use the behaviour tree somewhat different1:

1. Just like in the typical AI the behaviour tree is evaluated to execute the scripted behaviour.
2. We converted code into data. Data can be easily manipulated from the running game. For this specific weapon we can replace the above tree with:
3. This leaves one issue: when should we modify a sub action tree and how should we modify the tree? To solve this issue we make the tree searchable and design a simple query language for it. So that we can find any tree that contains the 'roll (attack dice)' action. We trigger the weapon's tree modifying action2 when such an action tree is about to be executed.
The tree modifying action can replace the 'roll (attack dice)' node by a sequence of 'roll (attack dice)' and 'is crit?' or insert the 'is crit?' subtree after the 'roll (attack dice)' in the parent sequence of 'roll (attack dice)'.

---

1 You could still use it for you AI system as well. The possibilities and features will grow: weapons or spells that manipulate behaviour of computer played monsters and NPCs.
2 If you like, the modify tree action can also be encoded as a behaviour tree (but this recursive level of abstraction might make some people dizzy).

# Answer
> 1 votes
After trying a few things I think I found a method I am happy with. I've broken the single Attack() function into several smaller functions. Each action has a default followup action that occurs when the current action is finished. When buffs are checked, "followup" is also passed in and can be altered. If a buff alters the outcome of the event it sets followup to a different function. From here the new action can either branch off into another new actions or, when it is done, return back to the default followup that would occur after the Damage function.

```
def Attack(attacker, defender):
    followup = Damage
    roll = Dice.roll()

    #a buff can edit what happens next
    for buff in attacker.buffs('attack'):
        followup = buff(attacker, defender, roll, followup)

    followup(attacker, defender, roll)

def Damage(attacker, defender, roll)
    followup = Counter_Attack
    roll += attacker.strength

    if roll >= defender.toughness:
        defender.damage(attacker.weapon.power)

    followup(attacker, defender)

def Critical_Hit_Buff(attacker, defender, roll, followup):
    def Critical_Damage(attacker, defender, roll)
        followup = Counter_Attack #same followup action as Damage
        defender.damage(1)

        followup(attacker, defender)

    if roll == 20:
        return Critical_Damage(attacker, defender, roll) #return new followup created by the armor buff
    return followup #return default followup

```

The above example assumes that there is at most one followup action that could occur when the buffs are checked (any others would overwrite the previous). However, it's possible to expand this to account for multiple paths.

---
Tags: game-design, events, effect-modifier
---


title: How simulate a random distribution?

text:
# Question
Title: How simulate a random distribution?
I'm working on a battle algorithm for a text-based game and I stumble when it comes to randomly distributing attacks on a set of units.

E.G, 100 archers shoot 100 targets at the same time. I thought of doing like this :

1. The 100 targets are considered as a single block
2. The arrows are distributed inside
3. The units hit the same number of times are grouped together.
4. I manage the life of each new group
5. Repeat on each new group if necessary

I can distribute the arrows (step 2) and get the result (step 3) through a loop, but with many armies composed of millions archers, computing time & memory consumption becomes a problem.

```
// Step 2
const targets = new Array( 1000000000 );
targets.fill( 0, 0, 1000000000 );
const arrows = 1000000000;
for( let i = 0; i < arrows; i++ ){
    const index = Math.floor( ( Math.random() * arrows ) );
    targets[ index ] += 1
}
//Step 3
const result = []
targets.forEach( value => {
    if( value ){
        if( result[ value ] ) result[ value ] += 1
        else result[ value ] = 1
    }
} )

```

**Is there another way to solve this problem ?** I believe that with large numbers, directly calculating the most likely scenario may be a good option. Unfortunately, I do not know anything about probabilities.

# Answer
> 1 votes
You need to set each archer with a random target. You could set it to any of the enemies but it would probably work better if they can only see a number of them. For the sake of simplicity, I'm going to use 10, not 100.

Archers:
0123456789

0123456789
Enemies:

Now, let's say each archer can only reach the enemy in front of him and two either side for his range so archer 0 can hit enemy 0, 1 and 2. Archer 1, can hit 0, 1, 2, 3. Archer 2 can hit 0, 1, 2, 3, 4 and so on until archer 9 who can only hit enemies 7, 8, 9.

Looping each archer, choose a random enemy then move onto the next archer to do the same.

Personally speaking, I'd also loop all archers before they fire which will add a bit of realism to the game by making some archers aim for enemies who are already dead by the time their arrow gets to their individual target.

---
Tags: algorithm, random, probability
---


# Question
Title: UE4 - projectile that turns into an enemy?
I'm wondering what would be the best way to do this: A boss enemy tosses a smaller enemy as a projectile. After landing the thrown enemy starts behaving like a normal enemy with walking, shooting etc.

My ideas would be either to make an enemy blueprint that has this behavior defined (for example, all the "normal" behavior is turned off until it lands), or to make two classes, the projectile and the enemy... then somehow convert them?

But how would I do it? I'm more interested in the latter method. The first one I could figure out myself. So how would I change the projectile to an enemy? Define some casting? Destroy the projectile and immediately spawn an enemy?

EDIT: What is really interesting to me is the technical side of the problem. If we go with the route of enemy who starts as a projectile and turns into a walking enemy, that would probably involve 2 sets of AI (I'm just grasping that, forgive me) and some trigger to switche between them, like hitting a wall. Seems simple.

If we go with the route of 2 classes, the transition is what bothers me. The most simple way would be to destroy the ProjectileEnemy and spawn the Enemy from it. That obviously won't work - after destroying Projectile enemy, there's nothing to call "Spawn" method. I have a crude workaround, spawn Enemy first and immediately after - destroy ProjectileEnemy. Won't that cause visual issues and other problems though?

# Answer
Although I suspect this question is somewhat opinion based, I believe the best way would be to have 2 different classes and have the enemy spawn where the projectile lands using an OnCollision event.

The main reason is that while it is possible that to calculate the angles and velocity to throw the enemy so it lands on its feet before turning into a normal AI, it's not the most efficient way. Using a projectile in an circle (or similar) basic shape means it can land any way it likes and the enemy spawns in the correct position.

Using the OnCollision event means you can run a check on where the projectile is (did it hit a wall? The player? Was it shot by the player?) so you can decide whether you want the trigger event to take place.

It also means you can have different weights, physics, materials and other things needed to make the spawned projectile move smoothly through the air and not need to change and of these on landing which could potentially slow down render time.

ADDITIONAL BASED ON EDIT TO QUESTION: You won't need two sets of AI. The projectile is just that. Fired with a velocity and physics.

To get around the issue of having both the projectile and the enemy AI on screen at the same time, you could have two extra variables on your boss. A boolean as to whether the projectile has landed and an FVector of the landing location.

On collision of the projectile with a floor, wall, whatever, the projectile casts to the boss, changing these two variables then destroying itself. The boss on tick, can check if the boolean is true and if it is, spawn the enemy AI at the FVector location before setting the bool to false so it doesn't spawn multiple enemies at the same location.
> 1 votes

---
Tags: unreal-4
---


# Question
Title: Unexpectedly fast rotation after refactoring OpenGL code to add more abstraction
I've been working on an OpenGL program that simply renders a square that rotates in 3D space. The square also has a texture applied to both sides. Here you can see an example screenshot of the program running:

I used very little abstraction in that project and most of the code was in main.cpp (apart from the shader loading and usage).

After finishing this project, I wanted to improve it as much as I could with my current knowledge. I started abstracting away functionality. The final result was a very clean main.cpp file with multiple classes (Mesh, Shader, Resource Manager and Window classes).

Apart from the texture, everything should functionally be the same, but I experienced the following after using the rotate function; left is the abstracted version of the first project, right is the first project:

The square in the new project rotates at a much higher speed than in the previous project. The implementation is the same, as in, the degrees that the square should rotate around the y-axis are the same in both projects - the time the program has been running, which is gotten through GLFW's `glfwGetTime()`.

I checked nearly everything. The .lib files are linked the same way between the projects. There are no differences between the vertex data. Both projects are running in DEBUG mode.

The only difference I could think of is the texture not being applied in the second project, but I recall that the textureless version of the first project was still running with the same speed as it is currently. But rendering a 64x64 texture on a square shouldn't be *that* expensive to run.

NOTE: I'm using GLM for the matrices and for the rotation transformation.

Does abstracting away all of OpenGL's initializing and buffer code improve performance by that much?

I'm using GLFW for window and context creation, and thus using `(float)glfwGetTime()` for the angle of rotation along the y-axis.

The second project basically moves over all functionality into categorized classes. So everything to do with meshes was moved to a Mesh class, loading of GLSL shaders and textures was moved over to a ResourceManager class etc. So all functionality should be the same.

# Answer
> 3 votes
As @ratchetfreak commented, I hadn't reset the model matrix to the identity matrix in the render loop. This was indeed omitted from the remade project.

The matrix needs to be reset each frame to the identity matrix because each frame it stores a new transformation (in this situation a rotation) in the matrix, so when the next frame a new rotation transformation is applied, it's applied to all the previous frames' rotations. So for example, on frame #5 the matrix is in a form that stores the rotations of frames 1-4 and the 5th rotation is applied on top of all those.

The resulting effect is a sort of 'exponential' increase in the speed of the rotation, before slowing down for a second and speeding back up again.

Again, thank you @ratchetfreak :)

(I'll accept this as the answer when the site allows me.)

---
Tags: opengl, c++, performance
---


# Question
Title: Object scales strangely when setting y rotation after parenting
I created 3 boxes, then align the three to form some sort of a gate, I set the parent to an empty object so that I can easily move it. And I add box collider inside the gate.

When I try to rotate it on Y axis, the boxes deforms

I just want to rotate the Y, not deformed it. Here are the object

Is this related to the transformation I created before? Something that requires to apply the transformation first? like in blender3d?

# Answer
> 3 votes
When you nest objects in the Hierarchy, all the transformations applied to the parent get applied to its children.

That means that if a parent has a non-uniform scale applied, its child objects will be distorted non-uniformly - getting stretched or squashed more in one direction than another.

When you add a child to a parent, Unity (by default) automatically re-calculates its local transformations to compensate for the parent's, so the net transformation on it remains as close as possible to what you had before parenting it. This can mask the effect of the parent's transformation at first.

As you rotate the child object relative to the parent's scaled axes, you change which way it's getting squashed or stretched by the parent's non-uniform scale.

eg. if I have a narrow wall perpendicular to a highly stretched axis of the parent, and gradually turn the wall until it's parallel to that axis, the wall will get longer and longer.

As a result, it's usually most predictable & controllable if you try to keep non-uniform scales only at the leaf level of your transform hierarchy (objects with no children of their own). You can use it to stretch your cubes into skinny beams and flat walls. Then when you need to combine those objects into larger constructs, put them inside container objects that have only uniform scaling applied (ideally 1, 1, 1), and keep your scales uniform at all parent levels.

---
Tags: unity, rotation, transformation, scale, hierarchy
---


# Question
Title: Why do I see "<" and ">" in Unity C# code?
I copied Unity code from a website and now it contains stuff like `&lt; T &gt;` which my IDE flags as an error.

It looks like the intended text has been corrupted somehow. What is this supposed to be, and how can I correct it?

```
public class Tree<T>
{
    public T Data { get; set; }
    public IEnumerable<Tree<T>> Childs { get; set; }
    public bool Opened { get; set; }

    public Tree()
    {
        Childs = Enumerable.Empty<Tree<T>>();
        Opened = true;
    }
}

```

# Answer
> 7 votes
HTML code uses angle brackets \< and \> to denote tags in its markup structure, eg.

> \<p\>This is a paragraph of text in HTML markup, and some of it is \<em\>*emphasized*\</em\>.\</p\>

Because of this, \< \> characters appearing in the text of the document can confuse the parsing. To avoid this, we can use what's called an escape sequence to describe the bracket character we want to use, instead of writing the character itself. In HTML, the escape sequences for these characters are:

* \< = `<` "less than"
* \> = `>` "greater than"

(Tip: hit the edit button to see where I've had to use escape sequences to ensure this answer renders as I intended!)

Many tools for editing web pages will automatically search text for \< \> characters and replace them with the matching escape sequences for you, so the author doesn't need to fuss with this.

Sometimes, they're over-eager about this, and convert characters that didn't need to be converted, resulting in mangled code samples like you showed in the question.

Fortunately, we can simply Find & Replace these two escape sequences back to the intended bracket characters to get the code as it was written (I also fixed the pluralization of "child" while I was at it):

```
public class Tree<T>
{
    public T Data { get; set; }
    public IEnumerable<Tree<T>> Children { get; set; }
    public bool Opened { get; set; }

    public Tree()
    {
        Children = Enumerable.Empty<Tree<T>>();
        Opened = true;
    }
}

```

In C#, angle brackets like these are used to denote Generics, special types that can adapt to one or more given type parameters.

For example, the generic `List<T>` means "A list that can contain some type `T`." By providing a concrete type like `int` we can form `List<int>`, a list of integers. And we can even nest those types, to make stuff like `List<List<int>>`, a list of lists of integers. That's what's going on where you see `IEnumerable<Tree<T>>` — it's an enumerable collection of Tree nodes containing Data of some type `T` ("enumerable" meaning we can iterate over the members of the collection in some order)

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


# Question
Title: Pathfinding: grid based map of irregular numbered tiles to mark connections
Given this map:

The floor tiles are separated from the rest (it's a map made in Tiled in separate layers) and as you can see, the id numbers are not in sequence.

How I would go about making connections from node to node so later the pathfinder can find a path?

The best approach I can think of is to iterate over all tiles (not just the floor ones) and that way the id's can be in sequence, but I want to find a way around this method because there's has to a way that I can't think of right now.

# Answer
Instead of having Id numbers you can assign a cost value to each tile based on the state of the tile. For example : if tile has enemy then give it cost value of 10000 and if there's a loot box then give it cost value of like 1. Your pathfinding algorithm can interpret this cost value as cost of connection and use this cost value to find the most favourable path for you.

consider this 1d array representation of 4x4 map, where tiles with 5 cost value has enemy and tile with 1 cost value has loot boxes, and 8 cost value for collider.

```
1,1,1,8,
1,5,1,8,
1,8,1,8,
5,5,1,1

```

the most favourable path here is (array indices) : 0-1-2-6-10-14-15
> 1 votes

# Answer
You could use dijkstra's algorithm where each node is on a floor tile

Youtube tutorial

You could generate the nodes & build connections once on initialisation. Traverse the map and place nodes on floor tiles. Look around the tile for other floor tiles and make new node connections.
> 0 votes

---
Tags: libgdx, path-finding, tiled
---


# Question
Title: How to place grass on custom terrain mesh
I made a custom terrain mesh and textured it, now I want to place grass on it, but I don't know how. I only find info about grass with the unity terrain. I am not even sure what exactly to look for.

What is the best/easiest way to place grass on a terrain? I'd like to do it in the shader if possible, but I guess I will need additional geometry if I want it to "stick out"?

(Random example picture http://www.beamng.com/attachments/stuff-png.16516/)

I'd appreciate a general outline on how to tackle this problem and maybe some links for further reading.

Thanks.

# Answer
> 3 votes
This is an old topic, but it's still valid.

There are a couple of ways you can handle grass outside of Unity's Terrain System.

The simplest way is to create your own planar mesh and apply a shader with back faces **or** use a reversed V pattern which are really close to each other and where each side is the mirror of the opposite. Then place copies of those manually one by one in your scene. The trick is to make sure it's both a static prefab as well as having GPU Instancing enabled on its material. This will allow the grass to be either batched or having a single copy stored in the GPU and rendered with the lighting variation. (It's one or the other, but by enabling both, the engine will which manage what's where based on the priorities.)

The **con** of that option is that it's time consuming.

The slightly more complex but **way** faster option is to use a particle (shuriken) system with a Mesh emitter with 0 `Gravity` and `Force` and with `Normal Offset` set so that the grass appears on the mesh's surface. You can make the grass particle infinite by disabling the `Over Lifetime` module in the particle, activating `Looping` and `Prewarm` and typing *Infinity* in the `StartLifetime` option. Ideally, you would have to have a script that calls the `Stop()` function so the particle system stops calculating generation, but still keeps the instantiated particles in the scene.

If these instructions are followed, this will generate grass with GPU instancing.

The cool thing about this possibility is that you can control the particle's features like cast/receive shadows, the amount of grass generated, if the grass is affected by light probs and reflection probs or not, etc. It makes it easy to setup with advanced graphical options.

You can even setup a master shuriken particle system that will generate multiple kinds of grass and flowers.

The only **con** to this option is the lack of LOD if you have some really complex geometry for the mesh on which the grass texture appears. (It will apply Mipmaps if the textures have Mipmaps activated!) If you wonder, yeah it's possible to have the wind's force affect the particles... but that has to be done in the shader used for the particle.

# Answer
> 1 votes
You need to create a texture for your grass, then create the geometry that the texture will be rendered onto. Use each vertex in the terrain as a starting point for the origin where to render each instance of the grass geometry and using a pseudo random offset for each origin, you could render lots of grass fairly quickly

Google will provide many shader driven approaches and other techniques.

# Answer
> -4 votes
It is very simple, Create one pdf like a grass texture. Place it in your unity package and goto terrain settings in 6th tab you can find a button lime a grass select it. select edit Details -\> Add Grass Testure -\> Detail Texture. in detail texture select the pdf file you have been created. adjuse the brush size and opacity. click your terrain.

Please Click the link For more details:

---
Tags: unity, shaders, terrain
---


title: Will Geolocations for IPs ever change?

text:
# Question
Title: Will Geolocations for IPs ever change?
I'm making a game where the geographic location of a user is used to give them a little flag icon next to their user name. To do this, I've been using the ipstack API. However, the API only allows up to 10,000 requests per month, and since I make a request every time a user connects, this could easily lead to overuse.

Would it make sense to just store geolocation data on my server and only make a request when an unknown IP connects? Or will the geolocation data ever change for an IP?

# Answer
> 1 votes
This is partially answered over here. In short: don't count on consistency. IPs probably don't get re-assigned/moved often, but services might change their algorithms, have bugs, etc.

Realistically, unless the perfect consistency of this data is critical to your game, you should be able to get away with caching prior results.

A reasonable hybrid strategy would be to store the result of the call and the time it was made with the rest of a user's data. Then when a user logs in with a last-checked date older than some threshold, refresh it. You could also maintain an internal ledger of how many API requests you have remaining for the month, holding some portion in reserve for new users.

# Answer
> 0 votes
Yes, IP addresses can change their physical location. ISPs sometimes trade blocks of IP addresses between each other. A large ISP might also change its regional IP address allocations for internal reasons. But this happens quite rarely.

But keep in mind that IP addresses are registerd block-wise. IP blocks get assigned to continents. The regional internet registires then usually break these blocks into subnets which get assigned to countries which then get broken up into sub-subnets which get assigned to ISPs. So when you just want to know the country of the user and not the exact city, then you just need to know the country the IP *range* with the user's IP is allocated to. There are many databases around which map IP ranges to countries. They are not hard to find with search engines and they are not so large that they wouldn't fit inside your application.

---
Tags: multiplayer, server, geolocation
---


# Question
Title: How to implement n-body in an Entity Component System
Recently I've been throwing problems at Entity Component Systems to see how far I can push the paradigm. One problem in particular I struggle with, which is writing an elegant implementation of the n-body algorithm.

First, let me clarify the terminology of ECS:

* **Component**: a structure that holds data
* **Entity**: a unique identifier used to associate and retrieve component data
* **System**: logic executed on entities that have a specific set of components

In ECS, for every frame, each system linearly walks over the matching entities. A typical ECS implementation lays out data consecutively in memory per component, which has as advantage that it is very CPU-cache friendly.

To implement n-body, we could have three components (Location, Mass, Speed). We could then have a system called Gravity, which will update the speed of all entities that have Location, Mass and Speed. Then there could be a Move system that walks over entities with Location and Speed, and updates the locations.

For every matching entity, Gravity will have to walk over all the entities (minus one) to compute the attraction force. The first problem is, how do I efficiently get the relevant entities? A query seems wasteful since the entity set it needs is the set that Gravity is already walking over.

The second problem is when entity A computed the attraction force from entity B I'd like to reuse the computed distance when calculating the attraction force from A on B. Ideally these two computations take place in the same iteration. That, however, impacts how I iterate over the entities. If I computed A \<-\> B when I processed A, I don't need to iterate over A anymore when processing B.

I am not actually interested in the most practical way to implement n-body, but am curious if/how this kind of problem can be elegantly implemented with ECS.

# Answer
One nice thing about systems in an ECS architecture is that they don't all necessarily need to follow the same structure of `for(int i = 0; i < entities.length; i++) process(entities[i]);` and then implement `process(entity)` as if there would be no other entities in the universe. If there is a smarter way to process entities than sequentially in natural order, you can do that.

Your gravity system can use two nested for-loops instead:

```
for(int a = 0; a < entities.length; a++) {
    for(int b = 0; b < a; b++) {
        calculateAttractionBetween(entities[a], entities[b]);
    }
}

```

This loop iterates the entities and then calcualtes the attraction between the current entity and every entity which came before. That way you never handle a combination of the same two entities. So the function `calculateAttractionBetween` only needs to calculate the distance between the two entities once, and then use that distance to calculate both the effect of `a` on `b` as well as the effect of `b` on `a`.

This algorithm still has a computational complexity of `O(n²)` and becomes cache-unfriendly as soon as your entity-array doesn't fit into the CPU cache. But if you want an *accurate* n-body simulation where *everything* is affected by gravity, then you won't get around this. The n-body problem simply is computationally expensive. There are a few optimizations you can do if you are willing to sacrifice accuracy. Like if you have some objects where the differences in mass are so large that the effect of one on the other can be ignored or when you can create localized sub-simulations which treat other sub-simulations far away as if they were a single gravity source. But all these optimizations sacrifice accuracy, so we are no longer talking about an n-body simulation like asked in the question.
> 5 votes

# Answer
> For every matching entity, Gravity will have to walk over all the entities (minus one) to compute the attraction force. The first problem is, how do I efficiently get the relevant entities? A query seems wasteful since the entity set it needs is the set that Gravity is already walking over.

Depending on how detailed you want it, everything is relevant, at least in physics. Basicly, everything attracts everything.

So, if you have a physics game with 3 to maybe 8 Objects, thats not a big deal.

But if you got a space simulation, you dont need to calculate the gravitational effect of a screwdriver to the pilot or the mascot dog.

In that case, you only need to calculate the gravitational force of objects with a certain gravitational impact. Planets excert a massiv amount of gravity, the sun does that aswell and most moons are also relevant. After that its debateble. On top of that, just asume Planets are on rails and are basicly indisruptable by your capabilites, else you got a new Universe Sandbox.

And even then it is easier to just calculate the influence of the object with the highest gravitational impact nearby. You dont need to know how much Pluto tuggs on you, when you are 500 km away from the sun. This is called the sphere of influence and is used in Kerbal Space Program to not calculate every effect, just for one body.

> The second problem is when entity A computed the attraction force from entity B I'd like to reuse the computed distance when calculating the attraction force from A on B. Ideally these two computations take place in the same iteration. That, however, impacts how I iterate over the entities. If I computed A \<-\> B when I processed A, I don't need to iterate over A anymore when processing B.

Again, if you only have a few objects, thats not a big deal. If you have only 8 objects, you could store the position of an object and additionally the position for each other object. Calculating the distance isn't that fast, but really not a problem. To iterate other them, you will need to take the hard way. E.G. for four Entities.

```
1.
A <-- pair A with every other Entitiy and apply each other forces to both,
B     like (A,B), (A,C), (A,D).
C
D

2.
A
-
B <-- Repeat the same with B, but ignore A, so (B,C), (B,D)
C
D

3.
A
B
-
C <-- Repeat with (C,D)
D

4. Only D is left and doesnt need to apply forces.

```

If you can simplify your calculations, like with a sphear of Influence or only certain bodys apply gravity, its much simpler and you only need one direction (Only A --\> B, not B --\> A aswell). Only exception then would be something like a gravity mine, that creates its own gravity, but can be influcenced by gravity.

> I am not actually interested in the most practical way to implement n-body, but am curious if/how this kind of problem can be elegantly implemented with ECS.

If you can make and ECS work for certain effects, just dont. Its not helpful to break ECS just to strangly develop a system that works, but is hard to manage and error prone.

If you only got a hammer, every problem looks like a nail.
> 1 votes

---
Tags: game-design, algorithm, entity-system, entity-component, entity-component-system
---


title: Running a scene in the background

text:
# Question
Title: Running a scene in the background
I've made 2 scenes where a room is another scene and the other is the outside of it. But whenever I do something in either scenes, and enter the other, it resets everything I did in the first one. I'm thinking of making the scene running in the background the whole time but how can I do that?

# Answer
> 1 votes
When adding your scene using SceneManager.LoadScene(scene, mode), pass the LoadSceneMode.Additive mode, to add your scene and keep the old one.

This might require some adjustments to make sure both scenes are placed properly in the world and make the transition smooth. By that I mean, when you add a new scene, you shuold make sure to offset it to a specific location to fit properly in your world. On a unity forum here there are many people asking for that feature, so until something changes, the only way is to do it manually.

Another way is to use the Object.DontDestroyOnLoad(target) on your scene, which will keep it in memory unless you destroy it manually. This will keep your scene when loading a new one. However I don't think this is the best way, as this method is better used for things like the player or the UI which are the same from one scene to another.

**Solve lag when loading a new scene**

Just keep in mind, every time you load a new scene, there might be some lag as everything is loaded on the same thread. You can also use SceneManager.LoadSceneAsync to load the scene in the background, although once the scene is loaded, every object inside it will call the `start` method, with might still cause some lag.

One way to solve this, is when you enter an area with a few houses, load the scenes with the houses as well, so that when you walk into a house, you don't have to load anything new, you just have to make the house scene visible.

**Quests repeat when a new scene is loaded**

Whenever you complete a quest, or progress in one, you should save that information somewhere, so the next time (even after the game closes) the player attempts to start the same quest, they will fail as it's solved already.

To solve that, you can save that information together with the player, you can have an array for example, holding all the started quests, and a number showing the progress on the quests, with `-1` showing that the quest is finished.

So now, every time the player attempts to begin a quest, the script responsible for that searches that array for that quest, if it doesn't find it, the quest begins, if its there, depending on the state of the quest, display the right message.

The same can be done when you load a new scene. Suppose that when you enter a specific building, an NPC is there if the quest is not started, but the same NPC is gone while doing the quest. In this case, when the scene is loaded, it searches the same array for the quest, if the quest has been started, don't initialize the NPC.

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


# Question
Title: How would I move a character In an RPG with Bullet Physics/Ogre3D?
lately I have been having problems with moving my character in my Ogre3D game. Basically I am moving the character with bullet's `RigidBody->translate()` function, but when doing so and bumping into a wall, I go slightly through it and then get bounced back. I am wondering if there is another good way to move my character(who has a sphere collision shape) around in a simple Plane-type world with walls?

The libraries I am using that are relative to this are 'Ogre3D' and 'Bullet Physics'.

# Answer
Although I haven't worked with the bullet physics engine specifically, I've done something very similar in another physics engine. The way that I solved it was to set the rigid body's linear velocity instead of translating it directly. Movement and collisions were then automatically handled by the physics engine update phase.

From the documentation there seems to be a `btRigidBody::setLinearVelocity` method that you can use. So for instance, if you don't want any accelerations happening, just set the linear velocity to an appropriate value whenever the character is moving, and set it back to (0,0,0) when the character is supposed to stop (i.e. when the player releases the key).

As for which values to use, the usual approach would be to start with desired speed of your character (as a float/scalar) and then multiply it by a normalized vector that is pointing in the direction you want to move. From what I can see the `btVector3` class already has methods for all of this.

Alternatively, you might consider treating the character as a complete physics object, and handle movement using either the `applyForce` or `applyImpulse` methods. These would result in a body acceleration, so your characters will have momentum and the results will probably look nicer this way. But you need to take some extra measures, for instance, by making sure the linear velocity never exceeds a certain limit, either by clamping it or playing around with damping/friction. So it will be a bit harder to implement and finetune.

Experiment with both approaches and then choose the one that behaves closest to your needs.
> 10 votes

# Answer
For the record, my experience with physics is using Chimpunk in a 2D game engine, but I'm pretty sure this concept translates into 3D just fine.

I'm assuming that your character is a physics body with weight and such. The best way to do this is to do a very simplified simulation of walking. Think of it like this: If you're standing, your feet have a lot of friction, so you don't just slide around. When your moving, it's roughly equivalent to removing that friction (since you're not resisting the movement with your feet) and applying a direction force. I'm *not* saying that you should individually simulate each foot pushing on the ground -- a rigid body is what you want.

* When your character isn't actively trying to move, make their velocity damping high so that they'll remain stationary.
* When your character is moving, lower their velocity damping and apply a force in the direction of movement. Set your damping and force so that the character moves at a reasonable speed.
* If the character is in the air, set the damping very, very low. If you want to be realistic, don't allow them to apply any force to change their direction while in the air. You can strike a happy medium here by allowing them to apply a much smaller force, giving them some limited ability to adjust their trajectory while airborn.

Here's where get gets a little complicated:

* If the character is already moving and they change direction, you'll need to compensate for your momentum by adjusting the direction in which you apply the force. For instance, if your character is moving due north and turns due east, you need to apply your force in a direction that's half way between the opposite of the character's current direction of travel and their intended direction of travel. As the direction of travel changes, adjust the force so that it's always half way between the two, and your character will quickly and smoothly change directions.

If you tune your force and damping correctly, applying a force will always give you the most realistic result, particularly if the character is going to be pushing objects around. Translating is going to be the worst way to do it, since the physics engine doesn't really consider that to be movement. Setting the velocity directly is somewhat better, but in my experience the best results can be obtained by using force and damping.

Hopefully I explained this well enough. Feel free to ask if you need clarification. :)
> 10 votes

# Answer
For bullet 2.87 it appears the proper method is to have a tick callback that updates at the internal simulation update rate (possibly many 100s of Hz), and setWorldTransform() on kinematic bodies will smoothly update the position:

This part is in the manual:

```
// set the rigid body as kinematic
rigid_body->setCollisionFlags(
    rigid_body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
rigid_body->setActivationState(DISABLE_DEACTIVATION);
...

```

This part was more tricky to figure out:

```
void externalTickCallback(btDynamicsWorld *world, btScalar timeStep)
{
  // get object passed into user data point
  Foo* foo = static_cast<Foo*>(world->getWorldUserInfo());
  ... loop through all the rigid bodies, maybe foo has them
  {
    if (rigid_body->getCollisionFlags() & btCollisionObject::CF_KINEMATIC_OBJECT)
    {
      btVector3 kinematic_linear_vel = ... // get velocity from somewhere
      btTransform trans;
      rigid_body->getMotionState()->getWorldTransform(trans);
      trans.setOrigin(trans.getOrigin() + kinematic_linear_vel * time_step);
      // TODO support angular velocity
      rigid_body_->getMotionState()->setWorldTransform(trans);
    }
  }
}
...
my_dynamics_world->setInternalTickCallback(tickCallback, static_cast<void*>(this), true);

```

This was helpful documentation in btRigidBody.h https://github.com/bulletphysics/bullet3/blob/master/src/BulletDynamics/Dynamics/btRigidBody.h:

> ///- C) Kinematic objects, which are objects without mass, but the user can move them. There is one-way interaction, and Bullet calculates a velocity based on the timestep and previous and current world transform.

setLinearVelocity() does not work for kinematic objects (maybe it used to in earlier versions?). But the dynamics world will understand setWorldTransform() and calls to getLinearVelocity() on the kinematic object will return the velocity set in the tick callback (it probably returns an average if those velocities were to change from internal tick to tick).

https://github.com/bulletphysics/bullet3/issues/1204 \- the issue poster has the right idea but the response isn't helpful.
> 0 votes

---
Tags: c++, ogre, bullet-physics, control
---


# Question
Title: Unity GameObject.Find() not working in batchmode?
I am trying to make GameObject.Find() work in batchmode but for some reason it returns a null object.

my code:

```
public class test: Monobehaviour {
    public static GameObject go;

    static void doing()
    {
        go = GameObject.Find ("testing");
    }
}
//testing is the name of the gameobject in the editor

```

I call it from the console on mac using: /Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -projectPath "" -executeMethod test.doing

# Answer
> 1 votes
When running in batchmode, Unity does not load the scene you normally see when opening the project in the editor. Thus, there are no `GameObjects` to find.

If you add `using UnityEditor.SceneManagement;`, you can use the SceneManager to open your scene, then continue as expected.

Assuming your scene file is under `Assets/Scenes` and named `Main`, and includes an object named `TestObject`:

```
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;

public class BatchTest : MonoBehaviour {
  static void runTest() {
    EditorSceneManager.OpenScene("Assets/Scenes/Main.unity");
    GameObject go = GameObject.Find("TestObject");
    ...
  }
}

```

To run this in batchmode, similar to your example, I run: `/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -projectPath "/path/to/project" -executeMethod BatchTest.runTest -logfile`

(`-logfile` with no specified logfile will output to console on Linux/Mac)

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


# Question
Title: Implementations for storing entities in an ECS system
I'm restructuring my model of entities, components and systems, where entities are:

```
const createEntity = (name, components) => ({
    id: genUniqueId(),
    name: name,
    components: components
});

```

And I came across a question, and would like to hear someone's experience about it. The question is what are the advantages and disadvantages of each of the following implementation approaches:

1 - Implement all entities in a single global object, and traverse this object by applying the systems in each entity, example:

```
const entities = {};
for(let key in entities)
    for(let system of systems)
       system(entities[key]);

```

2 - Create several global variables for each group that the systems serve, example:

```
const players = {};
const monsters = {};
const clouds = {};

for(let key in players)
       systems['input'](players[key]);

for(let key in monsters)
       systems['simpleAI'](monsters[key]);

for(let key in clouds)
       systems['wind'](clouds[key]);

```

3 - Create local variables within the systems to store the entities, and functions for each system to add and remove entities from their internal objects, example:

```
const windSystem = () => {
    const clouds = {};
    for(let key in clouds)
       ...
};

const addEntityInWindSystem = () => {...};
const delEntityInWindSystem = () => {...};

```

My intention with the question is just to look for other solutions or even understandings about the cons and advantages that each implementation can bring me during development.

# Answer
Sander's answer mentioned families, and I wanted to add some info:

* Families group entities together based on component criterion.
* Usually, a system has one family that forms its entity list.
* Entities can be added to the system/family when they are added to the game engine, and when the system itself is added to the game engine.

Here's a basic working implementation: (I normally don't write code for people, but this is best illustrated in a working example)

```
class Engine {
  constructor() {
    this.systems = [];
    this.entities = [];
  }

  process() {
    this.systems.forEach(system => { system.process(system.family.getEntities()) });
  }
}

class System {
  constructor(family) {
    this.family = family;
  }

  process() {}
}

class Family {
  constructor(engine, all=[], one=[], none=[]) {
    this.all = all;   // entity must have all of these components
    this.one = one;   // entity must have at least one of these
    this.none = none; // entity must have none of these
    this.engine = engine;
  }

  matches(entity) {
    let entityComponents = entity.components.map(comp => comp.constructor);  // get constructors
    let allPassed = this.all.every(comp => entityComponents.includes(comp));
    let onePassed = !this.some || this.one.some(comp => entityComponents.includes(comp)); // if there are no 'one's, it passed (you don't need this with Array.every)
    let nonePassed = entityComponents.every(comp => !this.one.includes(comp));
    return allPassed && onePassed && nonePassed;
  }

  getEntities() {
    return this.engine.entities.filter(entity => this.matches(entity));
  }
}

class Entity {
  constructor() {
    this.components = [];
    this.id = Entity.nextId;
    Entity.nextId++;
  }
  getComponent(constr) {
    for (let i=0; i<this.components.length; i++) {
      if (this.components[i].constructor === constr) return this.components[i];
    }
    return null;
  }
  toString() { return `Entity-${this.id}`; }
}
Entity.nextId = 1;

// --- sample usage ---
// no need to subclass a `Component` class, because you need to call `super`, and it's pretty useless to have to do for every component type
class HealthComponent {
  constructor(initial) {
    this.health = initial;
  }
}

class HealthSystem extends System {
  constructor(engine) {
    super(new Family(engine, [HealthComponent]));
  }

  process(entities) {
    entities.forEach(entity => {
      if (entity.getComponent(HealthComponent).health <= 0) console.log(entity + " died");
    });
  }
}

let engine = new Engine();
engine.systems.push(new HealthSystem(engine));

let deadEntity = new Entity();
deadEntity.components.push(new HealthComponent(0));
engine.entities.push(deadEntity);

let aliveEntity = new Entity();
deadEntity.components.push(new HealthComponent(1));
engine.entities.push(aliveEntity);

engine.process();
```

**This needs to be optimized so that a family's matched entity list is only updated when it *needs* to, not every time it is queried.** You need to update each family when either A) an entity is added to or removed from the engine or B) an entity gains or loses a component. I would store a cached list of matched entities in each family, and, when either A or B occurs, update each list.
> 1 votes

# Answer
Neither of the three approaches are typical. The first approach could be considered a "naive" approach as it works, but is not very efficient because you'd need to check for every entity if it matches the system.

What an ECS framework typically does is organize entities in *groups* that are based on the components that they have. The groups are then matched to the systems based on a *system signature*, which lists which components the system is interested in.

Lets say I have set of entities A with components `[Position, Velocity]`. I have another set B `[Position, Velocity, Mass]`. These two sets would be stored in different groups, and systems are matched against these groups. A system with a `[Position, Mass]` signature would only be matched against group B. A system with `[Position, Velocity]` would be matched against both.

You could represent this with something like this:

```
const A = [{entity: 0, components: {position: {x:1, y:2}, velocity: 5}}, ...]
const B = [{entity: 10, components: {position: {x:3, y:4}, velocity: 5, mass: 8}}, ...]

```

The groups here are "A" and "B". The system is "move". Note that entities are an id, similar to a primary key in a database table. You can then match your systems against these groups any way you like.
> 2 votes

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


# Question
Title: Modifying Animator Controller parameters
I have this GameObject with an AnimatorController. The AnimatorController has several states in which I want to parametrize the animation's speed because configuration. For this, I've created an animation parameter, called "RotationMultiplier" and set up the "Speed/Multiplier" value to this paramter on the needed states.

Now, my idea is being able to configure this speed from a script "somewhere." I've read a bit about StateMachineBehaviours, but my initial idea was executing this once, instead of once in each frame/state.

The "OnStateMachineEnter" function does not execute at all, and with the OnEnable I don't have access to the Animator (nor the parameters).

So, any idea?

# Answer
> 1 votes
If this is just an initial configuration, you can set it from the `Start()` method of an ordinary `MonoBehaviour` attached to the `GameObject` you're configuring.

Here's an example that lets you define the parameters in data, and tune them live in the Inspector while the game is playing.

```
public class AnimationConfiguration : MonoBehaviour {

    [System.Serializable]
    public struct FloatParameter {
         public string name;
         public float value;
    }

    public FloatParameter[] floatParameters;

    void Start() {
        var animator = GetComponent<Animator>();

        foreach(var parameter in floatParameters)
            animator.SetFloat(parameter.name, parameter.value);
    }

    // Allow live editing in the Inspector during play mode.
    void OnValidate() {
        if(Application.isPlaying)
            Start();
    }
}

```

---
Tags: unity, animation, animation-controller
---