# Question
Title: Event when nodes overlap, but not collide
I am trying to implement a scenario where a dynamic object (a node that implements `RigidBody2D` and defines `BodyType2D.Dynamic`) "collides" with a static object (like the former, but defines `BodyType2D.Static`) by falling through it.

Think of it like Mario Cart, where you steer the cart in the direction of a box and the cart goes right through the box to collect whatever is inside. But the cart doesn't actually collide with the box. In this example, the cart is the dynamic object and the box is the static object.

Is there an event that notifies you of whether or not two nodes overlap (or collide) without implementing the actual collision?

For instance, I am aware of the following events defined by nodes, `NodeCollision`, `NodeCollisionStart`, and `NodeCollisionEnd`, as well as `PhysicsBeginContact2D`. The latter event invokes if both objects define collision properties (such as `CollisionBox2D`); if you remove collision on the static object (which is what I assume I ultimately have to do), the event no longer invokes.

The other three events never seem to invoke at all, though, when I tested them, the static object did not define any collision. Thus, it is possible the three events do invoke, but only when collision is defined. Needless to say, the static object shouldn't define actual collision so these events don't seem to be the answer.

I've tried a few experiments where I make the dynamic object static upon collision, remove the static object (to show that it was collected), then make the dynamic object dynamic again. Unfortunately, the physics of the dynamic object is still disrupted by the static object because it does technically still collide and changing `BodyType` is very expensive.

I've thought about writing some position checks in `OnUpdate`, but that seems hacky and very inelegant.

After perusing the documentation (primarily, here and here), I could not find anything pertaining to this type of scenario aside from the aforementioned four events, which do nothing in terms of my issue.

Is there an obscured facility somewhere meant for this type of thing? I am somewhat new to game development so forgive me if there's an important concept here I don't seem to be aware of.

# Answer
From the docs:

> **Sensors**
>
> A collision shape can be set to trigger mode to only report collisions without actually applying collision forces. This can be used to implement trigger areas.
> 1 votes

---
Tags: c#, collision-detection, xamarin, urho3d
---


title: JavaScript canvas remove image

text:
# Question
Title: JavaScript canvas remove image
I'm writing a platformer and I want to implement own art, now I know how to display it and this isn't my question. It rather is how do I remove it? I tried drawing a rectangle over it and removing it, but that doesn't seem to work, here's my code:

```
function clearImage(id) {
    for (var i = 0; i < 6;) {
        if (img_id[i] == id) {
            console.log(img_loc_x[i]);
            console.log(img_loc_y[i]);
            ctx.fillRect(img_loc_x[i], img_loc_y[i], "1000", "1000");
            ctx.clearRect(img_loc_x[i], img_loc_y[i], "1000", "1000");

            img_loc_x[i] = null;
            img_loc_y[i] = null;
            img_id[i] = null
            console.log("Cleared image with id: "+id+" succesfully!");
        } else {
            i++;
        }
    }
}

```

I'm using some arrays to store the image data such as the location and an id form management, but I didn't implement a method yet to get the dimensions of it, thats why I'm giving it the size parameters. (Strangely it works if I enter the `fillRect` and `clearRect` commands in the console)

# Answer
> 1 votes
It's difficult to know what's going wrong without seeing the rest of your code, but because you said it works when you type it into the console, my guess is that you're calling `clearRect` *before* you draw the image. This can happen if you're waiting for the image to load before you draw it, and do not wait for that to have happened before you clear it.

For example:

```
var sprite = new Image();
sprite.onload = function() { ctx.drawImage(sprite, 0, 0); };
sprite.src = "sprites/sheet1.png";

ctx.clearRect(0, 0, canvas.width, canvas.height); // oops! runs immediately

```

Try adding a `debugger;` statement to your code immediately before drawing and clearing and stepping through (or litter your code with `console.log` statements) to see what order things are happening and make sure nothing funny is going on.

# Answer
> 0 votes
I don't have enough reputation to put it in the comment ...

What I do is I have several canvases on top of each other, organized with z-index. In the background I would draw background (such as it is), then on next layers actors, then bullets and so on ...

The idea is, that you clear then redraw the whole layer. But only the layer which needs to be redrawn. It is much more efficient that having single canvas and redrawing everything.

# Answer
> 0 votes
A Javascript canvas behaves like, well, a canvas. The moment you draw an image onto the canvas, it is no longer an image. The effect of any draw function is that a bunch of pixels on the canvas change their RGBA color values. The pixels don't retain a memory of what object they represent. So you can not really move or remove an image you drew onto the canvas. You can only paint it over.

The pattern used by most games which use the HTML5 canvas is to use the `requestAnimationFrame` function to pass a draw function which:

1. completely erases the canvas by using `context.fillRect` or `context.clearRect` with the parameters `(0, 0, canvas.width, canvas.height)`.
2. redraws the whole game scene
3. call `requestAnimationFrame` again with the same function so the same thing happens in the next render-loop of the web browser.

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


title: DOM for GUI - display animated objects

text:
# Question
Title: DOM for GUI - display animated objects
I'm creating an HTML5 game using Canvas, but want to use DOM for the GUI for the reasons mentioned in there articles:

That being said, we have a component on the GUI that needs to be animated which will be through a sprite. Is it possible to render sprite animations through a DOM element?

# Answer
> 1 votes
Yes. Your options are:

1. use a (second, small) `<canvas>`, and draw your animations to that
2. use an `<img>` or `background-image` (e.g. on a `<div>`) and use Javascript to update which image is displayed on a timer
3. use a no-JS solution using CSS animation `steps()`
4. encode an animated gif for each animation you want to display and just point an `<img>` to the appropriate one

Option 1 is the most versatile: for example, you could render live thumbnails of in-game scenes to your UI, or 3d spinning images of items.

---
Tags: javascript, animation, sprites, html-canvas
---


# Question
Title: How to save/persist a GameObject with incremental levels? Dictionary? List?
I create buildings and they have child Text objects that will reflect the building level.

**The Problem:**

What can I use to store the buildings a player has built so the data can be persisted?

I've looked at Lists, but when I upgrade a building, how would I update the list so that particular building has its new level reflected?

I'm working on a dictionary so I can update the key with the new value (level) but running into a problem with the keys and names. If I have lets say 10 "Farms" and try to add them to the dictionary, even though they have different properties, I get an error that I have a duplicate.

Currently I am learning how to persist that data through scenes;

GameManager.CS

```
public class GameManager : MonoBehaviour
{

public static Dictionary<Building, int> playerBuilt = new Dictionary<Building, int>();

public void SaveState()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/EmpireGame", FileMode.Open);

        SaveClass sc = new SaveClass()
        {
            food = Player.food.amount,
            buildingList = playerBuilt
        };

        bf.Serialize(file, sc);
        file.Close();
    }
}

[Serializable]
class SaveClass
    {
        public int food, wood, iron, stone;
        public Dictionary<Building, int> buildingList = new Dictionary<Building, int>();
    }

```

Building.CS

```
public abstract class Building : MonoBehaviour, IUpgradable {

    public int ID;

    //level this building is
    public Text levelText;
    public int level = 0;

    //starting cost to amplify the upgrade cost
    public int foodBase, woodBase, ironBase, stoneBase;

    //Upgrade cost
    public int foodCost, woodCost, ironCost, stoneCost;
    public float BuildingCostPercentage = 5f;

    public void UpdateDictionary()
    {
        if (GameManager.playerBuilt.ContainsKey(this))
            GameManager.playerBuilt[this] = level;
        else
            GameManager.playerBuilt.Add(this, level);
    }
}

```

Note: I have not tested the save function so I expect errors.

# Answer
> 2 votes
Myself, I'd pull out just the parts of the building I really want to save - ie. those that are unique to this instance of the building. Eg..

```
[System.Serializable]
public struct BuildingRecord {
    public BuildingType type;
    public Vector2 position;
    public int level;
}

```

Here `BuildingType` could be an enumeration, or a reference/index to a Type Object, or even just a string key - whatever will help you look up the appropriate source assets like a prefab when you want to spawn this building back into the game when you load from your save file.

Your `Building` can have a method like so...

```
public BuildingRecord GetRecord() {
    return new BuildingRecord(){
       type = this.type,
       position = (Vector2)transform.position,
       level = this.level
    };
}

```

Then your save function can simply iterate over a list of `Building` component instances that you've maintained all along, or fetched on demand with `FindObjectsOfType<Building>()` and make a simple serializable array of them:

```
BuildingRecord[] SaveBuildings(IList<Building> buildings) {
    var records = new BuildingRecord[buildings.Count];
    for(int i = 0; i < records.Length; i++)
        records[i] = buildings[i].GetRecord();
    return records;
}

```

On deserialization, you can pass each record to a factory method to look up the right prefab using the type information, spawn it at the given position, and initialize it to the given level.

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


# Question
Title: How does Ashley keep systems up-to-date with its entities?
I am currently trying out Ashley and overall learning how an ECS works internally. What I currently don't understand is how Ashley in particular keeps its systems up-to-date by adding or removing entities based on the specified Family. See the following code:

```
  def main(args: Array[String]): Unit = {
    val engine = new Engine()

    engine.addSystem(new EntitySystem() {
      var entities: ImmutableArray[Entity] = _

      override def addedToEngine(engine: Engine) = {
        entities = engine.getEntitiesFor(Family.all(classOf[MyComponent]).get())
        println("updated entities")
      }

      override def update(deltaTime: Float) = {
        println(entities.size())
      }
    })

    engine.update(0F)
    engine.addEntity(produce())
    engine.update(0F)
    engine.addEntity(produce())
    engine.update(0F)
    engine.addEntity(produce())
  }

  def produce() = {
    val entity = new Entity()
    entity.add(new MyComponent)
    entity
  }

  final class MyComponent extends Component

```

Which regurgitates the following output:

```
updated entities
0
1
2

```

