# Question
Title: How to make a world map from image like in paradox games? (Java, LibGDX)
I'm working on a grand strategy game similar to those made by Paradox Game Studios with their Clausewitz engine. I'm trying to create the world map from an image. On that you can see the areas, and every area has a unique color. I made a JSON file from this image and then the stored object contained every area with their points, their neighbours and their borders and in the game I just had to load this JSON file. I made a stage and added a custom object what would draw my map area by area, and pixel by pixel but with this method the FPS was really small (I think 8 was the max). Now I don't have any clue how I should make it work.

If there's any document about this I'd like to read it.

Image:

Map (which will be deserialized with JSON; I'm using Jackson JSON because I prefer that much more)

```
    public class Map implements Serializable {

    private static final long serialVersionUID = -518329203219605551L;

    public Area[] areas = new Area[0];

    public int width;
    public int height;

    public Area byID(int id) {
        for (Area area : areas) {
            if (area.id == id) {
                return area;
            }
        }
        return null;
    }

    public Array<Area> areas() {
        return new Array<>(areas);
    }

    private void add(Area a) {
        Area[] array = new Area[areas.length + 1];
        for (int i = 0; i < areas.length; i++) {
            array[i] = areas[i];
        }
        array[areas.length] = a;
        areas = array;
    }

    private int indexOf(int rgb) {
        for (int i = 0; i < areas.length; i++) {
            if (areas[i].rgb == rgb) {
                return i;
            }
        }
        return -1;
    }

    public Area area(int x, int y) {
        for (Area area : areas) {
            if (area.hasPoint(x, y)) {
                return area;
            }
        }
        return null;
    }

    public static void fix(Vector2 vector, float width, float height) {
        if (0 > vector.x) {
            vector.x = width - vector.x;
        }
        if (0 <= width) {
            vector.x = vector.x - width;
        }
    }

    public static Array<Vector2> neighbours(Vector2 vector, float width, float height) {
        Array<Vector2> vectors = new Array<>();
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                Vector2 v = new Vector2(vector.x + dx, vector.y + dy);
                fix(v, width, height);
                if (vector.y >= 0 && vector.y < height) {
                    vectors.add(v);
                }
            }
        }
        return vectors;
    }

    public static Map fromPNG(BufferedImage img) { // used only for build the JSON file
        try {
            Map map = new Map();
            map.width = img.getWidth();
            map.height = img.getHeight();
            System.out.println(map.width + " * " + map.height);
            for (int y = 0; y < img.getHeight(); y++) {
                for (int x = 0; x < img.getWidth(); x++) {
                    int rgb = img.getRGB(x, y);
                    Area area = map.byID(rgb);
                    if (area == null) {
                        area = new Area();
                        area.id = rgb;
                        area.rgb = rgb;
                        map.add(area);
                        System.out.println("New area: " + area.id);
                    }
                    Vector2 p = new Vector2(x, y);
                    fix(p, img.getWidth(), img.getHeight());
                    area.add(p.x, p.y);
                    for (Vector2 point : neighbours(p, img.getWidth(), img.getHeight())) {
                        int c = new Color(img.getRGB((int) point.x, (int) point.y)).getRGB();
                        if (c != rgb) {
                            area.add(c, x, y);
                        }
                    }
                }
                System.out.println("Row: " + y + " is done.");
            }
            System.out.println("Converting ids to readable");
            for (int i = 0; i < map.areas.length; i++) {
                map.areas[i].id = i;
                Set<Integer> set = new HashSet<>(map.areas[i].neighbors.keySet());
                HashMap<Integer, List<Vector2>> copy = new HashMap<>();
                for (Entry<Integer, List<Vector2>> entry : map.areas[i].neighbors.entrySet()) {
                    copy.put(map.indexOf(entry.getKey()), entry.getValue());
                }
                map.areas[i].neighbors.putAll(copy);
                for (Integer id : set) {
                    map.areas[i].neighbors.remove(id);
                }
            }
            System.out.println("Flipping coords");
            for (Area area : map.areas) {
                for (Vector2 p : area.points) {
                    p.y = map.height - 1 - p.y;
                }
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

```

Area object (which you can see in the Map class)

```
public class Area implements Serializable {

    public static class VectorSerializer extends JsonSerializer<Vector2> {
        @Override
        public void serialize(Vector2 v, JsonGenerator jgen, SerializerProvider sp) throws IOException {
            jgen.writeStartObject();
            jgen.writeNumberField("x", v.x);
            jgen.writeNumberField("y", v.y);
            jgen.writeEndObject();
        }
    }

    public static class VectorDeserializer extends JsonDeserializer<Vector2> {
        @Override
        public Vector2 deserialize(JsonParser jp, DeserializationContext dc)
                throws IOException, JsonProcessingException {
            JsonNode node = jp.getCodec().readTree(jp);
            return new Vector2((float) node.get("x").asDouble(), (float) node.get("y").asDouble());

        }
    }

    private static final long serialVersionUID = 2288613202778397975L;
    public Set<Vector2> points = new HashSet<>();
    public int id = -1;
    public int rgb;
    public HashMap<Integer, List<Vector2>> neighbors = new HashMap<>();
    public boolean naval = false;

    private Color color;
    private java.awt.Color java;

    public Color color() {
        if(color==null) {
            java = new java.awt.Color(rgb);
            String hex = String.format("#%02x%02x%02x", java.getRed(), java.getGreen(), java.getBlue());
            color = Color.valueOf(hex);
        }
        return color;
    }

    private Rectangle rect;

    public float x() {
        return rect.x;
    }

    public float y() {
        return rect.y;
    }

    public float w() {
        return rect.width;
    }

    public float h() {
        return rect.height;
    }

    public Rectangle rect() {
        return rect;
    }

    public void bounds(float x, float y, float w, float h) {
        rect = new Rectangle(x, y, w, h);
    }

    void add(float x, float y) {
        points.add(new Vector2(x, y));
    }

    void add(int rgb, int x, int y) {
        List<Vector2> list = neighbors.getOrDefault(rgb, new ArrayList<>());
        list.add(new Vector2(x, y));
        neighbors.put(rgb, list);
    }

    public boolean hasPoint(float x, float y) {
        for (Vector2 p : points) {
            if (p.x == x && p.y == y) {
                return true;
            }
        }
        return false;
    }

}

```

The Game Screen

```
public class GameScreen implements Screen {

    private CW game;
    private Save save;
    private Stage stage;
    private OrthographicCamera camera;

    public GameScreen(CW game, Save save) {
        this.save = save;
        this.game = game;
        this.camera = game.cam();
        camera.setToOrtho(false, save.map().width, save.map().height);
        game.viewport().setWorldSize(save.map().width, save.map().height);
        game.viewport().apply(true);
        this.stage = new Stage(game.viewport());
        InputMultiplexer input = new InputMultiplexer(stage, new InputAdapter() {
        });
        Gdx.input.setInputProcessor(input);
        stage.addActor(new WorldMap(this.save.map(), camera));
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        handleCamera();
        camera.update();
        game.batch().setProjectionMatrix(camera.combined);
        Gdx.gl20.glClearColor(0f, 0f, 0f, 1f);
        Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
        System.out.println(Gdx.graphics.getFramesPerSecond()); // TODO remove
    }

    private void handleCamera() {
        if (Gdx.input.isKeyPressed(Keys.LEFT)) {
            camera.translate(1, 0);
        } else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
            camera.translate(-1, 0);
        } else if (Gdx.input.isKeyPressed(Keys.UP)) {
            camera.translate(0, 1);
        } else if (Gdx.input.isKeyPressed(Keys.DOWN)) {
            camera.translate(0, -1);
        }
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }

}

```

The Actor:

```
public class WorldMap extends Actor {

    private Map map;
    private OrthographicCamera cam;

    public WorldMap(Map map, OrthographicCamera cam) {
        this.map = map;
        this.cam = cam;
        setBounds(0, 0, map.width, map.height);
    }

    private ShapeRenderer shape = new ShapeRenderer();

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.end();
        shape.begin(ShapeType.Filled);
        for (Area area : map.areas) {
            shape.setColor(area.color());
            for (Vector2 p : area.points) {
                if (cam.frustum.pointInFrustum(p.x, p.y, 0)) {
                    shape.rect(p.x, p.y, 1, 1);
                }
            }
        }
        shape.end();
        batch.begin();
    }

}

```

Thanks!

# Answer
In `WorldMap.draw` you are reconstructing the map texture every frame by drawing a bunch of 1px by 1px rects.

This is a very expensive way of drawing bitmaps, because it not just runs on the CPU instead of the GPU but also uses a very inefficient method (calling a method to fill rectangles instead of changing the color values of a pixel buffer).

If possible, it would be good to see if you can do your map rendering algorithm on the GPU by passing the raw data to a shader. But there might be good reasons to implement your map rendering algorithm on the CPU, for example, because it's too complicated for a shader or because you lack the necessary shader programming know-how. In that case you should:

1. render your map to a `Pixmap` (which offers you a more appropriate `drawPixel(x, y, color)` method)
2. use that pixmap to create a `Texture`. (the difference between a pixmap and a texture is that pixmaps are stored in system RAM while textures are uploaded to GPU RAM)
3. just `draw` that texture on each subsequent call to `draw`. Do not recreate the pixmap or texture unless the map data has changed. Reuse the same texture on every frame.
> 2 votes

---
Tags: java, libgdx, rendering, maps, image
---


# Question
Title: When to use NativeArray over List or Array?
I have been reading about NativeArray, but I have to admit I do not understand it.

From the documentation:

> A NativeArray exposes a buffer of native memory to managed code, making it possible to share data between managed and native without marshalling costs.

I have to admit I do not understand a word of what is being said in here.

What is the point of using it instead of normal arrays, or List? Would it be possible for someone to show me an example of how to use it, and how not to use it?

# Answer
# Jobs system

The rather new Jobs System of Unity makes use of native arrays (as well as their new cousins `NativeList`, `NativeHashMap`, `NativeMultiHashMap` and `NativeQueue`). The jobs system allows you to distribute expensive gameplay computations on multiple CPU cores. It also allows you to use Burst-compiled code, which is much faster than regular code. But the tradeoff is that burst-code can't use most default C# features. The Native family of containers are a substitute for regular C# container classes.

Native containers are mostly used for sharing data between jobs and "regular" game code. The whole system and the way it changes the way you structure the code of a Unity game is quite complex to explain just within the scope of a single answer. I recommend this Unity GDC talk for an introduction to it.

# Native Plugins

Native arrays are also relevant for communicating with a Native Plugin. Native plugins are DLL files which are compiled from code which can be written in any programming language, including "unsafe" programming languages like C++ which allow you to write very fast code by omitting some common sense safety checks. When you use native arrays, then both Unity code and DLL code can operate on the same data. Otherwise you need to copy the whole array back and forth which each function call, which can be so slow that it negates the performance gains you hoped to get form using a native plugin in the first place. Example:

```
// importing the function UpdateArray from myLibrary.DLL
// The function expects a memory location ("pointer") where an array of bytes can be found.
[DllImport("myLibrary")]
unsafe public static extern void UpdateArray(void* bytes);

// declaring a native array used for communication with the DLL
private NativeArray<byte> nativeByteArray;

// call the function from the DLL each update while passing the array by reference instead of by value
void Update() {
   unsafe {
      void* ptr = NativeArrayUnsafeUtility.GetUnsafePtr(nativeByteArray);
      UpdateArray(ptr);
   }
}

```

Native plugins lost a lot of relevance in the past couple years, because performance optimizations, feature additions and 3rd party assets made them unnecessary for many use-cases. Also, native plugins must be compiled separately for every platform, and not every technology makes cross-compilation as easy as Unity does. So they can be an additional hurdle for creating a cross-platform game.

But they can still be useful for some less usual scenarios, like interfacing with non-standard hardware.
> 8 votes

# Answer
I'm not an expert on native code, so I won't go into a lot of detail here, but I still think I can give you enough information to answer the question

NativeArray's can be used anywhere if you want to, but are primarily used within Unity's Job system. And their ecs system (or dots) uses it aswell (at the moment of writing, dots is still in preview, as in beta).

Unity's job system is made to be both fast and safe for multithreading. By that I mean that they do a lot of checks and add some limitations, to make sure you can't get some common errors when writing multithreaded code, as the architecture simply won't allow you to do so.

Those limitations inlude the fact that you are not allowed to reference classes inside jobs for instance (only structs). This is great as it means that you can't modify the same value in 2 jobs run **at the same time**, you can't accidentally do that as each job gets a copy of the value, meaning 2 jobs never get the same value in memory. On the other side, this also means that for the same reason, 2 jobs run **after each other** can't modify the same value.

Meet NativeContainers. They are structs that point to a piece of Native memory, meaning they can be used inside the job system and if 2 jobs are run after each other they can still access the same (native) memory. Unity then build their safety system around these NativeContainers. Meaning for instance that if you do try to write to the same memory in a NativeContainer from 2 different jobs (that can run at the same time), Unity will throw errors telling you that you are not allowed to do that and should make sure 1 of the jobs is dependent on the other to be completed first.

Another advantage is that because Unity forces you into a certain pattern with a lot of limitations, which includes using NativeCollections, Unity can optimize a lot of things for you when you enable the Burst compiler. Meaning you can write highly performant C# code. Which can be a huge difference (depending on the scenario).

---

There are however some rules applied to NativeArrays. These rules are basically there to ensure you use the NativeArray correctly.

* unlike regular arrays which allow you to populate it with instances of both classes and structs, the NativeArray only allows you to popuate it with structs.
* You have to dispose the NativeArray after you are done with it. Else you'll get memory leaks. This is because the NativeArray uses native memory instead of managed memory. For managed memory, the garbage collector makes sure data that is no longer referenced gets dealocated. This is not the case with the memory allocated for the NativeArray, you have to deallocate that memory yourself by calling Dispose.

You can find more background information about the safety system here.

---

As for when to use it:

I personally wouldn't advise you to use it if you are not also using the jobs system (Or dots as that uses the jobs system aswell), as the difference in performance might not even be noticable when used in regular Unity projects while the disadvantages remain. But don't take my word for it, check it yourself to be sure (in build, as Unity does a lot of extra checks in the editor that slow it down)

If you are using the jobs system, you should use them as you can't use regular arrays inside jobs.

There isn't really a point of showing you how to use a NaiveArray outside of the Job System (other then perhaps plugins already done in the other answer), and giving an example of the Job System requires me to explain a lot of the Job system itself which falls outside of the scope of this answer. So instead I would advise you see this example here, or to search for examples about unity's Job system.
> 4 votes

---
Tags: unity, c#, unity-job-system
---


# Question
Title: I need to replace the sprite at runtime Unity 2d
I need a help, I have some code in Unity that should replace the player's sprite at runtime. But this code does not make it correctly, it does't make the change. Could you help me? Thanks

```
using UnityEngine;
using System.Collections;

public class PlayerBehavior : MonoBehaviour {

  public enum Skins
  {
    normal,
    verde
  }

  private Skins skinAtual;

  private Rigidbody2D player;
  public float height;
  private Transform posicao;
  public float jumpForce = 10f;
  private AudioSource audio;
  public DeathMenu deathMenu;
  private float initialX;
  public float goBackSpeed = 10f;
  Object[] BGMusics;
  //private SpriteRenderer sprite;

  public SpriteRenderer[] sprites;

  public Sprite skinVerde, skinNormal;

  void Start () {

    //skinAtual = Skins.normal;
    skinAtual = Skins.verde;
    //sprite = GetComponent<SpriteRenderer> ();
    player = GetComponent<Rigidbody2D> ();
    BGMusics = Resources.LoadAll ("Music/BG");
    initialX = transform.position.x;

    //skinVerde = Resources.Load<Sprite> ("Sprites/BOYrECORTADOvERDE");
    skinVerde = Resources.Load<Sprite> ("Sprites/PersonagemFatiado_verde");
    skinNormal = Resources.Load<Sprite> ("Sprites/PersonagemFatiado");

  }

  private void UpdateSkin(Sprite novaSprite)
  {
    foreach (var item in sprites) {
      item.sprite = novaSprite;
    }
  }

  void Update ()
  {

    switch (skinAtual) {

    case Skins.normal:
      UpdateSkin (skinNormal);
      break;
    case Skins.verde:
      UpdateSkin (skinVerde);
      break;
    default:
      break;
    }

    if (Input.GetKeyDown (KeyCode.Escape))
      Pause.INSTANCE.Pausing ();

    if (Pause.isPaused)
      return;

    if (Application.isEditor)
      inputComputer ();
    else if(Application.isMobilePlatform)
      inputMobile ();

    FixePosition ();
  }

  void FixePosition()
  {
    if (transform.position.x <= initialX) return;

    var newPX = Mathf.Lerp (transform.position.x, initialX, Time.deltaTime * goBackSpeed);
    transform.position = new Vector3 (newPX, transform.position.y);

  }

  private void inputMobile(){
    if(Input.GetMouseButtonDown(0))
      playerJump ();
  }

  private void inputComputer(){

    if(Input.GetKeyDown(KeyCode.Space))
      playerJump ();
  }

  private void playerJump(){
    if (player.transform.position.y <= -8.93000f )
    {
      player.AddForce (new Vector2 (0, height * jumpForce), ForceMode2D.Impulse);
      MusicManager.INSTANCE.JumpSound ();
    }
  }

  void PlayRandom(){
    int i = Random.Range(0, BGMusics.Length); // index sortido
    AudioClip m = (AudioClip) BGMusics[i]; // uma referencia ao audioclip sortido
    GetComponent<AudioSource>().PlayOneShot(m); // tocamos esse audioclip
  }

  void Reset(){
    GetComponent<AudioSource>().playOnAwake = false; // aqui tira o play on awake do audio source
  }

  // CONFIGURANDO OS TRIGGERS E SUAS ACOES
  void OnTriggerEnter2D(Collider2D col)
  {
    if(col.gameObject.CompareTag("Heart"))
    {
      Score.INSTANCE.AddPoints ();
      col.gameObject.SetActive (false);
      Handheld.Vibrate ();
      //TOCAR
      PlayRandom ();

    }
    else
    {
      if (col.gameObject.tag == "Doctor")
      {
        MusicManager.INSTANCE.DeathSong ();
        player.gameObject.SetActive (false);
        Handheld.Vibrate ();
        ToggleEndMenu();
      }
    }

  }

  void ToggleEndMenu()
  {
    deathMenu.ToggleEndMenu (Score.INSTANCE.GetScore ()); //Send to DeathMenu the Score value
  }
}

```

# Answer
```
private void UpdateSkin(Sprite novaSprite){
foreach (var item in sprites)
    item.sprite = novaSprite;
}

```

The above function uses a for-each loop to assign specific sprites to the `sprites[]` which you defined at the top of type `spriteRenderer`

**Here's what you can do:**

1. Make sure you have assigned SpriteRenderer references properly in the inspector tab.
2. Make sure that

`skinVerde = Resources.Load<Sprite> ("Sprites/PersonagemFatiado_verde");`

`skinNormal = Resources.Load<Sprite> ("Sprites/PersonagemFatiado");`

are actually getting the references for the sprites instead of null. Try assigning those sprites in inspector tab instead of loading like that and see if it works.

**Tip:** Try using print statements to make sure that functions are executing and look out for errors in the editor when pressing the play button, they are a life-saver.
> 1 votes

# Answer
your object should have a `spriteRenderer` Component attached to it in the inspector. just update it using code below:

```
public Sprite mySprite;

this.GetComponent<SpriteRenderer>().sprite = mySprite;

```

my sprite is public so you can see it in inspector. just use second in every event you want to change the sprite of you object
> 0 votes

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


# Question
Title: Friction due to gravity in an impulse based physics engine
In my physics engine, I'm using impulses to solve collisions. I'm basing all calculations on these equations:

```
impulse = desired_velocity_change * mass
impulse = force * time
friction_force <= normal_force * coefficient

```

If an object moves along flat ground (infinite mass), after integration it'll be moving slowly "into" the ground due to gravity. This means that the impulse needed to react to that (given the restitution equals 0) will be the velocity in the direction of the contact normal, multiplied by mass.

The issue here is that gravity is a constant acceleration, which means that the object, no matter the mass, will always "dip" by the same amount given a constant frame rate. So the mass is never a factor in this situation, outside of the impulse calculation, which is just a flat velocity change.

Now, I can use impulse to calculate the force that was needed to react to the collision, this force can then be used in the friction equation as such:

```
friction_impulse / time <= normal_impulse * coefficient / time

```

Since time is always greater than 0, I can just multiply both sides by it, and then I can use the impulse equation, as such:

```
planar_velocity_change * mass <= velocity_change_along_normal * mass * coefficient

```

And again, I can just remove mass from the equation, which leaves me with:

```
planar_velocity_change * mass <= velocity_change_along_normal * mass * coefficient

```

This is the desired velocity change along the contact surface due to friction. The issue is, obviously, that none of this depends on mass, which means that no matter how heavy or light an object is, it'll always continue sliding along the surface by the same amount given a constant initial velocity.

What am I missing? It really looks like there's a logical mistake here. Should the dynamic friction depend on the mass in the first place? Moving a heavy object requires higher force, so static friction should be modeled properly, since it just flat-out removes velocity, though it'd be nice to hear if this has merit or just "looks good".

# Answer
Your pseudo code uses non standard notation (you seem to be using assignment in the `<=` comparison expressions, that is really confusing), which is makes it hard to read, but If I understand the issue correctly, its that there is some confusion with friction.

Friction in real life is caused by microscopic perturbations in the surface of a plane an object is standing on, characterized by a friction coefficient for simplicity sake eg: `u`. The magnitude of the force of friction is this (see wikipedia for an illustration):

```
friction_magnitude = u * magnitude(force_anti_normal_to_friction_plane);

```

A plane can be arbitrarily oriented, not just flat horizontal. But see that we use `force_anti_normal_to_friction_plane` and in your equations, you appear to only care about the acceleration due to gravity, when the force equation is actually `F = M*A`. The mass is accounted for in the force of friction. In this way your friction magnitude assuming gravity is the only force normal to the plane of friction should be:

```
friction_magnitude = u * magnitude(G * mass);

```

You then take this and multiply it with the part of the velocity parallel to the plane of friction, for a horizontal plane this is just your non vertical components (in my system this is normally x, and z) normalized.

```
friction_force = -u * magnitude(G * mass) * normalize(vec3(velocity.x, 0.0, velocity.z));

```

In the case where you have an arbitrarily oriented friction plane it is the rejection of the velocity vector with the normal of the plane which contains the components which to normalize, and the projection of the force to figure out what components of the force actually apply to the plane of friction. This rejection contains the orthogonal vector to the normal of the plane, which contains the parallel velocity component to the plane, the projection contains the components parallel to the the given vector.

```
// need to guarantee that the forces are at least pointing towards the plane
// and not away, if forces do not point towards plane, then there is no
// force anti normal to the plane of friction pressing down to cause contact

if(dot(forces,friction_normal) < 0.0){
    force_anti_normal_to_friction_plane = projection(force, friction_normal);
}else{
    force_anti_normal_to_friction_plane = 0.0;
}

friction_force = -u * magnitude(force_anti_normal_to_friction_plane) * normalize(reject(velocity, friction_normal));

```

Another thing you need to watch out with dynamic friction is that you don't want to apply it past when the object would have stopped moving in the parallel velocity to the plane. Ie if you have a very tiny vector moving across the floor of your friction plane, friction doesn't scale less because of that, and doing a naive calculation would cause your velocity vector to move back and forth forever across the plane. You need to halt your movement along that vector to adequately handle this case. In otherwords, if the magnitude of your velocity along the plane of friction is less than the magnitude of velocity change contributed soley by the force of friction *you need to stop moving!*. To do this for arbitrary orientations of the friction plane, take the velocity components rejected by the normal and subtract them from the velocity to cancel out that movement.
> 0 votes

---
Tags: physics, physics-engine
---


# Question
Title: How to make Sprites scroll with the background image that are inside Scroll View?
I'm new in Unity, so I hope you guys can help. I'm developing a 2D-game for Android device, on the scene I have a huge background image inside Scroll View (UI - Scroll View).

Next, I created new empty Game Object "Players", attached to it "Players script" and added "Sprite Renderer" component.

From the Sprites I created two prefabs - housePrefab and dogPrefab. Inside "Players script" I have the following code:

```
[SerializeField] GameObject housePrefab;
[SerializeField] GameObject dogPrefab;

void Start()
{
var houseXPos = 1.41f;
var houseYPos = 2.63f;

var dogXPos = -0.41f;
var dogYPos = 2.63f;

GameObject house = Instantiate(housePrefab, transform.position = new Vector2(houseXPos, houseYPos), Quaternion.identity) as GameObject;
GameObject dog = Instantiate(dogPrefab, transform.position = new Vector2(dogXPos, dogYPos), Quaternion.identity) as GameObject;
}

```

After I run game both Sprites appears on the screen (as I expected). The problem occurs when I Scroll background image, both sprites stay in the same position under scrolling. In other words sprites not scrolling with the background image.

As far as I understand, the Sprites needs to be added to the background image, but I don’t know how to do it. How to make Sprites scroll with the background image?

Thanks to all in advance.

# Answer
Your background is a UI canvas, but your playing objects are in the scene and not dependent. Your approach is wrong.

If you need a background for you game, just make a simple 2D object with SpriteRenderer and scale it to fill the camera view. Then make it child of the camera (drag in hierarchi and drop on camera).

Then you can define any behaviour for your characters.
> 1 votes

---
Tags: unity, c#, sprites, scrolling
---


# Question
Title: How can I adjust the speed my character jumps at?
I've applied this method How to make a character jump?, like:

```
  let wallForce = 0;
  const targetVx = -gravity * 4.0;
  const updatePos = delta => {
    const dt = delta * 0.01;

    const oldY = hero.y;

    hero.vy += wallForce * dt;
    hero.vy += gravity * dt;

    hero.x += hero.vx * dt;
    hero.y += hero.vy * dt;

    updateCollisionsBetween(oldY, hero.y);

    hero.vx += (targetVx - hero.vx) * dt;

    wallForce = 0;
  };

```

and on jump:

```
  let doubleJump = 0;
  const jump = delta => {
    wallForce = 0;
    hero.vy = -hero.jumpVy;
    if (doubleJump === 1) {
      hero.vx *= 2;
    }
  };

```

I want to speed up the jumps, that is I want the hero to jump and land faster. If I give a higher negative velocity on the jump (eg. `hero.vy = -hero.jumpVy * 2.0`), then the hero jumps higher but its speed doesn't change.

# Answer
You have to scale both the `jumpVy` and the `gravity`.

Explanation: `jumpVy` is the (upward) velocity of your character. If we never decrease this your character will fly away. Ok, so we decrease the velocity by using the `gravity` which pulls your character back to ground. Each iteration the upward velocity gets reduced by the `gravity` until it gets a downward velocity and your character start falling down. This is where your character is the highest (jump height). If you want to keep this point while increasing the speed you need to scale both forces. As your character is faster in his upward motion you need to slow him even further to get to the same point, your gravity value must be scaled by a bigger amount than the jump value.

Note: If your `jumpVy` and `gravity` have big values and your dt is high as well this might not work properly as the movement will be too fast or choppy, if this happens increase your sampling rate e.g. reduce the time between updating the positions and velocities.

You can find the working JSFiddle that is based on the post you linked here: http://jsfiddle.net/9opz3d0b/3/

I added a little red dot to show the highest point of the last jump.

Try this out and than change the `scaleVY` and `scaleGravity` back to 1.0 to see the difference.

Fast jump:

```
var scaleVY = 6.0;
var scaleGrav= 28.0;

```

Slow jump:

```
var scaleVY = 1.0;
var scaleGrav= 1.0;

```
> 1 votes

# Answer
I think its due the gravity. you are changing the value of jump but the gravity remain the same so impact of the gravity on both case is same so i suggest increase the value of the jump and reduce the value of gravity it would do the trick.
> 0 votes

---
Tags: physics, javascript
---


# Question
Title: Calculating approximations of contact between two meshes
I'm looking for ways to calculate the degree of contact between two objects in a scene. I was thinking that calculating the hausdorff distance would be a useful approximation if it is then normalized somehow using the surface area/volume of the objects. Does anyone have any experience calculating this in Unity? Or have any suggestions for other ways to approximate this?

Edit: For some context, I'm working on a project which involves looking at the relationship between geometric properties and relations of objects, and what language/words people use to describe objects and I am using scenes in unity to test this. The notion of 'contact' appears to be an important one and it would be useful to be able to quantify the amount of contact between two objects in a scene

# Answer
Initially I thought iterating over all vertices in a mesh would be too computationally expensive to do for each pair of objects but it turns out not to be, especially since my meshes are relatively simple.

To calculate the proportion of contact between two gameobjects, `e1` and `e2`, I iterate through all vertices, `v1`, in the instantiated mesh of `e1` and find the closest point on the mesh collider of `e2`: `v2= e2.meshColl.ClosestPoint(v1)`. If the distance from `v1` to `v2` is under some threshold distance (`0.01f` appears to be the default in unity), then the vertex `v1` is deemed to be in contact with the object `e2`. The proportion of contact between `e1` and `e2` is the number of vertices of `e1` in contact with `e2` divided by the total number of vertices in `e1`. Note that this is not a symmetric measure i.e. in general `contact(e1,e2) != contact(e2,e1)`
> 0 votes

# Answer
I don't think Hausdorff distance is an appropriate measure of "contact".

Imagine we have two objects, finite in extent, touching at one point, with neither fully enclosed by the other. I can increase the Hausdorff distance to be arbitrarily great by taking part of one object's surface on the far side from the contact point, and extruding it into a spike or tendril that escapes to a great distance from the other object. I haven't changed the nature of the contact, I've just changed the shape of a part of the object nowhere near the contact, and yet I've completely distorted the measure.

So I think what you want is something more like the closest distance / penetration distance, or a measure of the volume of space sandwiched "between" the objects.

---

If your objects are, or can be well approximated by, collision primitives, then you may be able to use the physics engine to estimate the smallest distance between them:

* If a collider of one object intersects a collider of the other, Physics.ComputePenetration will tell you how deeply it penetrates (ie. what is the minimal translation vector we'd need to apply to separate them?)
* If none of the first object's colliders intersect any of the other's, then you can use Physics.ClosestPoint to find the closest separations between them. If your shapes are convex, then it suffices to find the closest point on each collider to the center of each of the other object's colliders, then finding the closest point on the other object's collider to *that* point. If your shapes can be concave, then you may be forced to scatter sampling points along the surface of the concave shape and try to find closest points to those samples.

---

Another strategy you may be able to use if your contacts are "plane-ish" (ie. not wrapped around, like entwined chain links) is to use the rendering system to convert the 3D space to a raster image you can more easily analyze.

* First, identify the approximate axis of approach - this might be as simple as a line drawn through each object's centres, or determined using crude collider approximations as above.
* Position an orthographic camera so that it looks along this axis, scaled so at least one of the objects just fills its view (it's OK if the other extends out of frame - since we're looking for contacts, we only need the pixels that overlap both objects)
* Render the further object's front faces, with depth-testing set to "less", drawing the depth of each rendered pixel to one render target.
* Render the nearer object's back faces, with depth-testing set to "greater", drawing the depth of each rendered pixel to a second render target.
* Subtract one render target from the other: this is the depth of separation between the objects at this point, along your chosen axis. It will be negative where the objects intersect (a penetration depth).

Now you can apply any image analysis technique you can imagine to this separation depth map. You could look for its local minima (near-contact points or deepest intersections). You could sum areas of pixels to compute the volume of space in the sandwich. You could form a histogram of separation distances to categorize things that approach at only a few points vs objects that stay closely parallel/lapped over a large area...
> 1 votes

---
Tags: geometry, mesh
---


title: What is a "Projectile"?

text:
# Question
Title: What is a "Projectile"?
I don't know what a Projectile os.

I'm not sure whether a Projectile is a spawn point which spawn a number of object or a number of multiple objects.

I'm referring to this website.

How do I use Projectiles and what does it mean?

# Answer
> 5 votes
From dictionary.com:

> projectile\[ pruh-jek-til, -tahyl \]
>
> noun
>
> 1. an object fired from a gun with an explosive propelling charge, such as a bullet, shell, rocket, or grenade.
> 2. a body projected or impelled forward, as through the air.

In the context of game development, it's usually a small game object which is spawned by another object, moves in a predictable path (often but not always a straight line), is destroyed if it collides with a solid object and causes damage if that other object is an opponent of the object which spawned the projectile. Common examples are bullets, arrows, rockets or fireballs.

Projectiles in a 2d game (Enter the Gungeon):

Projectiles in a 3d game (Overwatch):

---
Tags: unity, terminology, projectile-physics
---


# Question
Title: Can polishing the GUI be ever considered a part of making the MVP?
I've read and watched about the MVP:

I'm trying to apply this concept to the menu-based combat game I'm trying to make as a hobby project.

This is a little bit tricky because when I started the project I did not know about MVP. As a result, I first cut my original idea significantly down to what I considered the minimum release-worthy version of my game; so that I could, in the future, release my game and then iterate on this first release. This, obviously, was far more than what would be considered MVP. Out of necessity (the game started as a project for a Uni class) I first focused on coding the stuff so that I could show my code to my Prof.

The result is that I now have a large, working though bug-ridden and unplayable mess of a game that I'd now like to try to slowly bring to playability. In order to achieve this I'm finally trying to cut the game to MVP and only work on these parts of the game that form the MVP, ignoring the other parts; then iterate on this, until I hopefully finally bring order to everything I made earlier. (I even commented out lots of code that is not responsible for the MVP-ish parts of the game.)

Unfortunately, it has proven difficult for me to determine which parts of this game form MVP.

One such difficult case is the GUI. As far as I understand, GUI is only part of MVP insofar as absolutely necessary to allow me - the dev - to interact with the game. So monsters are to be represented as uncolored squares etc.

But the problem is also, as far as I understand, I should keep polishing the MVP until it seems fun and only then add any content. But I now think that polishing the GUI a little bit more is a prerequisite of this.

Example 1: In the spirit of the MVP, I do not have health bars now. Instead, I have bare numbers on top of the empty space where the monster's sprite is supposed to be placed in the future. However, I find it not very readable to have a monster's HP represented as 3649/6000. A bar filled to around 60% of its maximum length would be far more readable IMO.

Example 2: The status console. Originally, since I only focused on writing more code, the console was a mess. Status messages were often in a counter-intuitive order, were poorly broken into paragraphs, etc. I found that this itself was making it annoying for me to interact with the game. So I started working to fix the console, and I think I fixed it *somewhat*, but enough to make me satisfied. I would now like to continue working on fixing the console.

Both examples show why I have feeling that polishing the GUI beyond what would be considered MVP is a prerequisite of making the correct MVP. I don't know, maybe it's a peculiarity of menu-based combat games: the menus themselves are at the very core of the game so they should be usable and information from the game should be displayed in a clear way that makes it easy to comprehend what is going on?

Am I correct that stuff like adding health bars instead of bare numbers and breaking the status messages into paragraphs correctly, displaying some of them in a smaller font, adding sleeps between more important messages can be considered a part of making the MVP? Or am I misunderstanding the concept of the MVP?

# Answer
Remember, these terms we throw around like MVP, agile, ECS, vertical slice, etc. are not absolute laws of the universe. They're just ideas that some folks have found helpful to their process.

Where they help you make progress, use them. Where they hurt your progress, bend them.

No MVP police will arrest you if you use a health bar. Steam will not ban you from selling your game if you put line breaks in your console earlier than you were "supposed" to. Your computer won't collapse into a black hole.

The only real consequence of how you interpret "MVP" is what it does to your development timeline.

So, look at your schedule:

* When do you want to have your complete, playable version? What absolutely has to happen for you to get there?
* Are you on track to meet that goal based on your velocity so far?

Did the time you spend improving the console so far threaten your deadline? Or did it help, by making it clearer to read what's going on, so your testing is more efficient now?
* What pain points do you still have, and how do they rank in priority order against the other features you still need to finish for your target MVP milestone date?

Once you've evaluated this, you can triage the remaining work items based on the value they add versus their cost/risk.

By managing your prioritized backlog of work, and re-evaluating periodically as you get further along, you can make sure you stay on target to deliver something playable for your MVP milestone date - maybe even with some niceties included as a bonus to make the next phase smoother.

Remember too that the focus is on "viable" - we want to find the minimal route to a playable result, not minimalism for minimalism's own sake.

If the current interface is too hard to read for you to clearly understand what's happening, then is it really "viable"? Will you be able to play the result and accurately evaluate whether it will support your target experience, and plan your next steps accordingly? Or are the rough edges too painful/distracting to get a good read, forcing you to risk more work on an unproven concept?

That's a judgement call you need to make based on the needs of your particular game, not a textbook definition for others to adjudicate for you. There are lots of different philosophies about how much depth and niceties are "enough" to prototype a feature - see Lee Perry's "Pizzazz First, Polish Later" microtalk, about 5:20 into this video. There, he argues that we should separate the notion of "good player feedback" from the notion of "polish," arguing the former is actually part of the core of the feature we need to be able to evaluate the feel and experience, not a coat of paint to add at the end. That doesn't mean we put the MVP on hold until we have final assets for everything, but it does mean putting in a quick & dirty placeholder effect isn't necessarily breaking the MVP "rule."

At the end of the day, it's your game, your production timeline, your risk to manage.

If you're answering to a publisher, backers, or prof, can you be accountable to them and say "this work is helping achieve our agreed-upon milestone goals"? If you feel you can't, maybe that's a work item to put into the longer-term backlog, and come back to later.
> 10 votes

# Answer
**TL;DR:** The idea behind creating an MVP is less about the precise definition of an MVP and more the general principles of:

* Not starting to polish until you have something you can actually play
* Not doing too much polishing (in the beginning and altogether)
* Not adding a bunch of features before having something playable

---

You start off creating the smallest thing that is actually playable. This would have no polish.

Then you polish this until it "works":

* Part of this is getting rid of bugs.
* But some polishing also makes sense here to have it be *functionally* fun: the core controls are smooth, you can see what's going on, etc. (but not that it looks "pretty")

If you consider a platformer as an example: you start off moving your character around in an empty room and tweak this until it feels smooth and only add elements after this. If the player's "core" controls aren't smooth and you want to change them late into development, you may also need to change how abilities that affect movement work, how different types of floors interact with movement, how enemies move and attack, what some levels look like so they're not too hard or easy, etc. Of course you may need to do these things anyway when you adding features, but you don't *also* want to do it for something you could've addressed a lot earlier.

Also, and perhaps more importantly, you may realise your vision just wouldn't make for a fun game, and you either need to rethink parts of your game (or your entire game) or just scrap them altogether.

You shouldn't spend *too* much time polishing though:

* Polishing too much can come at the cost of making "real" progress on your game, i.e. adding features and content and actually releasing your game.
* Things you add later may require you to make significant changes to what you've already done and scrap large parts of the polishing you've done so far.

At this point you get into a cycle of adding the most important next feature or piece of content, getting rid of bugs, doing some polishing and repeating.

After this, or somewhere in the middle of this, you start doing the "final" polishing, where you make things look "pretty". You shouldn't do this at the start.

**Whether you consider an MVP to be the part before or after the initial polish shouldn't really matter.**

---

For your example, I imagine having a "clean" UI would be a pretty important factor in whether it's functionally fun (as defined above), so you should definitely be polishing that a bit.

This includes how you display health. If you want a bar, I might recommend simple ASCII `-`'s, where each `-` represents 10%, or something like that. Of course it depends how much effort different options would be for you and what would fit in your UI.

I would start with extremely basic status messages that probably aren't even complete sentences, so if you're considering adding paragraphs, these may be too complex for an MVP (but it depends on what they actually say). Making sure you're able to actually read the messages would be important though, so adding delays between messages might make sense.
> 6 votes

# Answer
If your game is very UI-centric, then reading and navigating the UI can actually be the core mechanic of the game which you need to demonstrate in your MVP.

But it seems to me like you are already beyond the MVP phase and entered the prototyping phase. The purpose of an MVP is to get a playable game running so you can iterate on its design. But it seems to me like you already did that, discovered essential problems in your design (like UI which is so bad that it distracts from the game experience) and started to iterate on them.

Just make sure that you prioritize issues correctly.

Is the UI really the worst problem right now? Does the bad UI prevent you from playtesting your game mechanics because even *you* can't tell what's going on in the game? If so, fix the UI! But is the UI already able to give you the information you need? Are the problems with the UI largely cosmetic? Then you should focus on aspects which are more relevant to the game mechanics right now.
> 2 votes

---
Tags: game-design, terminology, project-management, pre-production
---


# Question
Title: Is there a name for turn based combat that uses a speed attribute like ATBs but doesn't involve waiting?
I've seen this in a number of games now - for me, I think the first (and one of the better examples) was Blue Dragon - where characters take turns in an order determined by their speed attribute such that a fast character will not only go first, but also take turns more often than a slow character. This is much like an ATB (Active Time battle) (with Wait=true) BUT the turns still take place immediately after one another (as opposed to each character having a time-bar that runs down in real time). And in the example of Blue Dragon, a number of tokens appear in a queue to indicate probable turn order (this would fluctuate if a character used a quicker or slower than normal action).

Is there a name for this turn-based-with-time-simulation-combat in games?

Edit: The closest I've come to a satisfactory term for this is a Combatant Cooldown System (https://tvtropes.org/pmwiki/pmwiki.php/Main/CombatantCooldownSystem) with a Visual Initiative Queue (https://tvtropes.org/pmwiki/pmwiki.php/Main/VisualInitiativeQueue) I like these but both came from *TV Tropes* and don't appear to be (commonly) in use elsewhere...

# Answer
I don’t believe there is a commonly-recognized term for what you’re talking about; it falls under the general category of “turn-based” but beyond that hasn’t really reached the point where it’s needed to acquire a unique moniker of its own.
> 1 votes

---
Tags: terminology, combat
---


title: Unity C# Array Scripting!

text:
# Question
Title: Unity C# Array Scripting!
I was just trying and make a simple 2D game. I have a simple circle sprite (red, green and blue). These circles fly upwards with my scripting as shown below:-

```
public class Direction : MonoBehaviour {
    public GameObject[] ballons;
    public float increase;
    public float timeInterval;
    public float timeForGetGo;
    public float increaseInterval;

    public float startTime;
    public float timeForNextSpawn;
    public Transform instantiatePos;
    void Start () {;
        StartCoroutine (direction ());

    }

    void Update () {
        increase += increaseInterval;
        direction ();
        Instantiater ();
    }

    IEnumerator direction (){
        while (true){
            foreach (GameObject gameObjects in ballons) {
                gameObjects.transform.position = new Vector3 (gameObjects.transform.position.x, gameObjects.transform.position.y + increase, 0f);
                yield return new WaitForSeconds (timeInterval);

                }
                }

```

So, instead of making them fly with one script by one script, which I normally do, I tried to make array of these gameObjects and make them go upwards. `**`It worked great!`**` But, I have a problem. I want these upward going circle to instantiate but when I instantiate them, they won't go upwards as they aren't in the list of arrays I put earlier as in:-

```
public GameObject[] ballons;

```

in first line in that script.

So, as in conclusion, my problem is the instantiated objects won't have same property coz the script is attached to another gameobject and not in the original gamobject itself. Any ideas?

# Answer
Your method of iterating over these objects looks very confused.

```
IEnumerator direction (){
    while (true){
        foreach (GameObject gameObjects in ballons) {
            gameObjects.transform.position = new Vector3 (gameObjects.transform.position.x, gameObjects.transform.position.y + increase, 0f);
            yield return new WaitForSeconds (timeInterval);
        }
    }
}

```

This says:

* take only the first balloon
* raise it by `increase` (where the size of `increase` grows proportionate to the number of frames your script has been active)
* wait for `timeInterval` seconds
* then, after you're done waiting, take only the second balloon...

(Also, you start one copy of this coroutine going in Start, then run a new copy for only one cycle — affecting only the first balloon — each frame in Update, in addition to the one that's running in the background)

That doesn't sound like what you really want.

I think you can do this more cleanly by attaching the rising behaviour to your balloon:

```
public class Balloon : MonoBehaviour {
    public Vector3 velocity;
    public Vector3 acceleration;

    void Update() {
        velocity += acceleration * Time.deltaTime;
        transform.Translate(velocity * Time.deltaTime, Space.World);
    }
}

```

This way your balloons handle their own animation and accumulation of speed over their lifetime, and your spawner can concern itself purely with when to spawn what:

```
public class BalloonSpawner : MonoBehaviour {
    // Create a prefab of your balloon and assign it in the Inspector.
    public Balloon balloonPrefab;

    public float spawnInterval;

    IEnumerator Start() {
         var delay = new WaitForSeconds(spawnInterval);
         while(true) {
              Instantiate(balloonPrefab, transform.position, Quaternion.identity);
              yield return delay;
         }
    }
}

```

But if you really prefer to have the spawner handle their movement, and have all objects accelerate together according to its lifetime, I'd recommend separating it from your coroutine and doing it in update for smoother motion:

```
public class RisingSpawner : MonoBehaviour {
    // Create a prefab of your balloon and assign it in the Inspector.
    public Transform spawnPrefab;

    public float spawnInterval;
    public Vector3 initialVelocity;
    public Vector3 acceleration;

    float _lifetime;
    List<Transform> _spawned = new List<Transform>();

    IEnumerator Start() {
         var delay = new WaitForSeconds(spawnInterval);
         while(true) {
              Instantiate(spawnPrefab, transform.position, Quaternion.identity);
              yield return delay;
         }
    }

    void Update() {
        // Purge any destroyed instances from our list before we iterate it.
        _spawned.RemoveAll(item => item == null);

        _lifetime += Time.deltaTime;
        var velocity = initialVelocity + acceleration * _lifetime;

        var shift = velocity * Time.deltaTime;

        foreach(var instance in _spawned) {
             instance.Translate(shift, Space.World);
        }
    }
}

```
> 1 votes

# Answer
You need to add instantiated objects to that array, and since one does not simply stretch or shrink an array, use `List<GameObject>` instead.

You can then write where you instantiate an object: `direction.ballons.Add (instantiatedObject);`

For this, you should have a reference to `Direction` class instance that controls balls' movement.
> 0 votes

---
Tags: unity
---


# Question
Title: Prevent oversteering catastrophe in racing games
When playing GTA III on Android I noticed something that has been annoying me in almost every racing game I've played (maybe except Mario Kart): Driving straight ahead is easy, but curves are really hard. When I switch lanes or pass somebody, the car starts swiveling back and forth, and any attempt to correct it makes it only worse. The only thing I can do is to hit the brakes. I think this is some kind of oversteering.

What makes it so irritating is that it never happens to me in real life (thank god :-)), so 90% of the games with vehicles inside feel unreal to me (despite probably having really good physics engines). I've talked to a couple of people about this, and it seems either you 'get' racing games, or you don't. With a lot of practice, I did manage to get semi-good at some games (e.g. from the Need for Speed series), by driving very cautiously, braking a lot (and usually getting a cramp in my fingers).

What can you do as a game developer to prevent the oversteering resonance catastrophe, and make driving feel right? (For a casual racing game, that doesn't strive for 100% realistic physics)

I also wonder what games like Super Mario Kart exactly do differently so that they don't have so much oversteering?

I guess one problem is that if you play with a keyboard or a touchscreen (but not wheels and pedals), you only have digital input: gas pressed or not, steering left/right or not, and it's much harder to steer appropriately for a given speed. The other thing is that you probably don't have a good sense of speed, and drive much faster than you would (safely) in reality. From the top of my head, one solution might be to vary the steering response with speed.

# Answer
> 7 votes
One solution would be to cheat a bit and guess what the player wants to do. When the player is on a straight section and presses left, you can assume that he wants to switch lanes. When he is close to a curve or intersection, he certainly wants to turn. The player is unable to control it's exact steering angle in a curve, so you could decide to give the player the benefit of doubt and always let him drive through curves in the ideal angle when he presses the turn button at the right moment (as long as physically possible - any player who tries to drive with through a hairpin curve with 200 km/h deserves to be punished by a short flight over the grass).

This, of course, could get tricky when the player actually wants to turn around on a straight section or actually wants to switch lanes just before an intersection.

Another solution would be to have a difference between tapping a key and holding a key. The longer the player holds the turn key, the higher the turning angle. This doesn't even feel unrealistic, because when you have a steering wheel, you need time to turn it all the way.

**Edit:** On a touchscreen, you could use sliders instead of buttons for controlling steering and speed in an analog way. When the screen is pressure-sensitive, you could also interprete the pressure (but give visual feedback on maximum pressure, or overzealous players might break their displays). When the device has orientation sensors, you could use device tilting to control steering.

# Answer
> 0 votes
I came across this (old) question while researching what other games than Grand Theft Auto IV and V have implemented, but I have a decent answer to achieve controllable oversteer. I only have some experience messing around with the driving model in Grand Theft Auto V, but this information should be applicable to most somewhat realistic driving models.

What seems to happen in most driving games, is that the car steering output is directly linked to player input - even if some sort of (temporal) smoothing is used. This causes a sluggish feeling or a jerky feeling - and the car does not correct itself after letting go of the controls. This is in contrast to a real car, where the car tends to center itself after releasing force on the wheel. Some games try to correct this by changing their handling model or having arcade handling models.

What can be observed in Grand Theft Auto V, is that user steering input is not directly linked to steering output. The vehicle steers by itself, towards its current velocity vector. This is visible when forcing a slight oversteer situation and observing the steered wheels - without any input, they countersteer by themselves. Any user input is then added on top of these "natural" corrections.

A downside to this approach however, is the car feeling too sticky and somewhat stubborn to get into a powerslide or drift - so this countersteer value can be limited to some angle.

This theory can be verified by re-implementing the steering system and comparing it with the original behavior.

* When linking input to output directly, the vehicle is indeed extremely hard to control, even when having applied the speed-based steering input limiter.
* When adding in the natural countersteer, the behavior is nearly identical to the games' implementation, but cars are "too" stable.
* When adding in a 15 degree limit to countersteer, the behavior is almost identical.

A thing to keep in mind is that Grand Theft Auto V was taken as "ideal" here - though I have yet to find any other game that implements this system.

If you're curious for some code, here's a snippet of my implementation.

```
// Returns in radians
float Racer_calculateDesiredHeading(float steeringMax, float desiredHeading,
    float reduction) {
    desiredHeading *= reduction;
    float correction = desiredHeading;

    // Get the relative velocity vector
    Vector3 speedVector = ENTITY::GET_ENTITY_SPEED_VECTOR(vehicle, true);
    if (abs(speedVector.y) > 3.0f) {
        // Simplify it to an angle
        Vector3 target = Normalize(speedVector);
        float travelDir = atan2(target.y, target.x) - static_cast<float>(M_PI) / 2.0f;
        if (travelDir > static_cast<float>(M_PI) / 2.0f) {
            travelDir -= static_cast<float>(M_PI);
        }
        if (travelDir < -static_cast<float>(M_PI) / 2.0f) {
            travelDir += static_cast<float>(M_PI);
        }
        // Correct for reverse
        travelDir *= sgn(speedVector.y);

        // Limit to some degree, R* uses 15 degrees
        travelDir = std::clamp(travelDir, deg2rad(-15.0f), deg2rad(15.0f));

        // User input deviation
        correction = travelDir + desiredHeading;
    }

    return std::clamp(correction, -steeringMax, steeringMax);
}

```

---
Tags: racing, steering-behaviors
---


title: How do I get the full path of Content?

text:
# Question
Title: How do I get the full path of Content?
To display an image from Content in a .NET Forms Dialog, I'm trying to make a function that loads an image through .NET's `Image.FromFile(string fileName)` function, but instead of taking a whole path, it takes the path you'd usually put in `Content.Load<T>(string assetName)`.

For this, I need to be able to get the complete root directory of the Content folder, but how do I get that?

I've already tried `Content.RootDirectory`, but that seems to give only a relative file path (in my case, it just says "Content" because I left it at default)

Thanks in advance!

# Answer
There's a few things you need to understand to get this to work.

First, what you're trying to do will be platform specific. So I'm going to assume you're only concerned with getting it working on Windows.

Second, if you're adding content to the `Content.mgcb` file it will be compiled by MonoGame's Content Pipeline and it will end up in a `Content` folder as an XNB file relative to the executable.

For example, let's say you've added a `texture.png` file to your `Content.mgcb` file. When the game or tool runs the image will be compiled and end up in the following place by default.

```
 - Game.exe
 - Content
     - texture.xnb

```

This means that the path relative to your executable would be `Content\texture.xnb` and you could use the regular C# method `Path.GetFullPath("Content\texture.xnb")` to get the full path relative to the executable.

Of course, you won't be able to load an XNB file with `Image.FromFile(string fileName)` because it's not a standard image format. To deal with that what you'll probably want to do is copy the original `texture.png` file to the output folder.

To do that you can use the Properties of the file and set the *Build Action* to **Content** and the *Copy to Output Directory* to **Copy if newer**.

Now the `texture.png` file will be available to load relative to the executable.

```
 - Game.exe
 - Content
     - texture.png

```

Lastly, if you want to actually load this PNG file directly into MonoGame *without* using the `Content.Load` method you can write you're own method using `Texture2D.FromStream` like this:

```
public Texture2D LoadTexture(string filePath)
{
    using (var fileStream = File.OpenRead(filePath))
    {
        var newTexture = Texture2D.FromStream(GraphicsDevice, fileStream);
        PremultiplyTexture(newTexture);
        return newTexture;
    }
}

private static void PremultiplyTexture(Texture2D texture)
{
    var data = new Color[texture.Width * texture.Height];

    texture.GetData(data);

    for (var i = 0; i < data.Length; i++)
        data[i] = Color.FromNonPremultiplied(data[i].R, data[i].G, data[i].B, data[i].A);

    texture.SetData(data);
}

```

Note: I've also included a method to pre-multiply the texture because this is something normally done by the MonoGame Content Pipeline. If you don't do this the texture won't work properly with `AlphaBlend` mode.
> 3 votes

# Answer
Use `Application.dataPath` to get the folder of your game, the concatenate the string with "Assets\Resources" or wherever your pictures may be.

https://docs.unity3d.com/ScriptReference/Application-dataPath.html
> 1 votes

# Answer
```
string contentPath = System.Forms.Application.StartupPath + "\\" + Content.RootDirectory;

```

Did the trick for me. Unfortunately, the files it'll give you are in a `.xnb` format, making it impossible to pass on to the image of a Windows Form.
> 1 votes

---
Tags: c#, monogame
---


# Question
Title: How to duplicate Blender glow and reflection effects in Unity?
I am trying to make my game more interesting by making a background with this NEON tunnel made of glowing lines.

Since I am not a good 3D artist, I choose to hire some freelancers, and they made a model that looks great in Blender. I have all that I need...but when I import my object into Unity, it does not have any effects, any colors, any glow or any "mirror" reflection.

The biggest problem is that I cannot find any other freelancer who actually knows how to fix this problem.

This is how it shows up in Blender when my freelancers made it, and it looks perfect:

I want to have the same effects, same look, same colors, same glow in my Unity project, but I don't know how to actually import this object and reproduce that same look.

This is all zip folder which contain pictures, object in blender file, same object in .fbx,.obj.mtl and in many more formats.. but seems like any of those models doesn't work in Unity because I bet Unity needs more modifications...

I hope someone will help me step by step to achieve my goal.

# Answer
> 1 votes
1. For mirror like ground create a material with standard Shader make the metallic value to 1 and smoothness to 0.5 and attach it to the ground which will make object like a mirror.
2. Now for the glowing objects create another material with standard Shader and then enable emission for material and then attach material to the model. for more info please follow the Video.
3. For Glow use post processing stack. Please follow this tutorial for how to use post processing stack.

I hope this will help.

---
Tags: unity, 3d, blender, reflection-rendering, glow
---


# Question
Title: Storing transformations in game objects. (GLM, C++)
I'm currently writing a game engine from scratch for learning purposes. I just started implementing transformations. I know how they work in general but I'm not sure how to implement them efficiently in hierarchical structure.

Should I keep each transformation separate or keep them bundled in a transformation matrix? I have a feeling a single matrix would be way more efficient than calculating model transformation matrix each frame for each object in component tree. On the other side, I'd like to access position, rotation and scale individually as I plan on using them later for some other optimizations.

I'm aware of `glm::decompose` but I'm not sure if it's a good idea to call it every frame.

Should I keep both the matrix and the components, decompose the matrix every frame or calculate it every frame?

# Answer
> 4 votes
My general recommendation is to keep both the source components of your transformation for ease of manipulation:

* local translation vector
* local orientation quaternion
* local axis-aligned scale triplet, or uniform scale scalar

**And** the resulting object-to-world matrix (factoring in the transformations of the parent hierarchy too).

Keeping these separate gives you the best of both worlds:

* Scripts that need to modify just a rotation or just a scale can act on those properties directly, without decoding and re-encoding them into the matrix on every use.
* Your rendering (and perhaps physics) systems have access to pre-concatenated object-to-world matrices exactly as they need, and don't need to take responsibility for building them on the fly.

You can even keep these two views of the transformation in separate components/buffers for cache utilization, if your code often works with just one or the other at a time.

You can use a dirty flag to avoid redundant re-computation of the complete matrix for objects that stay stationary for the frame. (Or a dirty list, to avoid iterating your whole collection with random-ish branching along the way) This also saves you re-computing the whole matrix for each intermediate step when an object's local properties are modified by several effects in a single frame - instead you "bake in" the combined effects lazily, the next time the matrix is needed.

A major benefit of separating out the source values is controlling the accumulation of errors. By storing these components separately, they remain pristine - repeated rotation won't "leak" rounding errors into deviations of your scale parameter for example - and you can more easily maintain invariants like orthogonality (something you get by construction when storing the rotation as a quaternion rather than a matrix).

Your hierarchy can be expressed as simply as a parent id / index - keeping the transforms sorted by this index can let you update a whole hierarchy in a single linear pass.

---
Tags: c++, quaternion, gameobject, glm
---


title: Additive Blending and Gamma Correction

text:
# Question
Title: Additive Blending and Gamma Correction
Should one do additive blending (aka lightmapping) in linear space?

I tried doing it in linear space, and it became, well, linear and bland, losing that cool HDR-style bloomy effect. Is there some standard way to do additive blending in linear RGB, or additive blending is now an obsolete gamma space hack and people should forget about it?

# Answer
> 0 votes
If you want to reproduce the type of additive blending you'd see in a photo editing app like Photoshop, you probably want to have both the source and the destination in a gamma-corrected color space such as sRGB. If you want to reproduce how light actually works, you should leave your colors in linear RGB.

When photo editing apps first implemented blend modes, they were done in a gamma-corrected color space. Doing an add of 2 colors in such a space (especially in 8-bits per channel) would cause a lot of clipping of colors. Because of this, there were blend modes that achieved some of the desired light-like effects in the gamma-corrected space. For example, the "screen" blend mode in gamma-corrected space looks a lot like an "add" blend mode in linear space.

Fast-forward 20 years and these apps started adding linear RGB as an option for editing and suddenly all the blend modes look "weird" (at least to users who had been doing gamma-corrected blending for the last 20 years). So some applications do a gamma correction before doing blending, and then convert the result back to linear afterwards. So if that's working for you, it's an absolutely fine way to do it. You wouldn't be the first!

See for example, this book:

> Artists have dealt with the problems of working directly in video space \[i.e. gamma-corrected space\] for years without even knowing. A perfect example is the Screen transfer mode, which is additive in nature but whose calculations are clearly convoluted when compared with the pure Add transfer mode. Screen uses a multiply-toward-white function with the advantage of avoiding the clipping associated with Add. But Add's reputation comes from its application in bright video-space images. Screen was invented only to help people be productive when working in video space, without overbrights; Screen darkens overbrights (Figures 11.11a, b, and c). Real light doesn't Screen, it Adds. Add is the new Screen, Multiply is the new Hard Light, and many other Blending modes become evident as mere kludges in linear floating point

---
Tags: graphics-programming, blending, alpha-blending, srgb
---


# Question
Title: Interpolation of render with fixed physics update
In Fix Your Timestep, they briefly address the remainder time in relation to rendering. Saying that remainder can be used to generate an interpolated rendering.

> We can use this remainder value to get a blending factor between the previous and current physics state simply by dividing by dt. This gives an alpha value in the range \[0,1\] which is used to perform a linear interpolation between the two physics states to get the current state to render.

http://web.archive.org/web/20190506030345/https://gafferongames.com/post/fix\_your\_timestep/

So let's say your last two physics updates we'll call A and B are from `00:10.033` and `00:10.066`, and it is now `00:10.070` when we want to perform a render. We have a remainder of `.004`.

I take "interpolation between the two physics states" to mean we compare all the objects in update **A** and **B** and slide them back from **B** towards **A** by `88% (.033-.004)/.033)`. This would mean I'm actually rendering the physical state at `00:10.037`, correct? So my physics updates **A** and B are really more like **previous** and **next** and my interpolation is between the previous and the next, correct?

# Answer
Exactly as you think. You use interpolation to render a state between 'previous' and 'next' state. If your timer says you're 88% between frames, you draw objects at 88% the distance between their previous and next position.

You can also use extrapolation, which removes the need to store previous state of the world, but you can (and probably many times will) overshoot, and your objects will render in the obstacles.
> 1 votes

---
Tags: fixed-timestep
---


# Question
Title: How can I publish my game (*.aab file) on google play?
I select arm64 (64 bit) and x86 and amrv7 and select build app bundle in player setting so but when I want publish so I have an error like :

Error

This release is not compliant with the Google Play 64-bit requirement

The following APKs or App Bundles are available to 64-bit devices, but they only have 32-bit native code: 2. Include 64-bit and 32-bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code it needs. This avoids increasing the overall size of your app.

---

I tried following the steps listed in this Stack Overflow post, but the problem remains. PLease answer me, why no people answer in this web site?

# Answer
I received the exact same error yesterday when I tried to publish a new update of the app. Apparently Google has made some changes internally. I had done about 30 builds before for this particular app, so I couldn't fathom what the difference was.

What solved it for me was unchecking the `x86` checkbox in the project settings.

This allowed my build to pass. I did get a notification that my new build would be supported by less devices. I checked the difference and the difference was '2'. From 12657 to 12655 devices.

I am not a 100% sure what the exact reason is that the `x86` build is rejected, but what I read on other forums was that it had to do something with missing `x64` libraries in the `x86` build. (but feel free to correct me if I am wrong)
> 2 votes

---
Tags: unity, google-play, google-play-services, build-process
---


# Question
Title: Entity Component System: where do I put containers?
I'm pretty new when it comes to the whole Entity Component System structure and I got some questions I just can't wrap my head around.

I know that for example collisions, you'd have a `CollisionComponent` and a `CollisionSystem` for handeling collisions. But what if I'd like to use a quadtree for collisions? Where do I put that quadtree? What do I store in that quadtree? Both the `PositionComponent` and `CollisionComponent`?

A quadtree is just an example, it could be any abstract container really. If somebody who has more experience with ECS could give me a primer on this, I'd be very grateful.

# Answer
---

## Update

I have wrote Theraot.ECS inspired by Fastest way to look up an entity with a set of components?.

However this answer motivated me to allow to specify custom containers for particular types. It would be necesary to provide an adapter to the interface `IIntKeyCollection<TValue>` exposed in the project. Which would in theory allow the ECS to use a quadtree internally, just for some types of componets, for example some third party `Vector2`.

The project is free and open source software, feel free to study it, use it, whatever. MIT license.

---

## Original Answer

> But what if I'd like to use a quadtree for collisions?

You have a physics system that has access to the quadtree.

**Addendum**: On the server both the physics (for collisions) and the network (to know what things are near the players, so it can send them only notification about their surrounding) would need the quadtree. On the client, both physics and rendering (to have a quick approximation of what is in camera to send to the GPU) would need the quadtree.

---

> Where do I put that quadtree?

It can be part of the physics system or shared (by means other than ECS) among various systems (you can pass it on system creation, see dependency injection).

---

Fancy commercial game engines can have the luxury of making a ECS that spatially aware. On one hand it has performance benefits. On the other it couples the ECS to a particular geometry, and a particular geometry library... which makes it very hard to reuse separete from the game engine.

**Addendum**: I believe it is possible to develop an ECS solution that allows to specify custom containers. Either for the whole or just for particular component types. We could tell such ECS to use (an adapter around) a quadtree that would be alike to the deeply woven one in the fancy ECS, except it was injected.

---

> What do I store in that quadtree?

Ern...

There are two ways that I can think of to go about this (besides the fancy spatially aware ECS):

* You have a system that synchronizes the quadtree with the ECS. This system will query every object that has a position component (and is not marked static or sleeping) and update the quadtree based on that.

This means your quadtree needs to have entity ids, and perhaps copies of relevant components that the systems that use the quadtree need.

The drawback is that you have a system busy synchronizing components, which would have some impact of performance.
* You have components that actually reference to the quadtree.

If we go for encapsulation, we would have a type – with value semantics – that has the means to get the position of an entity from the quadtree and to set the position updating the quadtree, and then you store that in your component.

If you want – or need – pure data, it would be a reference to the quadtree and some id for the position inside the quadtree (those could still be entity ids), such that the system that uses it will access the position associated with that component and not the others.

The drawback is, of course, that you have a reference to a big datastructure - which lies outside of the ECS - stored in your component. You must be aware of that when it comes to serialize the components for a save state, for example.

**Addendum**

* Have smart position components, such that systems can subscribe to changes of these components. Then the system that updates the quadtree can subscribe.

This is similar to the idea above, except the quadtree is not directly referenced in the component.

The ECS are not meant to have notification for changed components (and I do not mean events for added and removed components, but events for modified values), and having them is detrimental for performance※.

If the ECS does not have the means to subscribe to changes of a component - and I do not think they should have it, at least not out of the box※※ - we can make a not very pure component that has this ability.

*Perhaps having each component handle its own events does not sound as a great idea, then we could consider to centrilize these notification in a... wait, I'm adding a dependency to the components. We could just make that dependency the quadtree and we are back at idea above.*

---

※: On one hand, we can have only entities that move have a velocity component, or alternatively we can add a component to mark entities that do not move. In either case, the systems would be able to iterate over and only over the entities that move, being sure that all of them moved since last tick. On the other hand, ECS often optimize for cache locality and fast access and iteration, in fact, a tighly managed ECS could even provide - temporary - direct references to components allowing to modify them quickly but with no means to rise an event to notify that they were (well, we could assume they were modified if the developer took the references).

※※: If the ECS allows to specify a custom container, in particular for specific component types, we could tell the ECS to use one that has events for value changed. However, if that is possible, we could just use the quadtree.
> 4 votes

# Answer
Just like with any software architecture question, the short answer is "It depends..."

> Where do I put that quadtree?

Any auxiliary data structures needed by one system only should be part of that system. So if that quadtree is only used by the CollisionSystem, then you can make it part of the system.

But if that quadtree is used by many different systems, then it might make sense to extract it into an own system which does nothing but keep that quadtree up to date and also offers public interfaces for other systems to query the quadtree.

But on the other hand, if you have a dedicated MovementSystem in your architecture which is the only system allowed to move entities, then there could be potential efficiency gains to also have it manage the QuadTree. This is because the MovementSystem knows exactly which PositionComponents moved in the current tick, which allows it to decide if a branch of the quadtree needs to be updated or not.

> What do I store in that quadtree?

That depends on how you are using it and how expensive it is in your particular ECS architecture to navigate between components of the same entity. If retrieving components from entity IDs is fast, then the QuadTreeSystem might only store coordinate tuples and EntityIDs (if your PositionComponent is exactly that, it might store the PositionComponent).

But if navigating between components is expensive in your architecture, you might also store any other components in the tree nodes which are frequently required by the users of your QuadTreeSystem.
> 4 votes

---
Tags: architecture, quadtree, entity-component-system
---


title: Most optimal way to find closest object

text:
# Question
Title: Most optimal way to find closest object
So currently ive been using the `physics.castSphere` method with a small radius to find the closest of an object with a tag.

However this is pretty performance heavy so my question is, is there a way to optimize it?

i have also been looking at keeping a list of gameobjects and just looping through those however doing that a few times a frame for each object searching also seems rather performance intensive.

Here is my case:

> 50 individual characters on team 1
>
> 50 individual characters on team 2

each character has to find the closest of the character from the other team.

What is the fastest and least performance heavy way of doing it?

# Answer
if calculations are heavy you can divide them using something like Coroutine to avoid lags and...

if count of object that you need to calculate their distance is low you can simply calculate their distance or use rayCast if its important that nothing is between them.

if they are too many you can put a circle or... collider around it that only calculate those are in the range. you can make trigger bigger if there is no object in range.

if you use trigger you have to use layer masks to only calculate range for those only important.
> 1 votes

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


# Question
Title: How to make a PROPER main menu (or any other UI windows/modals) in Unity?
So, I'm currently learning both about Unity for the first time as well as the 'new' 2D UI system, but I'm having a hard time figuring out how to make windows, modals/dialogs, main menus etc. which are not only functioning, but also modular, reusable and written following proper coding standards. Most how to's, blogs, Q&As or tutorials I find only cover the most basic parts of UI development (e.g. how to drag a button from the toolbar to the scene window in 2 hours).

So basically, I'd like to have a main menu which meets those (very common) requirements:

* A button which 'starts' the game (e.g. by simply loading another scene)
* A button which 'quits' the game, but also opens up a confirmation dialog before
* A button which opens up an options dialog, which again is composed of multiple parts (audio, video...)
* and finally, it should be possible to go back to the previous screen using a 'back key/button', for example `Escape`

What I started with is a canvas which I called `GameMenu`. This canvas has several nested canvases, such as

* MainMenu
* OptionsMenu
    + OptionsMenuAudioPart
    + OptionsMenuVideoPart
* CancelMenuModal

Then I created a menu script which works as some sort of state machine:

```
public class MenuScript : MonoBehavior {

    private GameObject _currentStateObject;
    private GameObject _previousStateObject;

    public void SetState(GameObject newStateObject) {
        if(newStateObject == null || newStateObject)
            return;

        if(CurrentStateObject != null)
            CurrentStateObject.SetActive(false);
        _previousStateObject = _currentStateObject;
        CurrentStateObject = newStateObject;
        CurrentStateObject.SetActive(true);
    }
}

```

Every button has now an event trigger attached which calls the `SetState(...)` method on `MenuScript`.

However, I've got the following problems:

* How do I pass multiple parameters to methods invoked by event triggers? As soon as I add another parameter to `SetState(...)`, for example `bool isModal = false` to tell the method that it shouldn't disable the previous state, then it disappears from the event trigger action selection menu.
* How to I register key press events within the event triggers? It's easy by script (`Input.GetKey(...)` etc.), but I didn't find one on the event type selection.
* How do I make e.g. event triggers conditionally? So that certain events cannot be called when certain states are active?

I know I can solve all those problems within the script and make a fully functional main menu which does exactly what I want, but then...

* I cannot use it for something else
* I don't use the new Unity UI system, which makes me wonder what's the purpose of it
* I got to reference all involed game objects (the canvases, buttons etc.) in script, which makes it not really 'extendable' anymore as this means for every changed requirement, I have to alter the script (e.g. a new state, menu, button etc)

The main goal in the end is a script which I can use for all kinds of UIs without writing the same logic over and over again just because it's another scene, game state etc.

# Answer
> 1 votes
## General

There are many solutions for this approach. Mainly it would be just learning how to make every system reusable and modular. There are already a lot of solutions/patterns on the internet like: Micro-Services, Module Pattern...

After a bit of time and experience you would understand how to make everything modular and come up with your own solutions that work for your needs the best.

---

## Specific

I am going to describe the main system that I am using for UI.

I have a system that makes use of `MVC` pattern. I call it `OMCVO` \- Object Model Controller View Output.

In `Objects`\[aka `Components`\] I have data objects \[`Models`\] that are sent to a `Controller` which decides to what view to assign the data. Some views that I have are `Singleton`s, I usually don't use them through `Controller`.

\[Some of the method naming isn't the actual names of methods in system, they are just to show an example\].

Basically, I've split the `Data`, `Output` and `Behaviour`. The workflow is very simple:

* I create some `DataType` which I load with information and send this data to controller \[`Controller.Take(data)`\].
* Some `View` that accepts this `DataType` through `Controller` does calculations and displays them to `Output`.
* Some `Data` is linked to views for real-time changes.
* Views have standard API like `Open`, `Close`, `Show`, `Hide`, animations, relations to one another and other similar stuff.

Technical implementation is very tedious and complicated, so I won't go into it.

---

## Part of old asnwer that some people might find useful

But for this purpose I would have different Views that are Models and Controllers of itself.

For example, Confirmation Window - it has a method `public void ApplyConfirmation(UnityAction buttonConfirmationAction, string text);` \- and when you click on exit button wich has some method applied to if from MenuManager or whatever which has a call to Confirmation Window.

`ConfirmationWindow.Instance.ApplyConfirmation(delegate { this.ExitGame(this.SaveDataBeforeExit) }, "Do you really want to exit?");`

Now confirmation window pops up. `ApplyConfirmation` in my case has an "Yes" button which is asigned any method to be called when it's pressed and a text that changes the text on pop up window.

If you are sure that you are going to have only 1 UI element of that behavior and you can reuse it - you can go ahead and make it a Singleton to be able to call it easily from any class like `UIElementClassName.Instance.PublicMethodToCall();`

Hope you got the idea from it.

---

For a simpler and better described solution look at my other answer.

# Answer
> 1 votes
To address your problems:

* With default `UnityEvent` you cannot pass multiple parameters in the inspector. There are plugins that allow you to do that.
* You are probably referring to `EventSystem`. It has `Standalone Input Module` which which has settings for input. `Event System` has `First Selected`. It's an old input system module, you might want to write your own one to have full control over it. There probably exist ways to extend it, though.
* That is up to your created system or extended version of event system. I don't believe you can do this by default.

I would recommend to look into `Divide-and-conquer`. Try to split responsibilities as much as possible as long as it seems reasonable. If you are designing a system for reusable UI - you might want to split things like handling UI objects and how they react to changes of states in your game. Every game in some instances is different and in some it's similar. You can find things that are common for every/multiple games and create a system that uses those features only. And for specific features you would create game's unique behaviours.

Let's break down what each UI has in common or could have in most instances:

* Appear/Diappear.
* Animations \[Explained in "Most instances"\].
* Data to display. \[This one is a bit tricky, there way too many ways to put data in required forms. But you can choose your own approach to displaying data which in your own opinions suits your needs the best, or is the most performant, whatever you choose\].
* Fields to output data to. \[Same story with data\].
* Data communication. \[How to send data to display/How to get required data to display\].

(Most instances - because really what UI system needs to do is display information. I could just be `Text`, `Open`, `Close`. Not every UI needs animations, but well they feel nice :))

---

For this example, during game jam, I have created a project with reusable `View`s which is open to anyone on `Github`. In `View` I have tried to put everything that would usually be required for UI in Unity. Project has a little Main Menu demo. Like:

* Openning and closing.
* Playing animations.
* Generating animations for specific view.
* Makes use of `Canvas Group` which is commonly used in UI.
* Automatically creates/changes a few things on `GameObject` when script is applied.

You can modify it to your needs. But from my personal experience for every game that I have been using this system on I haven't removed any features, only added new ones or fixed some things. It does't really cover `Data •` because it is designed for every view to have it's own type of data communication route \[to put it simply - just creation of new method to display data with strong type. Or any other way, if you develop one, but this one is the easiest\].

Project is created in LWRP with Unity 2019.2.2f1 - **Unity UI View System**.

---

## Small example with animations from the project

---

For other game specific things like:

* Inventory.
* Dialogues.
* User information.

Those things are specific which require its own approach to how UI will work for them. But they still have those common things, like `Open/Close`, etc. If you want those UI's to be reusable as well - then make the systems\[Inv, Dialogue...\] reusable as well. One should adapt to the other in some way. (If someone knows some magic how to avoid that - I will gladly listen to theirs solution)

---

P.S. I've put this in another answer because it describes a different approach to solving the problem. I still use MVC alike pattern for personal projects which is a more complicated system to be described or developed.

# Answer
> 0 votes
If you want a modular UI you can use and implement different fonts/texts, I'd write my own gui texture's fonts ect and have a OnGui holding all the options you want then simply either create functions regarding each option or have multiple scripts. Regarding 'noise' if it works it works, having a simple:

```
audioMenu = false;
mainMenu = true;

```

Can simply revert u back to the main screen.

---
Tags: unity, gui, events, state
---


title: z ordering in directx11

text:
# Question
Title: z ordering in directx11
Hi recently i am trying to implement **z ordering system** into my directx framework. So *every object will have z order property(int), and this value will have higher priority than depth checking for rendering*. the current idea is from these three my assumptions that

1. depth check happens after vertex shader
2. value of `SV_POSITION` is used for depth checking
3. modifying z component of the value of `SV_POSITION` doesn't affect anything except in depth checking, because it is in projection space.

so after calculating projection position(local pos * WVP mat), i did projective dividision(it seems to make problem) and modified only z component corresponding orders that i want to draw with.

This is brief Vertex shader code

```
VS_OUTPUT output;

output.pos = mul(WVPMat, input.pos); // projection pos
output.pos /= output.pos.w;
output.pos.z -= renderPriority;

return output;

```

And !!! it kinds of works !!! but when i get my camera closer to any object, it weird thing happens

it doesn't make any this weird thing unless projective division. i am just curious why it happens instead of knowing another alternative way for z ordering. but any further advices and informations would be really appreciated.

# Answer
When the object is behind the camera, then the z coordinate is negative. The projection matrix uses that negative value and scales it and places it in the w coordinate. Since this is still negative, it will flip every coordinate. You need to clip the triangles before this happens
> 0 votes

# Answer
\[**Alternative Solution**\] Thanks for help guys. i just found out with your helps that **my idea won't work since the depth in pipeline will be restricted only between 0~1**.

Here is my another solution that i figured out. i post it here just in case for someone who need z order system. i came to **modify projection matrix** calculation. and have multiple of it, so that i have 5 hierarchy for rendering in my framework. you can set as many as you want btw.

```
// in class of application, not shader of GPU
#define Z_ORDER_MAX         5

#define Z_ORDER_UI          0
#define Z_ORDER_HIGHER      1
#define Z_ORDER_STANDARD    2
#define Z_ORDER_LOWER       3
#define Z_ORDER_BACKGROUND  4

projMats = new XMMATRIX[Z_ORDER_MAX];

for (int i = 0; i < Z_ORDER_MAX; ++i)
{
    float minD = i * 0.2f;
    float maxD = (i + 1)*0.2f;
    float A = (maxD * f - minD * n) / (f - 1));
    float B = n * (minD - A);
 // i can guess, after multiplication and perspective division, z value would be 'A+B/z'.  and then instead ranging them between 0~1, i does 0~0.2/0.2~0.4 so on.

    projMats[i] =
        XMMATRIX(
            1.0f / (aspectRatio*tan(verticalViewAngle*0.5f)), 0, 0, 0,
            0, 1.0f / tan(verticalViewAngle*0.5f), 0, 0,
            0, 0, A, 1,
            0, 0, B, 0);
}

```

and when you render any object, you choose and use the projMatrix corresponds to z order index that you want to set.
> 0 votes

---
Tags: directx, projection, depth-buffer, draw-order, vertex-shader
---