The `entities` object is an immutable wrapper around LibGDX's `Array` collection. The wrapped mutable variant isn't exposed either to the outside. There is no way this array can be mutated. The overrided `addedToEngine` method is only called when the `EntitySystem` was added to the `Engine`.

# Answer
> 2 votes
> There is no way this array can be mutated.

Wrong. If you look at the source code of `ImmutableArray` you can see that one of the constructors takes an `Array` as a parameter and stores it as a variable:

```
private final Array<T> array;

public ImmutableArray (Array<T> array) {
    this.array = array;
}

```

The `Engine` object simply keeps a reference to this internal array and edits it whenever it updates the systems:

```
// In "FamilyManager" - called when you call getEntitiesFor(Family)
private ImmutableArray<Entity> registerFamily(Family family) {
    ImmutableArray<Entity> entitiesInFamily = immutableFamilies.get(family);

    if (entitiesInFamily == null) {
        Array<Entity> familyEntities = new Array<Entity>(false, 16);
        entitiesInFamily = new ImmutableArray<Entity>(familyEntities);
        families.put(family, familyEntities); // <-- Store mutable array
        immutableFamilies.put(family, entitiesInFamily); // <-- Store immutable array

        // some other unrelated stuff
    }

    return entitiesInFamily; // <-- Returns the immutable array
}

```

Then whenever an entity is added it simply does something like this (pseudo):

```
private void entityAdded(Entity entity) {
    for(Family family : getMatchingFamilies(entity)) {
        Array<Entity> entities = families.get(family);
        entities.add(entity);
    }
}

```

---
Tags: java, libgdx, entity-system, ashley, scala
---


# Question
Title: How to make projectiles shoot at mouse position?
I'm looking to make it so my fired projectile is shot at the position of the mouse so aiming is an option ie:up down ect..

I have the script working to where it spawns the cloned object and launches it but it only shoots straight from my players hand before disappearing. how can I adjust my command so the object is shot in the direction the mouse is pointing?

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

public class ProjectileShooter : MonoBehaviour {
  [SerializeField]
  Transform attachmentPoint;
  GameObject prefab;

  void Start () {

    prefab = Resources.Load ("projectile") as GameObject;
  }

  // Update is called once per frame
  void Update () {
    if (Input.GetMouseButtonDown (0)) {
      GameObject projectile = Instantiate (prefab) as GameObject;
      projectile.transform.position = attachmentPoint.position + Camera.main.transform.forward * 2;
      Rigidbody rb = projectile.GetComponent<Rigidbody> ();
      rb.velocity = Camera.main.transform.forward * 40;
      Destroy (projectile, 2.5f);
    }
  }
}

```

# Answer
You're question is vague, but in general, the solution is to find the vector from the gun (or firing device) to the point where you want it to go. That is your direction vector. You can then normalize it and multiply it by the particle's speed to get a velocity. Something like this:

```
vec2 directionVec = chosenPoint - gunPoint;
directionVec.normalize();
directionVec *= particleSpeed;

```

This should work in both 2D and 3D. However, in 3D there's an extra step to figure out from the user's click what object they're aiming at. It will involve casting a ray from the camera into the scene and getting a list of objects it intersects. From that list, you need to decide which one the user intended to shoot at. It may be the one nearest the camera, or the one where the angle formed with the player's direction is closest to 0, for example.
> 1 votes

# Answer
The most accurate way is to retrieve the point where to shot based on the mouse position by casting a ray to the scene from the camera

```
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 10000.0f)) {
       Vector3 hitPoint = hit.point;
}

```

And then use the hitted point to find the vector based on your player/camera position.

NOTE: `Physics.Raycast` test only against collider. Any element without a collider will be ignored.
> 0 votes

---
Tags: unity, 3d
---


# Question
Title: Random 2d terrain algorithm for map generator
I'm new to game development and I need some advice. I'm building a web based 2d random map generator and I wonder which algorithms there are to create such random terrains in a simple matrix as seen in the images below. It would be great if anyone could point me to some terms/algorithms as I have absolutely no clue what to search for.

Note: I'm not interested in depth/biomes - just the generation of those 2d shapes that grow from a starting point.

I tried implementing it in several ways - but all attempts seem rather childish and don't really produce the desired result. First I started with a small pattern like a plus (5 cells) and replicated it always on the edges of the already generated cells. Another way was to define cubes in different sizes and then start to generate big cubes in any direction, after that put medium cubes on some random edges, then again with smaller ones etc.

Any tips are very much appreciated!

# Answer
If you are interested in generating maps that grow from a starting point, the formal names of the relevant topics are:

* cellular automata (for instance, using the 4-5 rule to generate caves)
* L-systems & other replacement grammars
* artificial life (for systems that model simple organisms such as yeast, etc)

That being said, it is not apparent what particular family of algorithm was used to generate the image you posted. Personally, I think it looks less like something that was 'grown' & more like a Perlin/simplex noise island, but it's not possible to come to any strong conclusions from the single image.
> 1 votes

---
Tags: algorithm, maps, terrain, random
---


# Question
Title: How does an iOS developer get his app/game on the AppStores main page?
I was looking at the front page of the AppStore, and they display a new game and a new app every day. I was just curious, how does an iPhone developer get their game or app onto that front page? Does Apple choose what goes on there? Or do you pay money?

I was just curious, I don't develop games for iOS.

# Answer
Typically, Apple makes their choices as to what goes in various featured sections at their discretion. If you have a good partnership with Apple, you may be able to guide their eye to your project, but in the end, it’s entirely up to them, and is not monetarily motivated (except that Apple gets paid when you buy apps and make in app purchases).
> 2 votes

---
Tags: game-design, ios, appstore
---


title: Code optimization

text:
# Question
Title: Code optimization
I'm making Space shooter game in Unity, in which I want to place boss. I have script in which I wrote how boss should move and it works but... I know i can do better. Any ideas how can I improve that code?

```
void FixedUpdate () {

     time -= Time.deltaTime;

     if(time < 0 && time > -2.7)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * speed;
     }
     else if(time < -2.7 && time > -5)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * 0;
     }
     else if(time < -5 && time > -7.7)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.right * speed;
     }
     else if (time < -7.7 && time > -9.7)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * 0;
     }
     else if(time < -9.7 && time > -11)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * 1/speed;
     }
     else if (time < -11 && time > -11.5)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * speed * 10;
     }
     else if (time < -11.5 && time > -16.15)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * speed;
     }
     else if (time < -16.15 && time > -19)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * 0;
     }
     else if (time < -19 && time > -24.5)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.right * speed;
     }
     else if (time < -24.5 && time > -26.5)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * 0;
     }
     else if (time < -26.5 && time > -27.8)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * 1 / speed;
     }
     else if (time < -27.8 && time > -28.3)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * speed * 10;
     }
     else if (time < -28.3 && time > -33)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * speed;
     }
     else if (time < -33 && time > -36)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * 0;
     }
     else if (time < -36 && time > -38.8)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.right * speed;
     }
     else if (time < -38.8 && time > -41)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * 0;
     }
     else if (time < -41 && time > -42.3)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = -1 * this.gameObject.transform.up * speed;
     }
     else if (time < -42.3 && time > -70)
     {
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * 0;
         Laser();
     }
     else if (time < -70 && time > -71.2)
     {
         laserSpawnDelay = 0;
         this.gameObject.GetComponent<Rigidbody2D>().velocity = this.gameObject.transform.up * speed;
     }
     else if (time < -71.2)
     {
         time = -2.7f;
     }

     GunShoot();
     RocketShoot();
     //Laser();

 }

```

# Answer
> 2 votes
The main problem here seems to be a code solution for a data problem. You basically want an array of {time,speed, direction} triplets. "Speed" in this context would be just the multiplier. So the table would look like this:

> { 0, 1, up }
>
> { 2.7, 0, up }
>
> { 5.0, 1, right }

BTW, the `1/speed` makes no sense; the dimension is just wrong. Whether you express `speed` in pixels/second or tiles/tick, you can't mix `speed` and `1/speed` because you'd be mixing distance per time and time per distance.

# Answer
> 0 votes
A few things:

You probably don't need to set the velocity every frame. It looks like you may want to just make sure it's set to be kinematic (in the inspector if possible), and then set the velocity once on each change.

This implementation is prone to decaying accuracy. Since you are setting the velocity rather than the position, and relying on an amount of time to pass before changing it, and `fixedDeltaTime` may not be set to an exact value where you trigger changes at the exact right physics step, the body won't necessarily end up in the same place each time you go through your movement loop. This would compound over time, causing gradual drift.

As mentioned by @MSalters, this does seem to be a problem where you are trying to represent data as code. You could expose some parameters in the inspector and use those. Here is an example of that put into code. This uses a coroutine to loop through the steps, and only sets the velocity on each change.

```
[Serializable]
public class AnimationStep {
    float Duration;
    Vector2 Velocity;
}
public AnimationStep[] Steps;

void Start () {
     StartCoroutine(RunBehavior());
}

IEnumerator RunBehavior() {
     Rigidbody2D body = GetComponent<Rigidbody2D>();
     var wait = new WaitForFixedUpdate();
     yield return wait;
     while (true) {
         foreach (var step in Steps) {
             body.velocity = step.Velocity * speed; //You could add more fields to AnimationStep to make this easier to use.
             float endTime = Time.fixedTime + step.Duration;
             while (Time.fixedTime < endTime)
                 yield return wait;
         }
     }
 }

void FixedUpdate() {
     GunShoot();
     RocketShoot();
     //Laser();
}

```

Note that this still suffers from the potential decaying accuracy problem. It uses a loop `yield return`ing every fixed update to wait for the next change, rather than using `WaitForSeconds`, which could cause even worse drift.

A better solution would be to specify a set of target positions to move between, rather than velocities (really, just make it an animation).

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


# Question
Title: Find ID from Spiral x, y positions. Hard programming formula
I have a formula, which gets coordinates from user\_id (see below).
I give User\_id, and I get back coordinates.
But now I need to get User\_id from coordinates.
For example:

```
function get_user_id_from_coordinates(x, y) {
  // if x = 1, y = 0, returns 4 (as in this image)
}

```

Please help me with that formula :) The first one i got also form this forum.

```
// if user_id = 64
function get_coordinates_from_user_id(user_id) {

  // Math.sqrt(user_id) = 8
  // 8-1 = 7
  // 7 / 2 = 3.5
  // Math.ceil(3.5) = 4
  var k = Math.ceil( (Math.sqrt(user_id) - 1) / 2 );

  // t = 2 * 4 + 1 = 9
  var t = 2 * k + 1;

  // m = 81
  var m = t * t;

  // t = 9 - 1 = 8
  t = t - 1;

  // if 64 >= 81 - 8.   If 64 >= 73
  if (user_id >= m - t) {
    // return [ -4, 4 - (81 - 64)].   return [ -4, -13 ]
    return [ -k,  k - (m - user_id)  ]
  }
  // else m = 81 - 8 = 73
  else m = m - t;

  // if 64 >= 73 - 8.   If 64 >= 65
  if (user_id >= m - t) {
    // return [ -4 + (73 - 64), -4].   return [ 5, -4 ]
    return [ -k + (m - user_id), -k]
  }
  // else m = 73 - 8 = 65
  else  m = m - t;

  // if 64 >= 65 - 8.   If 64 >= 57
  if (user_id >= m - t) {
    // return [ 4, -4 + (65 - 64) ].   return [ 4, -3 ]  <== passes
    return [ k, -k + (m - user_id) ]
  };

  // return [ 4 - (65 - 64 - 8), 4 ].   return [ 11, 4 ]
  else return [ k - (m - user_id - t), k ];
}

```

# Answer
> 8 votes
Let's add some colour coding to see if we can reveal some structure in the problem:

Here I've colour-coded the spiral into concentric rings of alternating colours. You'll notice the tile just before the bottom-left corner is always a perfect square. I'll dub this number the "Leader" of a given ring.

If we number our rings from 1 out, then the sequence of leader numbers is:

$$\begin{align} L(1) &= 1 &= 1^2\\ L(2) &= 9 &= 3^2\\ L(3) &= 25 &= 5^2\\ L(4) &= 49 &= 7^2\\ .&..\end{align}\\ L(ring) = (2\cdot ring - 1)^2$$

This will make it easy to number all the cells in a given ring, with reference to the corner. To reach...

* the row \\$y = 0\\$ in the left side of the ring, we subtract \\$(ring - 1)\\$
* the column \\$x = 0\\$ in the bottom of the ring, we add \\$(ring)\\$
* the bottom-right corner, we add \\$(2 \cdot ring)\\$
* the row \\$y = 0\\$ in the right side of the ring, we add \\$(3 \cdot ring)\\$
* the top-right corner, we add \\$(4 \cdot ring)\\$
* back to the column \\$x = 0\\$ along the top row, we add \\$(5 \cdot ring)\\$

So here's how we can translate that into a conversion method:

```
function spiralCellIndex(position) {
    // First, we round our position to the nearest grid cell.
    // Skip this if your input is already an integer pair grid coordinate.
    var x = Math.round(position.x/gridSpacing);
    var y = Math.round(position.y/gridSpacing);

    // Compute a modified x value symmetric across the line x = 0.5
    // (In the diagram I let this go negative,
    // but doing it this way saves an unnecessary abs() )
    var offCenterX = x > 0 ? x : -x + 1;

    var ring = Math.max(offCenterX, Math.abs(y));

    var leader = (2 * ring - 1);
    leader *= leader;

    // Top row of ring
    // (This one has to come before the left side, because the two
    // formulas disagree about the value to give the top-left cell)
    if(y === -ring)
        return leader + 5 * ring - x;

    // Right side of ring
    if(x === ring)
        return leader + 3 * ring - y;

    // Bottom of ring
    if(y === ring)
        return leader + ring + x;

    // Finally, left side of ring
    return leader - ring + 1 + y;
}

```

---
Tags: mathematics, javascript, geometry
---


# Question
Title: How to access sprite sheet via row and column
I'm currently designing a 2D game engine in C#, just had a quick question.

I have a `SpriteSheet` class that splits up a sprite into several different sprites (like a tileset for a example) and stores them in a list. Which is great, because now I can access sprites via it's corresponding index in the sheet.

However, I would really like to add a feature that will let me access a sprite by specifying the row and column it resides in (in the original sprite). I just don't know the equation to find where the sprite is in the list.

Here is what I have so far:

```
    public Sprite this[int index]
    {
        get { return this.sprites[index]; }
    }

    public Sprite this[int row, int column]
    {
        get
        {
            // Get the width and height of each individual sprite in the sheet.
            int cellWidth = this[0].Width;
            int cellHeight = this[0].Height;

            // Figure out and how many rows and columns are in the entire sprite sheet
            int rows = this.sprite.Width / cellWidth;
            int columns = this.sprite.Height / cellHeight;

            // Here is where I want to return the sprite located at the row and column specified.
            return this.sprites[ /* what do i put in here? */ ];
        }
    }

```

Also, I don't know if it will help but here is the method I use to fill the list with sprites:

```
    private void CreateSheet(Sprite sprite, int xOffset, int yOffset)
    {
        for (int y = 0; y < sprite.Height; y += yOffset)
        {
            for (int x = 0; x < sprite.Width; x += xOffset)
            {
                this.sprites.Add(sprite.Clone(new Rectangle(x, y, xOffset, yOffset)));
            }
        }
    }

```

# Answer
Since you are scanning from left to right and then top to bottom, you move one row down by adding (number of columns per row).

```
return this.sprites[row*columns + column];

```

meaning you don't need

```
int cellHeight = this[0].Height;
...
int columns = this.sprite.Height / cellHeight;

```
> 0 votes

# Answer
After getting extremely frustrated for the past hour I've stumbled upon a few questions on stack overflow that talk about converting 1D arrays to 2D arrays.

Finally, I was able to understand what to do, and my solution is this:

```
    public Sprite this[int row, int column]
    {
        get { return this[row + (this.sprite.Width / this[0].Height) * column]; }
    }

```
> 0 votes

---
Tags: sprites, spritesheet
---


# Question
Title: Path Planning in a chaotic, ever-changing environment
I've implemented Path Planning a few times, using A\* on nav meshes, and also Continuum Crowds but now I am trying to plan paths in very chaotic environments.

In this environment, new routes and new blockages are created constantly, and chaotically. This is because the environment is fully destructible, and the debris can create new obstacles.

In such an environment, nothing can be pre-computed. What would be a good way to sense the traversability in such a world? There is no concept of a grid in my world, b.t.w, but I wonder if I should introduce an artificial one for the purpose of planning.

But if navigation could be achieved without a grid, that would be much better of course.

Note that the navigation is not merely dynamic in the sense that certain transitions get opened/closed, but actually chaotic. This stops me from a simple approach of enabling/disabling certain edges on the navigation mesh. That approach would be usable if, e.g. a gate gets locked/unlocked. But in my case, in a blink of an eye, the routes could be drastically changed where simple mutations of a pre-computed mesh are not doable.

# Answer
With a robotic system needing to plan its movements quickly in a dynamic environment I have seen Rapidly-exploring random trees (or an adaption of them) being used for these approximations.
> 1 votes

---
Tags: path-finding
---


# Question
Title: Future of Julia in game development industry
I read in many posts that Julia is faster than many languages especially C++, What's the future of Julia in game development industry ? Will it replace all legacy C++ ?

# Answer
> 6 votes
As far as I am aware, Julia is not used at all in the games industry, except as a hobby language.

Firstly, you need to consider that *all* AAA games and AAA game engines are written in C/C++. These engines have full platform abstraction, so that you can write a game and it will run on a PC or PS4. Doing this in Julia, requires starting from scratch, which means an enormous cost for a company like Epic, in terms of learning hours (for the coders to be as competent in Julia as they are with C/C++), and actual man hours to do the actual writing of the engine. Then users of that engine also need to learn Julia to make games. Have fun justifying that to the literally hundreds of thousands of people using Unreal.

This is both unreasonably expensive, and unnecessary, when a perfectly good engine already exists, in a language that all the coders are already proficient with. In short, such an exercise would be wasteful, and provide no tangible benefit.

Secondly, All game engine coders are educated to write C/C++ from year 1. Graphics programmers are taught using the C++ DirectX or OpenGL API. Some branch out into web/mobile development and OpenGL\_ES, but the vast bulk continue using C++ and the API they were taught to use. Due to the frankly enormous number of coders who were taught and continue to use C/C++, there is considerable resistance to change. It's hard to convince a dozen coders to abandon their primary language (let alone tens, or hundreds of thousands), in favour of one that is unproven in a commercial game environment.

Thirdly, C++ as a fully established(for several decades), and proven game worthy language, has thousands of tested, fully supported libraries to allow the easy writing of games, for multiple platforms. I will guarantee you Julia has nowhere near that kind of support.

Finally, your claim that it is faster than C is not quite right. IBM have tested the computational speed of C, Cython, and Julia. In smaller scale matrix operations (common in games), Julia is indeed faster, but as the problems scale up, both C and Cython catch up in performance, until the difference is negligible.

So a language which has comparable performance, with vast support, a large professional talent base, and is directly supported for game dev, by both Microsoft and Khronos, compared to a language which has virtually none of that except a bit better performance.

I will also add that when writing code in C++, if you desperately need performance in a small block of code, you can always just write the code in assembly language, and insert a pre-processor directive to use the asm compiler, the result of which would be faster than Julia, if such performance gains were ever necessary.

But in practical truth, the vast bulk of your performance gains will be from how well you write your algorithms, which will always be affected by how well you know the language, and the fact is, more game programmers know C/C++ and so you are far more likely to get a well written game in C++ than you are in Julia.

C++ is not going to be supplanted by any other language in the game industry.

---
Tags: game-design
---


# Question
Title: the tree couldn't be instanced because the prefab contains no valid mesh renderer
I am beginner in unity. The problem is when i installed a package tree from Asset Store then imported a tree, show me following message

**the tree couldn't be instanced because the prefab contains no valid mesh renderer**

so what the problem here and what should i do in this case ?

# Answer
The easy way for this error is

1. Click on this **Prefab**
2. Remove the mesh render for this **gameObject**
3. From **Inspector window** =\> **Add Component** =\> **Mesh Renderer**
> 1 votes

# Answer
I was curious as to why it doesnt work for you. So i decided to try it.

* I am using Unity 5.3.4f1
* Downloaded the package
* Created a new scene
* added a new plane(made the plane a little bigger)
* went to UF Creator Lite-\>Prefabs-\>Trees
* in that folder there are 3 trees
* **drag and drop** each one to the plane

and they should work after that.
> 0 votes

---
Tags: unity
---


# Question
Title: Referenced script only working for one asset Unity C#
In my game, there is a maze, which has its walls generated by several types of points. In the top row, there are points that I call "type A" point - they only generate walls vertically (downward). "Type B" points have only horizontal (sideways) walls, and "type C" points generate both horizontal and vertical walls. All "A, B and C" points also generate items

because of this, I am using "shared" functions that are referenced on another script, in order to boost efficiency and so that I don't have identical code for the functions of generation on these points, as they all generate items the same way, and where applicable, generate horizontal and vertical walls in exactly the same way.

The issue here is, that I have a central script, that, within the scripts for "A, B and C", is referenced (public void function). the referencing works perfectly well.

however all the vertical walls generate on exactly the same point "A", (of which is first in terms of it's position in the row, and additionally first in the hierarchy); instead of all the different point "A"'s, meaning the rest of the point "A"'s are blank.

My function is "GenVwall", short for "Generate Vertical Wall", located in the central script:

```
public void GenVwall () {

    GameObject objV;

    //Decide the probability of there being a tile
    float lvlF = Mathf.Log10(gameManagerS.lvlNum);
    float pointF = 38.2f + (9.8f * (lvlF + 1));
    float decideV = Random.Range(0, 100);

    //Spawn different wall types (vertically)
    if (decideV < pointF) {
        int vWall = Random.Range (0, 40);
        if (vWall <= 24) {
            objV = Instantiate (Resources.Load ("tiles/wallReg"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 24 && vWall <= 26) {
            objV = Instantiate (Resources.Load ("tiles/wallSpiked"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 26 && vWall <= 31) {
            objV = Instantiate (Resources.Load ("tiles/wallBreak"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 31 && vWall <= 35) {
            objV = Instantiate (Resources.Load ("tiles/wallHalf"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 35 && vWall <= 38) {
            objV = Instantiate (Resources.Load ("tiles/wallGate"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 38) {
            objV = Instantiate (Resources.Load ("tiles/wallExplode"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        }
    }
}

```

and the referencing of the public void function, located within the "A" point script, is:

```
GameObject tempObj = GameObject.Find("genPointA");
    genPointS = tempObj.GetComponent<GenPointS>();
    genPointS.GenVwall();

```

Now, I believe the issue lies within the fact i use transform.position, and it's referring to the position of the first "point A" in the hierarchy.

Now, I'd like to know,

Is there a better way to make use of these functions? as I can't consider it too efficient to have the same function copy-pasted into the individual scripts for point "A, B and C".

# Answer
> 0 votes
A few strategies you can use:

1. Don't use different scripts for A, B, and C. Just make one wall-generator script where you can control horizontal or vertical wall spawning in data. eg...

public class WallSpawner : MonoBehaviour {
    public bool vertical; // Enable for A & C instances
    public bool horizontal; // Enable for B & C instances

```
   public void Spawn() {
       if(vertical) GenerateVerticalWall();
       if(horizontal) GenerateHorizontalWall();
   }

```

}

2. Have A, B, and C derive from a common WallSpawner class, and define their shared methods there (in typical OOP inheritance style)
3. If your shared wall-spawning logic isn't going to be attached to the instance it's spawning from anyway, then why not make it static? No messy `Find`/`GetComponent` required!

```
public static GenerateVerticalWallAt(Transform location) {
   // Use the location argument for positioning and orienting the wall.
   ...
}
```

Then your instance call this and pass its own transform as the spawn location.

`SharedSpawningLogicClass.GenerateVerticalWallAt(this.transform);`

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


# Question
Title: Canvas Element Not Render In Proper Position
I don't know what's going wrong. The `Text` and `Slider` must be on the red square area. Anyone can help to determine this bug ? Thanks

# Answer
> 0 votes
My friend had found it. The update is just to fast. My code is set the `Text` and `Slider` value first before I `SetActive(true)`. It's mean the canvas don't get the chance to update the position because it just too fast.

So the solution is `SetActive(true)` the canvas first, Then update the canvas position

---
Tags: unity
---


# Question
Title: Unity RectTransformUtility.ScreenPointToLocalPointInRectangle
What does the unity's RectTransformUtility.ScreenPointToLocalPointInRectangle do I've read unity documentation but I didn't get the clear meaning.

# Answer
> 4 votes
# Preface

This question starts with a small geometry problem. You have two different planes which may or may not be parallel.

1) Your screen space. This is the actual screen coordinates your computer is displaying and its where your arrow icon moves around in when you move your mouse. This can be thought of as a 2D plane across the surface of your screen.

2) A rectangle in your scene. Due to how Unity3D (the 3d part is important here) sets up the scene you have objects that exist in an environment with depth. In a 2D scene this plane will most likely be parallel to your screen, however in a 3D scene this plane may intersect your screen instead of running along side of it.

# What does this function do?

This function will take a coordinate on your screen (a common example is mouse position) and translate it so that instead of sliding along your screen, it slides along the plane of a rectangle in your scene.

# Documentation

Now lets go over each part of the documentation in a little extra detail.

### Parameters

Names are in bold, and Unity3D's documentation is in italics.

**rect:** *The RectTransform to find a point inside.* This rectangle defines the plane you want to transform your screen space coordinate into.

**cam:** *The camera associated with the screen space position.* This is a camera object which is representing your screen space coordinate. So this function will take a point from this camera's reference and adjust it so its relative to the **rect** parameter.

**screenPoint:** *Screen space position.* This is a point you have (calculated, or gotten. Maybe even your mouse position from the example above?) and that you would like to move into your rectangle's plane.

**localPoint:** *Point in local space of the rect transform.* This is an "out" parameter. This means that you pass in a blank point object and this function will populate it. This **localPoint** is populated with the **screenPoint** translated from **cam**-space to **rect**-space.

### Returns

**bool** *Returns true if the plane of the RectTransform is hit, regardless of whether the point is inside the rectangle.* This means that the function will return true if it worked, and it will return false if it was unable to convert the **cam**-space point into **rect**-space. The reason it returns a bool is so that it can let you know if it failed to calculate in a way other than just crashing your program. Checking the bool before you use the returned out **localPoint** is probably a good idea, although it may be unnecessary for what your doing.

### Description

This just provides some warnings and info on edge cases. But we've already covered the gist of the documentation so I'll let you ask another question if you run into any issues using this function.

Hope this helps! Let me know if there are any other questions.

# = EDIT =

Sorry for the delay, just saw your comment. I also don't have access to Unity3D on this computer so the examples are not guaranteed to work. I may be able to find some time tonight to write a sample program, but no promises (sorry in advance if I can't get around to it!)

### Returns in-depth

This function only has 2 different returns. It returns a boolean(true/false, yes/no) value.

It returns 'true' if the function was ran successfully. This means that there will be some Point coordinate in the **localPoint** out parameter that you can trust (only trust it as far as you trust your inputs).

If the function returns false that means that it was unable to calculate a **localPoint**. This can potentially happen if you pass in a null object, or perhaps a camera that isn't active.

### Example

**Scenario:**
You want some small critter to follow your mouse around on the main menu.

**Things you'll need:**
1) The RectTransform which describes the background for your main menu.
2) The GameObject of your small critter.

**Untested example code**

```
void Update()
{
    // this is a hard-attach. you can move it over a Time.delta or
    // give it some other behavior to make it more interesting.
    RectTransformUtility.WorldToScreenPoint(menu_background_rect,
        Input.mousePosition, Camera.main, critter.transform.position);
}

```

You'll likely have an easier time figuring out what it does by trying it yourself and seeing first hand what the results are, but I hope this is a good enough starting point. Good luck!

---
Tags: unity, transformation, unityscript
---


# Question
Title: c++ static only classes for subsytems and Engine
From the book **Game Engine Architecture**

> In C++, global and static objects are constructed before the program’s entry point (main(), or WinMain() under Windows) is called. However, these constructors are called in a totally unpredictable order. The destructors of global and static class instances are called after main() returns, and once again they are called in an unpredictable order. Clearly this behavior is not desirable for initializing and shutting down the subsystems of a game engine, or indeed any software system that has interdependencies between its global objects.

The book suggests to implement the subsystems as singelton objects with empty constructor and destructor and add explicit `Init()` and `Dispose()` methods, such that the construction and destruction order can be manually specified. The question is now whether this can be done using global static classes instead of singelton objects, like this:

```
//Renderer.h
class Renderer
{
public:
    static void Init()
    {
        //init logic
    }

    //Some static, global fields

    static void Dispose()
    {
        //Disposing logic
    }
private:
     //some more static, not global fields / methods
};

//Engine.h
class Engine
{
public:
  static void Init()
  {
    Renderer::Init();
    //etc
  }
  //other stuff

  static void Dispose()
  {
      Renderer::Dispose();
      //etc
  }
};

//Main.cpp

int main()
{
    Engine::Init();
    //some work
    Engine::Dispose();
}

```

Will this kind of approach also solve the initialization order problem described in the book?

# Answer
> 1 votes
> Will this kind of approach also solve the initialization order problem described in the book?

Yes.

The book is referring to the "static initialization order fiasco," which has to do with static *objects*. In your example you are creating static *functions*, which don't get "initialized" ever; they aren't objects. So they are not subject to this issue.

The static members of these classes that you add *will be* objects and *will* be subject to the SIOF. But as long as you don't allow them to do any interdependent initialization, as long as you defer that to your `Init` function (and the cleanup to your `Dispose` function), which you call manually, you can use this approach to solve the problem.

(Note that your "static class" approach is essentially the equivalent to a collection of free functions and global state.)

# Answer
> 0 votes
1. A word about static objects.
2. Static functions approach.

**A word about static objects.**

First of all, the book is not perfectly correct about static objects: The standard does not guarantee that they will be constructed before the program's entry point. It only guarantees that they are constructed before their first usage.

In practice, we can note that:

* Global static object are constructed before the program's entry point,
* Static field (class variables) objects or static variable (method variables) objects are constructed when they are used.

This is useful, for instance, to simulate the concept of static constructor, available in C#.

Let's consider the following code...

```
#include <iostream>

struct Bar
{
    Bar ()
    {
        std::cout << "Bar constructor\n";
    }
};

class Foo
{
public:
    Foo ()
    {
        static StaticConstructor staticConstructor;
        std::cout << "Foo constructor\n";
    }

private:
    struct StaticConstructor
    {
        StaticConstructor ()
        {
            std::cout << "Foo static constructor\n";
        }
    };

    static Bar field;
};

int main ()
{
    std::cout << "Let's go!\n";
    Foo foo1;
    Foo foo2;
    return EXIT_SUCCESS;
}

```

Output:

> ```
> Let's go!
> Foo static constructor
> Foo constructor
> Foo constructor
>
> ```

You can note that the static variable `staticConstructor` is constructed after "`Let's go!`", so after the program's entry point. You can also note that the static field `field` is never constructed because it was not used.

**Static functions approach.**

Yes, this approach is the correct one.

That is what the book recommended. A singleton is nothing less than a global variable (that also guarantees to be instantiated only once). Methods of a singleton can be seen as free methods... except that they can share data in the protected namespace of the singleton class. But if you do not have such data, it's all the same. ^^

The only problem with that, is that you are not exception proof: What you initialize this way is not guaranteed to be disposed. Have a look at the RAII principles.

What I could suggest is to add some `Subsytems` class responsible of both `Init` and `Dispose` sequences.

Here is a small example of what I mean:

```
#include <iostream>

class Engine
{
public:
    static void Init ()    { std::cout << "Engine::Init\n"; }
    static void Dispose () { std::cout << "Engine::Dispose\n"; }
};

class Renderer
{
public:
    //static void Init ()    { throw "Renderer init failed!"; }
    static void Init ()    { std::cout << "Renderer::Init\n"; }
    static void Dispose () { std::cout << "Renderer::Dispose\n"; }
};

class Subsystems
{
public:
    Subsystems () {}

    void Init ()
    {
        Engine::Init();
        Renderer::Init ();
    }

    ~Subsystems ()
    {
        Renderer::Dispose ();
        Engine::Dispose();
    }
};

int main ()
{
    std::cout << "Let's go!\n";
    try
    {
        Subsystems subsystems;
        subsystems.Init ();
        std::cout << "If init worked, do some stuff...\n";
    }
    catch ( ... )
    {
        std::cout << "Kaboom!\n";
    }
    return EXIT_SUCCESS;
}

```

Output:

> ```
> Let's go!
> Engine::Init
> Renderer::Init
> If init worked, do some stuff...
> Renderer::Dispose
> Engine::Dispose
>
> ```

If you uncomment the Init with the throw and comment the other one, you'll have:

> ```
> Let's go!
> Engine::Init
> Renderer::Dispose
> Engine::Dispose
> Kaboom!
>
> ```

Of course, your `Dispose` methods should be designed to be robust against a call where partial or no initialization has been performed. ;)

Also note that I didn't add the init sequence in the `Subsystems` constructor. Why? Because if a constructor throws, the destructor is not called.

Hope it helps. ;)

---
Tags: c++
---


title: Map growing algorithm

text:
# Question
Title: Map growing algorithm
I'm quite new to programming games and I'm currently working on a group project in university on creating one. In the game we've got a set of squares (cities, other entities) which are placed on the real plane. We'd like to start the game with a few squares in the center of the map and, as time goes, randomly place new ones around them, growing the whole network like that. I couldn't figure out how to elegantly do this and I found a lot of map generation algorithms, but they're mostly for surfaces and similar things, whereas my problem is more discrete. Any ideas?

I've added a picture in response to a comment - so our game might start off with the three red squares and as time goes we might add additional three squares (greens), after a while we can add two more squares again and so on.

# Answer
I find that a very elegant way of random placement is the use of Halton sequences.

Compare the random with Halton, here:

As you can see, the Halton-2,3 distribution is much more orderly, in that all points have their neighbours at a reasonable distance. Also, it progressively densifies, so the first samples are all widely spaced apart.

Now, in your specific application, you want to grow outwards. You could achieve this with filtering the sequence based on proximity to centre.

Do you ever want your cities to show 'infill?' If not, you could simply sort the sequence on distance to centre, and create them in that order.

If you do want occasional infill, I would push them outward, with increasing distance for each city. The extends will grow, yet, spaces in the interiour will get filled every now and then.

You could also reject outliers based on a radius, with a growing radius as the city grows.

The code to reject samples would look like this:

```
    i = 0
    while numaccepted < numv:
            x = -1 + 2 * halton( i, 2 )
            y = -1 + 2 * halton( i, 3 )
            allowed_radius = 0.1 + 0.9 * numaccepted / float(numv)
            if pt_in_circle( x, y, allowed_radius ) :
                    accepted.append( (x,y) )
                    numaccepted += 1
            i += 1

```

As you generate samples, you slowly grow the accepted distance from centre from 0.1 to 1.0 units.

And to generate the halton numbers, I used:

```
def halton(idx, base) :
        result = 0
        f = 1.0 / base
        i = idx
        while ( i > 0 ) :
                result += f * ( i % base )
                i = i / base
                f = f / base
        return result

```

Which results in the follow growth animation of 200 samples that survived the rejection test. To get them, a total of 2791 samples were tested, by the way.

Because so many samples are rejected, the final result is not as nicely distributed as straight up Halton-2,3. You would get a nicer distribution by sorting the Halton samples, at the detriment of never seeing new samples in the interiour: they will always grow at the outskirts.

This is what it looks like if you generate 200 Halton samples that fall with in the unit circle, and then sort them by distance to the origin:
> 1 votes

---
Tags: maps, random
---


# Question
Title: How to add rotation to two particle collisions?
I'm trying to make a particle system where when particles collide, they merge together, to get the new velocity vector the smaller particle's force is added to the larger one. However, this isn't exactly how I want it to work because when a small particle hits the edge of a large particle it shouldn't simply move in the direction it was hit. It should impart a rotational force, and that should be resisted by inertia. The further away from the center the more it should rotate the particle as opposed to pushing it. What is the physically accurate way to approach this problem?

# Answer
> 0 votes
The correct physics to use here is **conservation of angular momentum**.

For the two particle collision you describe, it will be easiest to calculate the angular momentum about the center of the large particle. Then the initial angular momentum will be *L=mvr*, where *m* and *v* are the small particle's mass and velocity, and *r* is the perpendicular distance from the small particles trajectory to the center of mass of the large particle. The final angular momentum will be *L=Iw*, where *I* is the moment of inertial of the large particle, and *w* is it's angular velocity.

Solving these gives,

```
mvr = Iw
w = mvr/I

```

If the large particle is a sphere, then it's moment of inertia will be *I = (2/5)MR^2*. So,

```
w = (5/2)(mvr/MR^2)

```

I suggest reading a bit about angular momentum, if this doesn't call the topic to mind.

Note also that this matches part of your intuition, that the "further away from the center the more it should rotate the particle as opposed to pushing it". This is the *r* parameter, so the larger *r* is, the more it rotates (ie, *w* is larger). But the other part of this intuition is incorrect: it doesn't rotate more "as opposed to pushing it". It is pushed the same amount, that is, the center of mass about which this combined particle will spin will move at the same speed in both cases, since this is due to conservation of linear momentum which is independent of *r*. This incorrect intuition probably comes from the idea of conservation of energy (that if more energy goes into spinning of the particle than it's going to have to move slower), but that's not useful or correct in an inelastic collision (such as here when the particles stick together).

---

Below are answers to possible questions:

**Are linear momentum and angular momentum independent?**: Yes, linear and angular momentum are independent in the sense that both quantities are always independently conserved within a closed system (ie, one that has no external forces or torques applied to it). They are different in some ways, for example, linear momentum is a fundamental property of all masses whereas angular momentum is a derived quantity that's primarily useful only for rigid bodies.

**What's the difference between momentum and force?**: Momentum is a property of a body, force is a thing that's externally applied to a body that changes its momentum. Similarly for angular momentum: Angular momentum is a property of a body, torque is a thing that's externally applied to a body that changes the angular momentum. So when the question mentions, "get the new velocity vector the smaller particle's force is added to the larger one". This statement is true if the word "momentum" replaces "force", but without that substitution it doesn't really work from a physics perspective. And in this case, the correct momentum is linear momentum (*p=mv*), not angular momentum.

**When are conservation of linear and angular momentum useful**: In these rules, it's important to keep in mind that the conservation rules only apply to closed systems, that is, systems without external forces and torques. To understand this, consider two variations on a somewhat similar example: 1) If a spinning wheel is dropped onto the ground, then the ground will apply an external force to the edge of the wheel (so it's both an external force, and a torque about the axil) and this force and torque will both reduce the spin of the wheel (the external torque will reduce the angular momentum) and make it move forward (the force will increase the linear momentum). That is, neither the linear or angular momentum are conserved because both an external force and torque have been applied. But, 2) if two spinning wheels collide in space (so it's a closed system with only two interacting bodies), then the collision will preserve both the total linear momentum and the total angular momentum.

**How about elastic vs inelastic collisions**: Unlike conservation of energy which only holds for elastic collisions, conservation of linear and angular momentum holds for both elastic and inelastic collisions.

# Answer
> 0 votes
If a billiard ball (pool, snooker, whathaveyou) hits another 50% from full on, I am pretty sure there is no creation of angular momentum.

If the first ball had no rotation, I don't think the 2nd ball would be rotating after being struck.

That said, if you did want to introduce it on collision, just take the cross product between vector A and B, where:

A is the velocity vector of ball 0.

B is the unit vector pointing from ball 0 to ball 1.

Then use the magnitude of the cross product as a measure on how much side-ways the impact was. Use the sign to determine which direction to spin the particle, L or R.

If you work in 3D, just use the entire cross product vector for rotation direction and magnitude.

If both balls are moving, you should probably do the same again with roles reversed.

I think more physically correct would be not to add angular impulse based on grazing factor. Instead, transfer existing momentum, regardless on how much full-on the contact was.But I think that requires taking elasticity into account.

# Answer
> 0 votes
I am not able to write down the exact formulas from the top of my head, but some starting points:

* you need to define the friction coefficients between the two objects. Friction is a function of both object's surfaces, but you can simplify to giving each surface a coefficient, and always use the larger one when two objects connect.
* you need to define each object's elasticity, between 0 and 1. A billiard ball would be very near to one, and for example foam would be about zero. Again, you can simplify, this time to always use the smaller value.
* when the objects touch, the total momentum is always kept (mass1 * velocity1 + mass2 * velocity2 = const, where velocities are vectors)
* also, the total energy is always kept, but a part of it is converted to deformation energy = warmth (mass1 * velocity1^2 + mass2 * velocity2^2 = const)
* your elasticity defines how much energy gets converted into deformation
* your friction coefficient defines how much energy gets converted into rotation
* the rest goes into v1 and v2 after the bounce
* from the two equations, you can calculate the momentum and rotation of each object after the touch: (1) total momentum before = total momentum after touch = const; (2) total move energy before, minus deformation, minus rotation = total move energy after the touch.
* from the amount of energy going into rotation, and the data about the object's rotational inertia, you can calculate the rotation speed of each object

That is all not that trivial, but such is the real world.

---
Tags: java, collision-detection, physics, rotation, particles
---


title: How to find points that lie on a circle

text:
# Question
Title: How to find points that lie on a circle
From the image below I know the vectors P1, P2 and P3. How can I find the point A which lies on the circle and line P2A which is a bisector (angle q and r are equal) of the lines P2P1 and P2B? Also how can I find the point B which is in the same direction as P2P3 and lies on the circle?

# Answer
> 2 votes
First, let's name some more vectors so that the origin is at P2 :

$$v\_1 = P\_1 - P\_2$$ $$v\_3 = P\_3 - P\_2$$

We can find B by normalizing v3 and scaling it by the length of v1 (that is, the radius of the circle):

$$v\_B = {\lVert v\_1 \rVert \over \lVert v\_3 \rVert} v\_3$$ $$B = P\_2 + v\_B$$

Finally, we can sum both side vectors to get a bisector, and normalize and scale that to get A: $$v\_A = {\lVert v\_1 \rVert \over \lVert v\_1 + v\_B \rVert}(v\_1 + v\_B)$$ $$A = P\_2 + v\_A$$

You will probably find possible optimizations while implementing this.

# Answer
> 0 votes
P2P3.normalized\*R = P2B;

Where R = P2P1.magnitude or R = P2A.magnitude; etc...

P2A = Quaternion.AngleAxis(Q, Vector3.forward)\* P2P1 = Quaternion.AngleAxis(-r, Vector3.forward)\* P2B;

# Answer
> 0 votes
Let \\$\vec a\\$ be \\$P1- P2\\$ and \\$ \vec b\\$ be \\$P3-P2\\$

Then point B is simply

$$ P2 +\frac{\vec b}{|\vec b|} \cdot radius$$

And point A is

$$ \vec c = (B + P1) / 2 - P2$$ $$ A = P2 + \frac{\vec c}{|\vec c|} \cdot radius$$

# Answer
> 0 votes
Here's the answer strictly in unity's terms.

```
public Vector2 p1;
public Vector2 p2;
public Vector2 p3;
Vector2 b;
Vector2 a;

void Start() {
    float radius = (p1 - p2).magnitude;
    //Direction from p2 to p3
    Vector2 p2_p3_Dir = (p3 - p2).normalized;
    //Find point b
    b = p2 + p2_p3_Dir * radius;

    //Vector from b to p1
    Vector2 b_p1 = (p1 - b);
    //Distance from b to p1
    float b_p1_Distance = b_p1.magnitude;
    //Direction vector from b to p1
    Vector2 b_p1_Dir = b_p1.normalized;
    //Temporary point midway between b and p1
    Vector2 temp = b + b_p1_Dir * (b_p1_Distance/2);
    //Direction from p2 to temp
    Vector2 p2_temp_Dir = (temp - p2).normalized;
    //Finally, find a
    a = p2 + p2_temp_Dir * radius;

}

```

---
Tags: unity
---


# Question
Title: How can I add 3D animation to my Pygame window?
I've developed a quiz game using Pygame but now I'm being asked to implement a 3D animation element (a game show host) to the game.

I used Pygame as I was told it would be an easy enough language to learn and make something simple, however I see now that it seems very limited in terms of 3D animation.

I've seen OpenGL being used with Pygame and what I need is for my game to run exactly as it is, but with the 3D element (game show host) added on the corner of the window for example.

How can I use OpenGL in Pygame in order to do this?

# Answer
> 1 votes
```
import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

    glTranslatef(0.0,0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)

main()

```

This is some example code taken from https://pythonprogramming.net that creates a simple cube and draws it on screen. It has and accompanying tutorial playlist featured here.

You will need to have the seperate PyOpenGL installed which can be found here.

In the example code he first creates a list of vertices and a list of edges that references the index of each vertex. He then creates a simple Cube class which loops through each vertex and connects them with lines.

In the main function when `pygame.display.set_mode()` is called, it should have the `DOUBLEBUF` tag to create a double buffer, and the `OPENGL` tag to have pygame create an OpenGL-renderable display. You can find more info on the Pygame display module at the Pygame docs here.

He then creates the OpenGL perspective with `gluPerspective` with the FOV, Aspect-ratio, and near and far clipping planes `glTranslatef` translates the display (in this case -5 on the z axis.

In the main loop, among the normal Pygame code, `glClear` clears the display with the flags being what is meant to be cleared, and the `Cube()` class which creates the wireframe cube that was mentioned earlier.

Hopefully this helps you on the track learning PyOpenGL in Pygame.

---
Tags: opengl, 3d, python, pygame
---


title: Linq with Unity - Select One from Many

text:
# Question
Title: Linq with Unity - Select One from Many
I'm using Linq to select the objects closest to the player that have the usable tag thusly:

```
GameObject[] usables = GameObject.FindGameObjectsWithTag("Usable")
    .Where(t => Vector3.Distance(t.transform.position, playerT.position) < useDistance)
    .ToArray();

```

This works as I intended, but I'd like to further narrow it down to the closest object in that array so the Linq query returns only the single closest GO. Linq is, however, a serious weak spot for me. Any thoughts on how that would look?

Thanks!

# Answer
> 1 votes
I think this post on "How to use linq to find the minimum" will give you some ideas on this. The `MinBy` extension method in MoreLINQ is likely your best bet, as there isn't a built-in method for what you want to do in `System.Linq`.

Doing this in pure LINQ is possible with LINQ methods like `Aggregate` or even `OrderBy` to sort, but I think it is likely to be a bit clunky or not performant compared to non-pure LINQ code.

This answer shows how to use `Aggregate` to accomplish finding the minimum item. For example, if you really wanted to use LINQ for this:

```
var usables = GameObject.FindGameObjectsWithTag("Usable");
var closestUsable = usables.Aggregate((minItem, nextItem) => Vector3.Distance(minItem.transform.position, playerT.position) < Vector3.Distance(nextItem.transform.position, playerT.position) ? minItem : nextItem)
// check if (closestUsable < useDistance), or add another `Where` method to keep it LINQ

```

However, this involves calling `Vector3.Distance` more often than necessary and it is also not very readable.

EDIT: This is how this would look like with `OrderBy` which is more readable, but runs in O(n log n) time due to the sorting:

```
    GameObject closestUsable = GameObject.FindGameObjectsWithTag("Usable")
        .OrderBy(t => Vector3.Distance(t.transform.position, playerT.position))
        .Where(t => Vector3.Distance(t.transform.position, playerT.position) < useDistance)
        .FirstOrDefault();

```

---
Tags: unity, c#, .net, linq
---


title: Data structure for a body

text:
# Question
Title: Data structure for a body
I'm writing a game in Java and am struggling to think how to appropriately manage character's bodies. My current structure is, in relevant part:

```
public class Character{
    private Body body;
    private Race race;
}

public class Body{
   private Leg rightLeg;
   private Leg leftLeg;
   //etc

   //the constructor takes a single Race argument and constructs a default
   //body for a member of that race

   public Leg getRightLeg(){
       return rightLeg;
   }

   ///etc
}

public class BodyPart(){
  //assorted instance variables and appropriate getters and setters
}

public class Leg extends BodyPart(){
  //leg specific stuff
}

public class AdvancedLeg extends Leg{
    //various different ways of improving body parts - magical enhancement
    //for example.  There are a number of these classes
    public AdvancedLeg(Leg l){
        //make leg better
    }
}

```

But this isn't working because each character must have the same basic body structure - 2 arms, 2 legs, one torso, one head, etc. Sure, I could have `public class QuadrapodBody` or similar (and make `Body` into an interface) but I certainly don't want to be getting in to `public class OneHeadTwoRightArmsOneLeftArmOneRightLegOneLeftLegBody implements Body`.

In essence I want to be able to flexibly assign body plans to each character and be able to manage `get`ting body parts without having to write a potentially infinite number of classes each with a subtly different set of instance variables and `getters`/`setters`.

Hopefully my question is clear enough.

# Answer
> 1 votes
Instead of a separate variable for each bodypart, as in

```
private Leg rightLeg;
private Leg leftLeg;

```

have a list of bodyparts:

```
private List<BodyPart> bodyParts = new List<>();

```

You can then use getters which return one bodypart (or all bodyparts) which fulfill a specific criteria. For example:

```
// returns the first Head of the creature, or null when the creature has no head(s)
public BodyPart getHead() {
      return bodyParts.stream()
                      .findFirst(part -> part instanceof Head)
                      .orElse(null);
}

// returns all legs, arms, tentacles and prehensile tails
public BodyPart[] getExtremities() {
      return bodyParts.stream.filter(part -> part instanceof Extremity).toArray();
}

```

---
Tags: java, data-structure, body
---


# Question
Title: LibGDX. How to fill background with shader?
I want to make background of my game like lava via perlin noise. I've read some tutorials but they were too old and some api calls aren't exist already. If I understand right in libgdx I need to create a runtime-generated texture (FrameBuffer) on x=0 and y=0 with width=`Screen width` and height=`Screen height` and apply shader to it.

I tried to do:

```
class A extends ApplicationAdapter {
    FrameBuffer   background;
    ShaderProgram shaderProgram;

    public void create() {
       background = new FrameBuffer(
           Pixmap.Format.RGBA8888,
           Gdx.graphics.getWidth(),
           Gdx.graphics.getHeight(),
           false
       );
       shaderProgram = /* stuff to pickup .vert and .frag */
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        background.begin();
        batch.setProjectionMatrix(
          new Matrix4().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight())
        );
        batch.begin();
        batch.setShader(shaderProgram);
        batch.end();
        background.end();
    }
}

```

My shaders are simple red fill programs:

```
//Vertex
attribute vec4 a_position;

uniform mat4 u_projTrans;

varying vec2 v_Pos;

void main() {
    gl_Position = u_projTrans * a_position;

    v_Pos = gl_Position;
}

//Fragment
#ifdef GL_ES
    precision mediump float;
#endif

uniform mat4 u_projTrans;

varying vec2 v_Pos;

void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

```

Nothing has been drawn. I expect that all my viewport become red

Function that picks up shaders is working, i tested at sprites

# Answer
> 1 votes
The first step in creating and using a shader in libgdx is to create the shader vert and frag components. You already have these in your question.

The second step is to create the shader in libgdx and that is done with this code:

```
ShaderProgram.pedantic = false;
ShaderProgram shader = new ShaderProgram(
        Gdx.files.internal("shaders/vert.vert"),
        Gdx.files.internal("shaders/frag.frag"));

```

I use .vert and .frag to identify my shader components but these are not required and you can use any naming convention you like.

Once you have crated your shader you should check that it has loaded and has compiled without error with:

```
if (!shader.isCompiled()) {
    System.err.println(shader.getLog());
    System.exit(0);
}

if (shader.getLog().length()!=0){
    System.out.println(shader.getLog());
}

```

You can now add your shader to your spritebatch:

```
SpriteBatch sb = new SpriteBatch();
sb.setShader(shader);

```

To make it only fill the background use the shader on one spritebatch and fill the screen then use another spritebatch to draw on top.

more information on shaders can be found:

gamedevelopment.blog

Cheat Sheet

https://thebookofshaders.com/

---
Tags: libgdx, shaders
---


# Question
Title: How can I properly detect my cars collisions using hitboxes?
I have created two car objects and their current speed is represented as the `len` variable.

This is the code:

Under Blue Car *Collision Event*:

```
if (place_meeting(x,y,obj_CarRed)) { // Checking Collision
    len = 0 //Current speed
    if (len < obj_carRed.len) { // Blue Car's current speed is greater than Red's
        myHP -= obj_carRed.len/2
    }
}

```

So I copied the code to the other object and replaced Red with Blue. When the Red car crashes into the Blue car, the Blue car takes damage because the Red car is traveling faster than the Blue car. But when the Blue car crashes into the Red car, the Red car won't take any damage.

Later, I thought about using a Hitbox and have it as a parent for both cars, but I don't know if it would mess up the collisions, and I don't know how to tell the hitbox that it's been created by Blue Car, or by Red Car. I don't know if I should make a new hitbox for each car or one for both.

# Answer
> 0 votes
The Game Maker engine executes every object event in order, and if more objects have the same event the overall execution order is due to the object's `depth`.

The reason Red Car is never damaged is likely because **Blue Car** executes its collision code first, and it sets its own velocity to `0` in line 2:

```
len = 0 //Current speed

```

So, when it's up to **Red Car** executing the collision script, when computing the amount of damage:

```
if (len < obj_carBlue.len) { // My current speed is greater than Blue
    myHP -= obj_carBlue.len/2
}

```

there will be always no damage for Red, because `obj_carBlue.len` is *already* set to 0 before this code is executed.

**Proposals**
To solve this problem, you must set `len` to 0 *after* computing amount of damage for both cars. A better option is create another object in charge of computing damage for each car and setting their speeds to 0 after updating their `hp` values; most game engines rely upon a collision response separated from the detection, and acting stricly *after* the detection has happened.

**A simpler fix**
On the other hand, if you want to stick with the *Collision Event* alone you can change your code as follows:

`obj_CarBlue`'s *Collision Event* with `obj_CarRed`:

```
if (len < other.len) { // My current speed is greater than Red
    myHP -= other.len/2
} else {
    other.myHP -= len/2
}
len = 0
other.len = 0

```

First, we get rid of `place_meeting()` because we are inside the *Collision Event* and the collision is certaintly happening. Then, we use the special keyword `other` to make a reference to the very Red Car we are colliding with instead of a generic one: if we reference `obj_RedCar.something` we are trying to read the variable `something` of any instance among all Red Cars. Inside the *Collision Event* the keyword `other` tells us what is the particular **instance** the collision occured with.

The code above deals with the collision at once for both cars, you can copy/paste it for Blue and Red cars and it will still work because after the first execution both cars' velocities will be set to 0, so that the code is duplicated but its effects aren't.

---
Tags: collision-detection, game-maker
---


title: Object pooling with collisions in Unity

text:
# Question
Title: Object pooling with collisions in Unity
I am trying to create doodle jump like game with object pool for platforms. I have created an empty object with box 2D collider attached to it. This object moves with player and should be gathering platforms which exit its collider, but it isn't.

```
public class PoolGrabber : MonoBehaviour {

[Tooltip("Field for game manager.")]
[SerializeField]
private GameObject gameManager;

private void Awake()
{
    gameManager = GameObject.FindGameObjectWithTag("GameManager");
}

private void OnTriggerExit2D(Collider2D collision)
{
    if(collision.tag == "PooledObject")
    {
        collision.gameObject.SetActive(false);
        gameManager.GetComponent<LevelGenerator>().objectPool.Add(collision.gameObject);
    }
}

```

It also doesn't work with OnTriggerEnter2D.

I have also tried

```
private void OnBecameInvisible()
{
    gameObject.SetActive(false);
}

```

on a platform. Doesnt work either.

---

I have discovered that for all those methods above object required to has Rigidbody2D component. But what if I don't want any phisycs calculations to be handled. I don't need physics on those platforms at all. Also, an object doesn't become invisible if you see it in the editor window. Isn't very convenient.

# Answer
You need a Rigidbody2D on one of the two colliding objects (moving objects with colliders always must have one). If you don't want the Rigidbody2D to be affected by forces but instead to be manually controlled you must set it to kinematic. The reasons to have a rigidbody on moving objects are two. The first one is that a moving collider without a rigidbody causes performance troubles for Unity. The second one is that if 2 objects are colliding and only the static one have rigidbody it is very likely it to be in "sleep" mode (for performance reasons) and so the collision will not be detected. There is an option on the rigidbody to disable the "sleep" mode.
> 1 votes

---
Tags: unity, 2d, collision-detection, unityscript, object-pools
---


# Question
Title: What's the difference between Raytracing and Physically-based-rendering?
I know raytracing is a technique based on the route calculation done by the light, following the rays through the interaction with the surfaces, and that Pbr is a *collection* of render techniques that are more or less based on the theory which matches that of the physical world, aiming to mimic light in a physically plausible way.

Is it possible to implement both into a Rendering engine? What's the difference?

# Answer
Yes, you can... sort of.

DirectX announced a support for hardware based ray-tracing a couple of weeks ago and Epic Games (creators of Unreal Engine) have already made a demo with the models from the new Star Wars movies (check it out here).

This can make reflections much easier to create and should eliminate cube map based rendering almost completely.

There is a catch though, it is very slow. They had to run it on a 1280p screen with a Titan X to get 60FPS, which is a big problem considering how many people have 4k screens.

So yes, it's possible, but we'll still have to stick to cheating our way through different rendering techniques for a while and it's unlikely it will replace rasterizing very soon.
> 1 votes

# Answer
There are two different aspects of a renderer in play here:

1. How do we determine **which bits of surface are visible** on each screen pixel (including direct visibility or reflection), and what lighting those surfaces receive? Here we have two families of techniques:

* **Raytracing & Path Tracing** renderers do this by modelling the way rays travel through the scene, including rays through each screen pixel and rays from each light source, seeing where they strike scene geometry first, and where they bounce to.
    * **Rasterizing** renderers do this by breaking surfaces into small pieces like triangles, and projecting them onto the screen, using a depth buffer to handle layering. For determining whether a point is lit or in shadow, we do the same thing from the light's point of view, saving the result to a "shadow map" texture we can sample when rendering the camera view.
2. Now that we know what surface we're drawing and what lighting it receives, how do we **colour it so that its material appears to respond to light** in the right way?

* Older renderers, both raytracing and rasterizing style, relied on simple/idealized models of how materials bounce light, like perfect cosine Lambertian reflectance. That's why when you look at older 3D renderings, even raytraced output tends to have a slightly surreal, plastic-y appearance. The rays are hitting the right spots, but there's something just a bit *off* about how the material interacts with that light. Real world materials are more complicated.
    * In **physically based renderers**, the materials' response to light is grounded in more sophisticated models and often direct measurements of real materials, including things like microfacets, surface anisotropy, fresnel effects, energy conservation, etc. See this earlier answer for some examples of how this affects the appearance of rendered objects and how artists work with them. This work started in offline/ray- & path-traced rendering for films, and more recently made its way into games' rasterizing renderers. The use of these more sophisticated models helps the shading of objects look more natural and accurate over a range of lighting conditions.

So yes, you can combine physically based shading with a raytracing renderer, as they relate to different parts of the problem of rendering a scene.
> 5 votes

# Answer
Raytracing works in some fashion that light does as it travels trough the world, by casting rays, bouncing off surfaces/passing trough them. Only that rays are cast from the eye/camera and tries to find the intersection between a surface and a light source and returns the result of the path. It's actually closer to a physical simulation than PBR techniques for games has it in its name. And to get a good quality image you need to cast a good amount of rays. Which is computational heavy. Raytracing by itself does not mean PBR though. Next to CPU you also need a lot of Ram for this.

PBR for games as is, is similar to any other traditional rendering technique. Where triangles are clipped and rasterized first and the data between vertices interpolated in each shader stage. After just rasterizing the triangles we already have the fragments to work with. The output pixel is calculated by using some PBR principles by combining Albedo, Metallic, roughness values with additional light settings( which can be precomputed/baked for static objects).The name Physical Based Rendering simply implies that it is using some principles of actual physics model. However it does not mean it actually is, as in it just borrows a few ideas but not the exact model. Many things in game render techniques come down to faking it.

Actually simulating lights bouncing off surfaces is very computationally expensive. And these new raytracting apis for gpus are just one step closer to achieving realistic visuals.

wiki article for ray tracing concept

This one is not directly on game graphics, it's still relevant
> 0 votes

---
Tags: opengl, raytracing, pbr
---


# Question
Title: How to adjust objects' coordinates and scale for different device resolutions?
I have a bunch of objects which are generated in specific coordinates, let's say in a range of -5 to +5 on the X axis. I came up with these numbers because of camera size I have in Unity editor.

What if I run my game on few random devices with different aspect ratios and resolutions? Will Unity adjust my game automatically so everything fits perfectly, or should I do it manually somehow? And if so, how?

# Answer
This depends on how you've authored the objects.

* 3D objects and 2D sprites positioned in your scene's worldspace will not move, scale or change *their worldspace transformations* no matter what happens to the display screen/window.

+ **BUT:** These objects are viewed through a **Camera**, and the camera's view is mapped to the screen. That mapping will change as the screen/window size changes.

    By default, Unity will keep the camera's *vertical* FoV or orthographic height the same, meaning that you'll see the same portion of your game world from the top to bottom of the screen. So if your objects were 60 pixels tall on a screen 1080 pixels in height, they'll be 40 pixels tall when displayed on a 720-pixel-high screen. The objects didn't move or shrink in your scene, so all your gameplay metrics and physics will work identically: they're just being displayed on fewer pixels.

    The *width* of the camera's view is, by default, allowed to grow or shrink to match the aspect ratio of the screen. So a player on a wider screen will see more of your scene to the left and right. If you haven't placed any objects there, they'll see blank space, because Unity doesn't know what you might want to put there instead - you'll have to tell it.
* UI objects inside a Canvas element that's set to Screenspace - Camera or Screenspace - Overlay will be repositioned / sized according to their anchors when the dimensions of the containing canvas's viewport change.

This lets you, say, make a UI button that's always in the bottom-right corner, no matter how tall or wide the window/screen is.

The canvas and UI components expose a number of controls for you to decide exactly *how* you want this scaling to happen - whether you want to preserve sizes proportional to the width or height, or preserve the native pixel size of the elements, etc.

If you like the scaling behaviour described above, you're done. If not, then you'll need to define what "proper" scaling behaviour is for your game. Some examples:
> 4 votes

# Answer
It will adjust everything automatically for different resolutions if the aspect ratio is the same. If the aspect ratio is different, everything will still be scaled automatically, but you might see a little bit more or less of the game at the edges of the screen.

To see this for yourself, you can try resizing the game view window in the Unity editor and setting different aspect ratios in the game view control bar to see how your game behaves.

If you want to enforce a specific aspect ratio, this post illustrates the problem and also has potential solutions, such as enforcing a specific aspect ratio in the project settings, or adding a script to resize the camera viewport to fit that aspect ratio with a pillarbox or letterbox effect.
> 1 votes

---
Tags: unity, camera, mobile, resolution, aspect-ratio
---


# Question
Title: If a game is made for Windows or MacOS, and sold for profit, is Microsoft or Apple entitled to royalties, even if it's sold on a different website?
I.e. sold on some website some game developer made, and **NOT** sold on Apple Store or Microsoft Store.

2) *Also*, for any game made and sold for their platform, does Apple or Microsoft *look at the game/app content*, and decide whether they want that game/app to exist for their platform or not? Again, this for the case of where the game/app is NOT sold on the Apple Store or Microsoft Store.

3) same questions, but for game consoles? e.g. Nintendo, Sony, etc.

EDITED: I ask because... well... sometimes I wonder if a certain game has content which is too inappropriate. So I'm wondering ... what companies looked at these games and said they were okay when maybe they should've said no.

# Answer
No, Microsoft of Apple generally do not take royalties from software just because it runs on their desktop operating systems. They only take royalties if they are distributed through their own distribution channels.

They also do not do any quality control or censorship for such software. Creating a program which runs on Windows or macOS is trivial. There are plenty of free and paid software development tools around to do that. If you use Visual Studio Community Edition to create a `microsoft_sucks.exe`, you can upload it to the Internet and any Windows user can download and run it without Microsoft's approval. However, if the software does something harmful, then it might end up getting classified as malware by Windows Defender. Any Windows user with Windows Defender enabled will then get a big, red warning when they try to run it. But they can choose to ignore that warning if they want to.

Game consoles, however, are traditionally walled gardens. The manufacturers of almost all game consoles take special precautions to prevent their consoles from running any software not approved by them. This is part of their business model. Game consoles are usually sold at prices below their manufacturing cost. The manufacturers make their profit from royalties on any games sold for their consoles. Console games usually also have to pass the manufacturers quality control and content guidelines. That's why you see no explicitly pornographic games on most game consoles, while it is a flourishing niche market for PC.

The reason for this cultural divide between desktop computers and game consoles is that while game consoles are usually used "just" for gaming, desktop computers are used in a far more versatile manner. People want to run all kinds of applications on them, some of them extremely specialized and obscure. In fact the majority of software development which happens around the world is to create software intended for just one organization, or even just for one specific computer doing one very specific task. Microsoft can not curate all these different applications, nor would they want to.

So they allow anyone to develop, distribute and run any software they want. The only limitation to the software you are allowed to release are your local laws.
> 7 votes

# Answer
Apple and Microsoft only have licensees for their closed ecosystems. For Microsoft, that's the windows store and the Xbox platforms. For Apple, that's just iOS (as far as I know).

Consider Steam, itco.io, GOG, Desura, and the like. These are sales platforms that run on Windows, Linux, and Mac OS. If Valve, CD PROJEKT RED and others had to pay to put their shops on Windows, and then also pay Microsoft for putting the games it sells onto Windows too, then that would be quite an accounting nightmare. This is also why there is no Steam on PlayStation, or Xbox.

The only case I know of where an app has been able to provide its own software from inside a closed ecosystem has been the success of the Amazon app store inside Google's platform.

As to Quality control, it varies massively.

Consoles such as PlayStation, XBox, and Nintendo devices, have very strict guidelines, and go through an official process to be approved to go in their stores.

Apple has a much more lenient process for the App Store. The same seems to go for Steam, and other Desktop PC store fronts.

Android is pretty much "check for viruses and other dodgy stuff and publish."

Publishing a game without a middleman or vendor gives you the freedom to decide for yourself, and can often still lead to good quality software (for example, Adobe doesn't go through a certification process, but no-one is going to say their software is half finished and untested).

As to costs and the publisher cuts, some of that stuff is corporate secret, so not safe to divulge, but there's a lot of public knowledge that states numbers around 30% cut on the secretive platforms.
> 2 votes

# Answer
As far as I know, any game that is made for any platform but is sold on a "random" website (or one owned by you) has no relation to Microsoft or Apple (pay-wise). In theory they earn money because more games for a platform means more sales for that platform. They can only claim money if you decide to upload in their app-stores.

Also, considering that you supply only binaries, there's not much for any company to "look at". There are tools that can check binaries for malicious activities, but that's pretty much as far as it goes.

Note that this is different when you want to publish a game on a marketplace (Google Play or Apple's App Store etc). I know that for Google Play, you upload your game, and Google runs some automatic check on it to make sure it doesn't do anything harmful. After 2-3 days your app gets approved and published online. I've heard Apple does something very similar, but there is some human-interaction involved, to ensure higher quality (although I could be wrong).

Although I have no experience with developing on game consoles, I assume it's a similar thing. If you create a game and upload it on your personal website, nobody bothers you, if you want to publish it on Xbox live or Nintendo's store, you probably have to be approved.

In the end, if you make a game that is "mediocre" quality but you want to see it live, don't hesitate to upload it. Worst case scenario it gets rejected, and you can work to improve yourself.

If however you are asking because your game has content which you are not sure is legal to publish (gambling or nudity etc) then each store has its own rules to deal with such content.
> 1 votes

---
Tags: legal, business, distribution, platform, sales
---