# Question
Title: Simulating a real camera's perspective projection
I'm trying to simulate a real camera's perspective projection of straight, parallel lines running along the ground (one-point perspective) by mapping the real-world 3D coordinates of the lines to 2D screen coordinates. Suppose the camera's tilt angle is known, is there a way to calculate the slopes/coordinates/expression of these lines projected on to the 2D plane? Which parameters of the camera are needed?

My understanding is that when the camera is tilted, the vanishing point is effectively shifted. But does tilting the camera cause the same changes in the perspective of the lines as moving the camera lower to the ground (closer to the lines)?

# Answer
> 3 votes
> But does tilting the camera cause the same changes in the perspective of the lines as moving the camera lower to the ground (closer to the lines)?

No, it is not the same. To angle the camera to look below the horizon is not equivalent to move the camera closer to the ground while remaining level with the ground. In fact, tilting the camera will offset things vertically by some amount, including the vanishing point. On the other hand, changing the position of the camera will change the slope of the lines.

With that said, thinking in terms of vanishing point is not the best approach. Vanishing point are an emerging property of the geometry of objects and perspective.

And I mean by that, that a different geometry (I mean different shapes and orientations, not different metrics, nor different topologies) may result in different apparent vanishing points※, which may even be exploited for optical illusions.

※: I am claiming that the main difference between one-point, two-point and three-point perspective is the shape and orientation of the object, and not anything about the math behind it.

---

I need to define the *principal* of the camera. I prefer to refer to it as the principal line of sight. You can find it with other names such as "princial axis", "principal ray", etc.

It is the line that goes from the position of the camera, to the point that is projected at the center of the image. *It is forward vector of the camera if you are working on a game engine.*

---

If you have your camera level with the ground (a.k.a the ground is parallel to the principal of the camera), the horizon will stay at the center of the image.

You are probably familiar with this effect. It is often worded as saying that the horizon on the picture is at the height of the eyes of the viewer:

*The vanishing point and horizon line are at the height of the eyes of the viewer.*

We are used to have a camera that is level with the ground. However, that is not always the case.

---

Now, we say we have a one-point perspective when the scene has mainly lines that are parallel or perpendicular to the principal of the camera. In this case you will have a single vanishing point at the center of the image.

*A cube depicted in one point perspective.*

Notice in the image that the depicted cube only have lines parallel or perpendicular to the principal of the camera. As a result it has a single vanishing point at the center of the image.

Then, when you tilt the camera. The scene no longer have mainly lines that are parallel or perpendicular to the principal of the camera... because changing the orientation of the camera changes the principal of the camera. As a result you end up with a two point perspective. That is, it will have two main vanishing points.

*A cube depicted in two point perspective.*

In this second image, the cube has been rotated. It no longer have lines that are parallel or perpendicular to the principal. In fact, if you group lines by how much they change in depth you end up with three sets, of which one does not change at all (these lines remain perpendicular to the principal of the camera). Thus, it has two vanishing points.

Notice also that the lines that do not change in depth will remain parallel instead of going to a vanishing point. We can say that lines that lie on planes perpendicular to the principal of the camera (that is, the normal of the plane matches the principal of the camera) are in true size, will not appear distorted by perspective (just scaled) and will not have a vanishing point.

If we now rotate the camera to an angle where there are no longer lines perpendicular to the principal of the camera we end up in three point perspective.

*A cube depicted in three point perspective.*

Notes:

* All of these emerge from the same math we use to make a perspective projection.
* It is possible to create a projection starting by defining the vanishing points for the main axis of an scene (it could be by placing them at infinity), doing so will allow for projections that do not match how cameras work.
* An image may appear to have more than three vanishing points. This is due to the shape and orientation of the object it contains.
* Isomorphic, if you are curious, would place the vanishing points for the main axis of the scene in an equilateral triangle. You can get it by using the angles 45º and 35.264º (aprox)
* There are also skwed projections (such as the oblique projections), they are off topic here.

---

Our objective is to capture the behaviour of a pinhole camera. We are disregarding depth of field, optical and chromatic aberrations. That is, we only care about the geometry.

Our pinhole camera has:

* Focal length
* Position
* Orientation

Notes:

* The Focal length of the pinhole camera is the depth of the *camera* (from Latin camera "a vault, vaulted room").
* The pinhole camera also have an apperture size. The apperture affects depth of field (what is the distribution of things in focus) and exposure, it and may introduce some aberrations such as Vignetting. We do not care of any of that.

The first step is to transofrm the world space into camera space. That is, we need to do a coordinate system transformation such that the camera ends up at the origin, looking down the z axis and with the x and y axis corresponding to the camera Roll.

Once you have your system in camera space, doing an orthogonal projection is trivial: take the x and y coordinates, scale and offset to match the viewport.

However, instead we want perspective. Thus, what we are going to do is scale things depending on the distance to the camara (their position on the z axis).

---

Consider a transformation of the form:

```
(x, y, z) = (x, y, z) * func(z)

```

Where `*` denotes scalar product.

Note: remember that we do not plan to use the z coordinate.

---

Notice that the pinhole model yields a flipped image. While we can just invert the coordinates after we are done. It is simpler to think of it as placing the projection plane in front of the camera instead of behind. The model now looks like this:

Ah, geometry, we can solve this. We can separate the axis, and the result will be a similar triangle problem.

Since we have similar triangle, it follows that:

```
x'/f = x/z

```

Where `x'` is the image x coordinate, `x` is the camera space x coordinate, `f` is he focal length, and `z` is the camera space z coordinate.

It follows that:

```
x' = x*f/z

```

Thus:

```
(x, y, z) = (x, y, z) * f/z

```

---

Alright, but you do not want to work with points, you want to work with lines...

Let us say we have - in camera space - a line running along the floor (`y = 0`) in one-point perspective (`x = k`). In this case `x' = k*f/z` and `y' = 0`.

Alright, now let us define a line tilted vertically with a knonw slope `m` and starting at `c` below the camera. For this line we have `y = z*m-c` and `x = k`. We need to define it in parametric form:

```
x = k
y = t*m-c
z = t

```

And transform:

```
x' = k*f/z
y' = (t*m-c)*f/z
z' = t*f/z

```

Replace z:

```
x' = k*f/t
y' = (t*m-c)*f/t
z' = t*f/t

```

Simplify:

```
x' = k*f/t
y' = m*f - c*f/t
z' = f

```

Let us try to get a nominal line equation:

```
x' = k*f/t

=>

x'/k = f/t

---

y' = m*f - c*f/t

=>

y' = m*f - c*(x'/k)

=>

y' = m*f - x'*c/k

=>

y' = - x'*c/k + m*f

```

---

Demo 1

The following code implement the line equation we figured out. It will render 5 parallel lines, with an offset of 0.1 on the x axis among them. This will ease to visualize how it works.

I am using a library designed for plotting math functions. It takes as input the function as a string. I did this so that it is clear on the code when I am using the function, and that - in fact - I am using the function I claim to be using. In general, this library reduces the amount of code I need to draw the lines based on the line equations without making then unrecognizable. As a side effect, the code is slow.

Important: This code is slow.

```
let draw = function() {
  // y' = - x'*c/k + m*f
  let c = $('#c').val();
  let k = $('#k').val();
  let m = $('#m').val();
  let f = $('#f').val();
  if (c === '' || k === '' || m === '' || f === '') {
    return;
  }
  k = parseFloat(k);
  let fna = 'x*(' + c + ')/(' + k + ') + (' + m + ')*(' + f + ')';
  let fnb = 'x*(' + c + ')/(' + (0.1 + k) + ') + (' + m + ')*(' + f + ')';
  let fnc = 'x*(' + c + ')/(' + (0.2 + k) + ') + (' + m + ')*(' + f + ')';
  let fnd = 'x*(' + c + ')/(' + (-0.1 + k) + ') + (' + m + ')*(' + f + ')';
  let fne = 'x*(' + c + ')/(' + (-0.2 + k) + ') + (' + m + ')*(' + f + ')';
  $('#fn').html('y = ' + fna);
  functionPlot({
    target: '#plot',
    data: [{
        fn: fna
      },
      {
        fn: fnb
      },
      {
        fn: fnc
      },
      {
        fn: fnd
      },
      {
        fn: fne
      }
    ]
  })
};
let initialize = function() {
  $('#draw').click(draw);
  $('input[type=number]').change(draw).keyup(draw);
};
$(document).ready(initialize);
```

```
input {
  width: 18%;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://wzrd.in/standalone/function-plot@1.18.1"></script>
<input type="number" id="k" placeholder="x" step="0.1">
<input type="number" id="c" placeholder="camera elevation" step="0.1">
<input type="number" id="m" placeholder="slope" step="0.1">
<input type="number" id="f" placeholder="focal length" step="0.1">
<input type="button" id="draw" value="draw"> Formula: <span id="fn"></span>
<div id="plot"></div>
```

I suggest start by setting a slope of 0, a focal length of 1, some positive camera elevetion and then move x and camera elevation. You may then move to play with slope and focal length to see how they affect the picture.

Note:

* Camera elevation here is the vertical distance from the lines to the camera, not an angle. To manipulate the inclination use slope.
* If you only move x and elevation, you are not changing the orientation, and thus the vanishing point stays fixed.
* If you put elevation at 0, the camera is on the same plane as the lines. At this point, all lines are horizontal.
* This library will not plot equations that result in division by 0 when evaluating. Games will often define lines with position and director vectors instead of using line equations to avoid dealing with this problem.

Important: This code is slow.

---

For the sake of it, let us work out how to add horizontal lines.

I will define this lines with `z = a`, `y = -c` and `x = t`:

```
x = t
y = -c
z = a

=>

x' = t*f/z
y' = -c*f/z
z' = a*f/z

=>

x' = t*f/a
y' = -c*f/a
z' = a*f/a

=>

x' = t*f/a
y' = -c*f/a
z' = f

```

Note: as we can see `y` is constant.

Let us do it more interesting. Let us define these horizontal lines to be on the same plane as the lines we defined before:

```
x = t
y = a*m-c
z = a

=>

x' = t*f/z
y' = (a*m-c)*f/z
z' = a*f/z

=>

x' = t*f/a
y' = (a*m-c)*f/a
z' = a*f/a

=>

x' = t*f/a
y' = (a*m-c)*f/a
z' = f

=>

y' = (a*m-c)*f/a - (a*m-c)*f/a

=>

y' = a*m*f/a - c*f/a

=>

y' = m*f - c*f/a

```

---

Demo 2

Same as above, but I have added horizontal lines (they are all pink).

```
let draw = function() {
  // y' = - x'*c/k + m*f
  let c = $('#c').val();
  let k = $('#k').val();
  let m = $('#m').val();
  let f = $('#f').val();
  if (c === '' || k === '' || m === '' || f === '') {
    return;
  }
  k = parseFloat(k);
  let fna = 'x*(' + c + ')/(' + k + ') + (' + m + ')*(' + f + ')';
  let fnb = 'x*(' + c + ')/(' + (0.1 + k) + ') + (' + m + ')*(' + f + ')';
  let fnc = 'x*(' + c + ')/(' + (0.2 + k) + ') + (' + m + ')*(' + f + ')';
  let fnd = 'x*(' + c + ')/(' + (-0.1 + k) + ') + (' + m + ')*(' + f + ')';
  let fne = 'x*(' + c + ')/(' + (-0.2 + k) + ') + (' + m + ')*(' + f + ')';

  // ---

  let fnxa = '(' + m + ')*(' + f + ')-(' + c + ')*(' + f + ')/(' + 1 + ')';
  let fnxb = '(' + m + ')*(' + f + ')-(' + c + ')*(' + f + ')/(' + 2 + ')';
  let fnxc = '(' + m + ')*(' + f + ')-(' + c + ')*(' + f + ')/(' + 3 + ')';
  let fnxd = '(' + m + ')*(' + f + ')-(' + c + ')*(' + f + ')/(' + 4 + ')';
  let fnxe = '(' + m + ')*(' + f + ')-(' + c + ')*(' + f + ')/(' + 5 + ')';
  let fnxf = '(' + m + ')*(' + f + ')-(' + c + ')*(' + f + ')/(' + 6 + ')';

  $('#fn').html('y = ' + fna);
  functionPlot({
    target: '#plot',
    data: [{
        fn: fna
      },
      {
        fn: fnb
      },
      {
        fn: fnc
      },
      {
        fn: fnd
      },
      {
        fn: fne
      },
      {
        fn: fnxa, color: 'pink'
      },
      {
        fn: fnxb, color: 'pink'
      },
      {
        fn: fnxc, color: 'pink'
      },
      {
        fn: fnxd, color: 'pink'
      },
      {
        fn: fnxe, color: 'pink'
      },
      {
        fn: fnxf, color: 'pink'
      }
    ]
  })
};
let initialize = function() {
  $('#draw').click(draw);
  $('input[type=number]').change(draw).keyup(draw);
};
$(document).ready(initialize);
```

```
input {
  width: 18%;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://wzrd.in/standalone/function-plot@1.18.1"></script>
<input type="number" id="k" placeholder="x" step="0.1">
<input type="number" id="c" placeholder="camera elevation" step="0.1">
<input type="number" id="m" placeholder="slope" step="0.1">
<input type="number" id="f" placeholder="focal length" step="0.1">
<input type="button" id="draw" value="draw"> Formula: <span id="fn"></span>
<div id="plot"></div>
```

Important: This code is slow.

---

Final note:

If anybody out there is thinking, "hmm, I could make a 3D engine using this", let me tell you... I have been there, when I was young and naive. First off all, 3D engines use matrix transformations for all this stuff and for good reason. So if you want to do something like that (say, for example, to make a 3D game using excel, or some other cute use case like that) improve your knowledge of linear algebra first. Second, if you want to know how 3D graphics works, go learn about pixels and triangles. And third, if you want to develop 3D video games, you do not need to figure out this stuff yourself… all modern 3D solutions have matrix transformation math embedded in already for you to use. If you do not want to use a game engine (such as Unity) go learn OpenGL or something.

---
Tags: camera, simulations, perspective
---


# Question
Title: How to use Particle start color in unity3d 2017
I want to create a particle(prefab) and use another object color to change those particle's color but it seems everything is changed and I don't know the new method to use it.

Here my code:

```
 GameObject breakpart = Instantiate (smoke, gameObject.transform.position , Quaternion.identity) as GameObject;

 breakpart.GetComponent<ParticleSystem>().startColor = gameObject.GetComponent<SpriteRenderer>().color;

```

So how can I fix it?

# Answer
Particle Systems in Unity have modules to keep various bits of related data together. The start color is in the Main module.

Set the `startColor` property:

```
var ps = breakpart.GetComponent<ParticleSystem>();
var main = ps.main;
main.startColor = gameObject.GetComponent<SpriteRenderer>().color;

```
> 0 votes

---
Tags: unity, particles
---


# Question
Title: Efficient minimum distance between two axis aligned squares?
I have two 2D arbitrarily-positioned axis-aligned squares.

I need to find the minimum distance between those squares – i.e. if you were to draw them, what's the length of the shortest line you could draw that would touch both?

Now, I have an algorithm that works. The problem is it's quite slow. Here it is:

```
function min_distance(a_left, a_right, a_top, a_bottom, b_left, b_right, b_top, b_bottom) {
    if (a_left <= b_right && a_right >= b_left && a_top >= b_bottom && a_bottom <= b_top) {
        return 0;
    } else if (a_left <= b_right && a_right >= b_left && a_top >= b_bottom/* && a_bottom <= b_top*/) {
        return a_bottom - b_top;
    } else if (a_left <= b_right && a_right >= b_left/* && a_top >= b_bottom*/ && a_bottom <= b_top) {
        return b_bottom - a_top;
    } else if (a_left <= b_right/* && a_right >= b_left*/ && a_top >= b_bottom && a_bottom <= b_top) {
        return b_left - a_right;
    } else if (/*a_left <= b_right && */a_right >= b_left && a_top >= b_bottom && a_bottom <= b_top) {
        return a_left - b_right;
    } else if (/*a_left <= b_right && */a_right >= b_left/* && a_top >= b_bottom*/ && a_bottom <= b_top) {
        let a = a_left - b_right;
        let b = b_bottom - a_top;
        return Math.sqrt(a*a+b*b);
    } else if (a_left <= b_right/* && a_right >= b_left && a_top >= b_bottom*/ && a_bottom <= b_top) {
        let a = b_left - a_right;
        let b = b_bottom - a_top;
        return Math.sqrt(a*a+b*b);
    } else if (a_left <= b_right/* && a_right >= b_left*/ && a_top >= b_bottom/* && a_bottom <= b_top*/) {
        let a = b_left - a_right;
        let b = a_bottom - b_top;
        return Math.sqrt(a*a+b*b);
    } else if (/*a_left <= b_right && */a_right >= b_left && a_top >= b_bottom/* && a_bottom <= b_top*/) {
        let a = a_left - b_right;
        let b = a_bottom - b_top;
        return Math.sqrt(a*a+b*b);
    } else if (a_left <= b_right/* && a_right >= b_left && a_top >= b_bottom && a_bottom <= b_top*/) {
        return b_right - a_left;
    } else if (/*a_left <= b_right && a_right >= b_left && a_top >= b_bottom && */a_bottom <= b_top) {
        return b_top - a_bottom;
    } else if (/*a_left <= b_right && a_right >= b_left && */a_top >= b_bottom/* && a_bottom <= b_top*/) {
        return a_top - b_bottom;
    } else if (/*a_left <= b_right && */a_right >= b_left/* && a_top >= b_bottom && a_bottom <= b_top*/) {
        return a_right - b_left;
    } else { unreachable() }
}

```

This can also handle rectangles, whereas I only need squares.

**Are there any known algorithmic tricks to calculate this substantially faster?**

# Answer
By far the slowest part of this algorithm would be the **square root**. Try to avoid it if you can, and deal with the squared distance directly. For example, if you're comparing distances, the results will be the same if you compare squared distances.

Having said that, here's an alternate formulation of the distance function.

Suppose we have two squares sitting some distance apart, shown in red and blue. The shortest distance is equivalent to the length of the diagonal in the inner rectangle. This rectangle can be found by taking the outer rectangle (the smallest rectangle that covers both squares) and subtracting its dimensions by that of both squares. For our purposes, it doesn't matter where the inner rectangle is positioned, so we could just represent it as a pair of width and height.

So the pseudocode is:

```
Given square_a, square_b
rect_outer = (
    min(square_a.left, square_b.left),
    min(square_a.top, square_b.top),
    max(square_a.right, square_b.right),
    max(square_a.bottom, square_b.bottom)
)
inner_width = rect_outer.width - square_a.width - square_b.width
inner_height = rect_outer.height - square_a.height - square_b.height
min_distance = sqrt(inner_width^2 + inner_height^2)

```

Note that there are special cases, where the inner rectangle happens to have negative width, height, or both. Then we don't care about that dimension, and set it to zero. For example, given this arrangement:

The `inner_width` will come out negative after the calculation. In this case the min distance is just `inner_height`. So we can deal with this by clamping the `inner_width` to 0 and greater. Similarly we do the same thing with `inner_height`. This conveniently handles the cases where the two squares overlap.

```
Given square_a, square_b
rect_outer = (
    min(square_a.left, square_b.left),
    min(square_a.top, square_b.top),
    max(square_a.right, square_b.right),
    max(square_a.bottom, square_b.bottom)
)
inner_width = max(0, rect_outer.width - square_a.width - square_b.width)
inner_height = max(0, rect_outer.height - square_a.height - square_b.height)
min_distance = sqrt(inner_width^2 + inner_height^2)

```

This code is a bit easier to read than yours, but I don't think it's substantially faster, as it's doing the same calculations and checks.
> 10 votes

---
Tags: 2d, collision-detection, performance, geometry
---


# Question
Title: Possible bottlenecks when rendering sprites programmatically in Unity using Graphics.DrawMesh()?
I'm currently trying to render sprites in Unity without using a sprite renderer component.

So far using Graphics.DrawMesh() I have this:

```
public void Draw(Sprite sprite, Vector3 pos) {
    Material mat = new Material(spriteMaterial) {
        mainTexture = sprite.texture
    };
    Mesh mesh = new Mesh() {
        vertices = Array.ConvertAll(sprite.vertices, x => (Vector3)x),
        triangles = Array.ConvertAll(sprite.triangles, x => (int)x),
        uv = sprite.uv
    };
    Graphics.DrawMesh(mesh, Matrix4x4.TRS(pos, Quaternion.identity, sprite.bounds.size), mat, 0);
    }

```

Everything was working fine except after doing a test with a about hundred or so sprites my fps went down to around 30.

So the question is, is this normal? If not, what potential bottlenecks could there be?

# Answer
I think it's bacause of this:

```
    Material mat = new Material(spriteMaterial) {
    mainTexture = sprite.texture
};

```

It just creates a new material to each sprite. This means each game object has it's own material, and Unity cannot apply dynamic batching, so it produces 1 draw call for each game object. See if you have lots of draw calls in the statistics panel (in Game window). If you have so many draw calls and 0 "saved by batching" draw calls, maybe this is the problem.

To solve it, instead of creating a new material for each sprite, just create only 1 material, and use it for all of them.
> 1 votes

---
Tags: unity, rendering
---


# Question
Title: How are Roguelike/Bullet Hell mechanics stored in Unity?
I'm going to be creating a roguelike bullet hell game wherein the play will be a bullet hell game, but you will be traveling between "rooms" wherein the action takes place. The "rooms" will be randomly generated like in roguelikes such as *The Binding of Isaac*, but with bullet hell play similar to *Touhou* or *Batsugun*, with a possible twist. It will be similar to *Enter the Gungeon*, but there will be some differences.

I'd like to know how Unity will deal with storing possibly thousands of different "rooms" and generating these each time, along with the enemies and bullets these enemies will begin to shoot after you enter the room. Only one room will be visible at a time.

How would Unity deal with mapping possibly thousands of rooms, and will it be able to store this while generating bullet patterns? I know that in classic bullet hell arcade games, when there were many bullets on the screen, the game tended to slow down because of hardware limitations.

# Answer
The trick behind these roguelike mechanics is that typically you don't store much at all.

The shape/contents of each room are determined by an algorithm that's generally seeded with the position of the room, and possibly a unique key for each "new game" session.

This algorithm, which can take many forms, is effectively a deterministic machine: put the same numbers in, and you'll get the same room out. (But put in different numbers, and you'll get different rooms!) So you don't need to store the contents of the room to be able to re-draw it if the player doubles back. Just put the same position in again and you'll automatically get the same room.

This is how early roguelike and procedural games managed to pack such immense explorable worlds onto the tiny floppy drives and limited RAM of early PCs.

If the player can make changes to the rooms, then you do need to store those changes to be able to reproduce them faithfully. This storage generally grows linearly with play time, and can be discarded when the player hits a permadeath point, so even if it's conceptually unbounded it can usually be kept quite modest.

You can tune how much you need to store by the design of your mechanics: if the room repopulates whenever the player leaves it without clearing it entirely, then you only need a single bit of storage per room: a "cleared" flag. Or if the player's changes are limited to discrete cases: killed enemy/bombed breakable wall, you can similarly keep it scoped to some worst-case number of bits per visited room. Or you could have the player's changes "age out" after they move more than 10 rooms or 30 minutes' game time away, allowing complex state tracking with a limited time horizon. Games like Minecraft, which allow much deeper player customization of visited chunks, correspondingly have much more intense storage needs.

As for how "Unity" deals with this: it handles it however you tell it to. It doesn't have a built-in roguelike bullet hell component you're forced to use. So you can script whatever custom system you find will meet your game design/player experience goals and performance needs on your target hardware. Generating the next room's contents, discarding old rooms, storing what you deem important along the way, all of that is your responsibility.

If you ask a narrower question with details of a specific mechanic or piece of your generation strategy you'd like some help with, we can provide tailored answers about that particular problem.
> 4 votes

# Answer
If your game is like *Binding of Isaac* where each room is full-screen, then it might be a good idea to actually only have one scene with one room. When the player moves to a different "room", you just modify that room accordingly by `Destroy`ing and `Instantiate`ing the room-specific objects.

When you do want scrolling transitions between rooms, you could do a room transition by instantiating the new room from a prefab, set it up, pan the camera to the new room, and destroy the previous room.
> 0 votes

---
Tags: unity, game-mechanics, roguelikes
---


title: RawImage texture change event?

text:
# Question
Title: RawImage texture change event?
I have a `RawImage` and an `AspectRatioFitter` attached to it so I want to change the aspect ratio to fit the image in the texture field of the raw image.
But I need to avoid checking for it in the update as much as possible.
Is there an event for when the texture of a RawImage element has changed? Something like `OnTextureChanged()`.

# Answer
> 2 votes
I would create a script responsible for changing the Texture instead of calling `rawImage.texture`. You will be able to raise an event when the texture changes thanks to this.

```
using UnityEngine;
using UnityEngine.UI;

[System.Serializable]
public class FloatEvent : UnityEngine.Events.UnityEvent<float> { };

public class RawImageManager : MonoBehaviour
{
    // Drag & Drop the RawImage component
    [SerializeField]
    private RawImage target ;

    // Select the `AspectRatio` component and the `aspectRatio` dynamic variable
    [SerializeField]
    private FloatEvent onAspectRatioChanged ;

    public Texture Texture
    {
        get { return target.texture ; }
        set
        {
             target.texture = value ;
            if( onAspectRatioChanged != null )
                onAspectRatioChanged.Invoke( value.width / value.height ) ;
        }
    }
}

```

And then, call `GetComponent<RawImageManager>().Texture = texture ;` instead of `GetComponent<RawImage>().texture = texture ;`

---
Tags: unity, textures, gui, ui-design
---


# Question
Title: Is there a term for placeholder graphics for dialog systems?
I'm working on a game that has a lot of dialog. It has a dialog system similair to Phoenix Wright, where the characters appear onscreen when they talk, either in sprite form or as a 3d model. Usually there's mouth and eye animations as well, and their facial expressions change depending on the context of the scene.

Here's my problem: I suck at drawing. Like, massively. I enjoy writing dialog and I already have lots of dialog written down. I even made a little program for myself, which mimics how the dialog would play out in my game. Something that I don't enjoy doing, however, especially when I implement the dialog into my game, is have tags everywhere that describe the characters mood/expression instead of showing it visually. Example:

John: **mostly neutral, slightly worried** How was your day?
Jane: **sad** Not so great...

Even in the prototype stage, I would like something more... visual, to convey the scene better to everyone else and really get the right mood and expression of the character across. That way, it would be easier for the future artist to draw the necessary poses, expressions, animations, etc. for each character.

What I would like to do is have placeholders of blank (mostly featureless) characters that have lots of different expressions to convey what I want the character to look like in that situation. I'm not asking where to find something like that, I simply want to know if there is some sort of game developer jargon/term for this kind of thing (animated or still), so I can narrow down my search a little.

# Answer
"Placeholder" is already the term usually used to describe assets hastily made and used as stand-ins while artists still work on a more production-quality version of them.

Placeholders should intentionally be made as ugly as possible. When they are not ugly enough, you might get so used to looking at them that you become blind to their lack of quality and end up shipping them.

My recommendation for dialog portraits would be to create the placeholders with MS Paint. Use the mouse to draw a free-hand smiley face conveying each emotion. To represent different characters, either paint in a different color or write the character name below it. Do not spend more than one minute on each one.

A practice you sometimes see is that people use assets ripped from a different game as placeholders during development. I would recommend you to **not do this**, because it is easy to lose track of which assets are placeholders and which are your own. If you accidently end up shipping a placeholder (or even just publish a development screenshot with one), you are committing a copyright violation which might get you into a nasty lawsuit.
> 2 votes

# Answer
I generally use the term *emoji*.

The term conveys what it is, and since they're part of Unicode, maybe your infrastructure supports them out of the box.
> -1 votes

---
Tags: terminology
---


# Question
Title: How to handle component-based objects in a game loop?
I've been writing my own game engine and I was wondering the correct way to handle my game objects. Each game object is different. The only thing they have in common is a set of operations to handle their components. With that said, each game object will have different components that do different things. Ex: game object 1 has input, physics and display components; object2 has only a display component. I was wondering if it was best to

1. Loop around the list of objects and call an "update" on each of them and then run each "update" for each component the object holds; or
2. Have a list of components in my game loop and check for each component if they have the current component. If so run it, otherwise move on...

I see benefits and harm to both strategies.

* Benefit of 1 is that there isn't a lot of overhead, but things might get out of sync;
* Strategy two is basically the opposite of 1...

For sake of simplicity I'm not putting how I'll handle the gameloop tick and I'm using a generic language.

Example of code for 1:

```
gameLoop() {
  forloop on each game object as obj {
    obj->update()
  }
}

//obj
update() {
  foreach component as component {
    component->update()
  }
}

```

Example of code for 2:

```
gameLoop() {
  input = &event
  forloop on each game object as obj {
    if (obj->canHandleInput())
       obj->handleInput(&event)
  }
  forloop on each game object as obj {
    if (obj->hasPhysics())
       obj->updatePhysics()
  }
  forloop on each game object as obj {
    if (obj->canDraw())
       obj->Draw()
  }
  //audio...
  //other components
}

```

What is the currently the most accepted way to handle objects in a game loop?

# Answer
Both approaches should result in the same result, so your choice really comes down to what makes the most sense architecturally.

But first, your example for approach #2 is incorrect. Each system should have a collection of components, so you do not need to have multiple loops over your game objects. That is:

```
foreach physicsComponent in physicsComponents {
    physicsComponent.update()
}
....

```

The advantage of #2 is it gives you more flexibility in how to implement system-specific updates. For example, for a physics-heavy game, you might perform a clustering pre-processing step so that you detect collisions only on pairs of nearby objects. It's also cache-friendly as you're repeating a small bit of code over lots of data in one go.

But the advantage of #1 is that you have more flexibility in how systems interact with each other. Suppose you have an animation system and you want to avoid updating it for far-away objects, since the player won't see them at all. But your physics system might depend on the animations as well - let's say your game is a fighting game where character animations change the physics shapes. You can easily handle this if you update on a per-game-object basis, whereas if you went with #2 you'll get a messy tangle of inter-system dependencies.
> 2 votes

# Answer
```
gameLoop() {
  forloop on each game object as obj {
    obj->update();
  }
}

//obj
update() {
  foreach component as component {
    component->update();
  }
}

```

No, not all components require an update. Instead, Write granular systems which handle tasks common to a subset of components, such as updating position by velocity, or computing your graphics transform from position.

Your game loop becomes:

```
void gameloop()
{
    for ( auto s : m_systems )
    {
        s->update();
    }
}

```

Within each system, you have customised loops that only work with a small subset of components, as mentioned before.

It looks like your understanding of this has a few gaps, so I would recommend doing some more reading on Entity Component Architecture, before doing any more work on your engine. I think you will find it illuminating.
> 1 votes

---
Tags: software-engineering, game-loop, component-based
---


# Question
Title: How to calculate acceleration distance(frictionless, massless)
Object A is moving via. 2D rigidbody by velocity V and in script is defined breaking power P. Every frame of breaking (P * Time.deltaTime) is subtracted from velocity V (in other words, ignoring mass). How i can calculate distance D required to slow down to target velocity tV ?

I'm not actually using force/power but i setting velocity directly with this line of code :

```
Vector3 dir = transform.TransformDirection(Vector3.up);
ship.rb.velocity = Vector2.MoveTowards(ship.rb.velocity, (dir * maximalSpeed) * ship.massModifier, speedGain / ship.massModifier);
```
(Don't worry about ship.massModifier, Basically heavier ship hulls are slower)

I'm self-learning Indie developer and i need this for AI to my game. Enemy in space ship have nothing like space-breaks so only way how to slow down is to turn ship by 180 degrees and thrust forward in counter-direction.I need to know this to calculate distance from target required to slow down and prevent possible collision with target.

# Answer
> 1 votes
Use the formula

$$ t = \frac{v\_0}{a}$$

$$ s = v\_0 \cdot t + \frac{at^2}{2}$$

where \\$v\_0\\$ is the starting velocity, \\$a\\$ is the acceleration/deceleration and \\$s\\$ is the distance

---
Tags: unity, c#, physics, mathematics, ai
---


# Question
Title: Change in force on objects after collision
i am implementing a billiard simulation game and i have a question about collision response.

As integrator, i am using Semi-Implicit Euler,

```
ball.setVelocity(ball.getVelocity().add(ball.getAcceleration().multiply(dt)));
ball.setPosition(ball.getPosition().add(ball.getVelocity().multiply(dt)));

```

Before integrating, i am calculating acceleration :

```
this.setAcceleration(this.getForce().multiply(1 / this.getMass()));

```

dt is time frame here, and acceleration, velocity, force and position are Vector class. (operations as add, multiply... are standard vector operations).

My question is - when i initially hit ball with cue, i am giving force -k\*x (Hooke's law) to ball. But when it collides with other ball, i can only find formulas that calculate new position and new velocity, but my force will stay same. But how to change force here in both balls (it will change velocity and position later in SE Euler).

I appreciate any answer!

# Answer
> 1 votes
You usually don't look at forces when trying to get the new velocity of an object after collision, since it's in the field of kinematics. You only need momentum.

The momentum of an object can be calculated using \\$m \cdot v\\$, where m is the mass and v is the velocity. Collisions are basically just momentum transferring from object A to B. The formulas can be pretty involving, but if you don't want to be that realistic about this, then you could simply transfer a constant amount (like 90%) of the momentum to simulate the effect. You can tweak this value if it doesn't feel right.

So, you'll basically need to do these steps for each ball involved in the collision separately:

* Calculate the momentum of the current object.
* Get the velocity difference of the current object and the other object, then multiply it by the mass of the other object.
* If the result is larger, than the current momentum, then all of the momentum of the current object can be trabsferred into the other object, if it's smaller, then only as much as the result (think about it, if you throw a ball at a truck, then it will stop, so all of the momentum was transferred to the truck, but if the truck hits the ball, then it can't go faster, than the truck itself and the truck won't stop).
* increase the momentum of the other object and decrease the momentum of the current object and calculate the speed from the new momentums (velocity = momentum / mass)

# Answer
> 0 votes
Most changes in velocity are computed instantaneously (which is a good approximation of how snooker balls behave in reality). The equations for your physics calculations should also never change position.

The physics of impact resolution only deals with changes in velocity, and for spheres, can be computed very easily:

When a collision is detected, compute the relative velocity(Vrel) for each ball involved:

```
Vrel = velB - VelA
contactVel = Vrel dot collisionNormal

```

This is used to: Compute the resultant impulse vector(J) which is :

```
e = min(Rest_a, Rest_b) //(Rest being how "bouncy" a ball is (should be close to 1))

J = -(1+e) * contactVel
J/= (Ma^-1 + Mb^-1)

Ja = J * collisionNormal
Jb = -Ja

VelA += Ja/Ma
VelB += Jb/Mb

```

Then later you do:

```
posA += VelA * dt;

```

There is no reason to change the position of a ball, during collision resolution, as an impulse is a third order differential, and as such must reduce itself to a second order differential in order to change position.

```
dx/dt = v (velocity is a 1st order differential)
dv/dt = a (acceleration is a second order)
da/dt = J (instantaneous Force(impulse) is 3rd order)
J/dt = F (force applied over 1 seconds).

```

Thus, the result of an impact is not a change in position, but an instantaneous change in acceleration (we know it isn't really instantaneous, but it's a decent approximation). Once this impulse is used, it is discarded.

---
Tags: java, physics
---


# Question
Title: How can I simulate a crash of OpenGL in GLKViewController to help track down a user's problem?
I am using `GLKViewController` for iOS app. On some devices, there are problems (possibly with OpenGL), that I am unable to solve, because I dont see this problem on none of my devices or emulator.

Is there a way, how to "manually" force OpenGL (`GLKViewController`) to crash, but not to crash app? Or is there any other way, why `GLKViewController` instance can become null?

# Answer
> 1 votes
Sure, there are ways to cause `GLKViewController` to crash, ranging from giving it a bad delegate, to swizzling one of its methods and dereferencing a null pointer in the implementation, et cetera.

But doing so is pointless. It wouldn't help you fix a crash that users were seeing unless you happened to randomly choose to recreate precisely that crash, which would be *very* unlikely. And it certainly won't help you fix a problem that users are reporting that isn't even a crash.

What you probably want to do instead is ship a build with improved error checking and logging around the operations you're doing with the view controller and OpenGL setup. Log what is going on, make sure you're checking any `NSError` objects that are filled out, et cetera. Hopefully with such a build (which you may be able to distribute specifically to the users experiencing the problems), you will be able to generate a log that can help lead you down the right path.

---
Tags: ios, opengl-es
---


# Question
Title: Calculating the geometry of a thick 3-way miter joint
Following a very helpful post on another forum I've found a simple algorithm that takes an array of 2D vectors and creates a triangle strip. I've modified the source code for my purposes. I haven't tested it yet, but it should do the trick.

```
public static void PolyLineToTriangleStrip(Vector2[] pts, bool closed, float thickness, List<Vector2> vertices, List<int> indices)
    {
        var numPts = pts.Length;
        vertices.Clear();
        indices.Clear();
        for (int i = 0; i < numPts; ++i) {
            int a = ((i - 1) < 0) ? 0 : (i - 1);
            int b = i;
            int c = ((i + 1) >= numPts) ? numPts - 1 : (i + 1);
            int d = ((i + 2) >= numPts) ? numPts - 1 : (i + 2);
            var p0 = pts[a];
            var p1 = pts[b];
            var p2 = pts[c];
            var p3 = pts[d];

            if (p1 == p2)
                continue;

            // 1) define the line between the two points
            var line = (p2 - p1).normalized;

            // 2) find the normal vector of this line
            var normal = new Vector2(-line.y, line.x).normalized;

            // 3) find the tangent vector at both the end points:
            //      -if there are no segments before or after this one, use the line itself
            //      -otherwise, add the two normalized lines and average them by normalizing again
            var tangent1 = (p0 == p1) ? line : ((p1 - p0).normalized + line).normalized;
            var tangent2 = (p2 == p3) ? line : ((p3 - p2).normalized + line).normalized;

            // 4) find the miter line, which is the normal of the tangent
            var miter1 = new Vector2(-tangent1.y, tangent1.x);
            var miter2 = new Vector2(-tangent2.y, tangent2.x);

            // find length of miter by projecting the miter onto the normal,
            // take the length of the projection, invert it and multiply it by the thickness:
            //      length = thickness * ( 1 / |normal|.|miter| )
            float length1 = thickness / Vector2.Dot(normal, miter1);
            float length2 = thickness / Vector2.Dot(normal, miter2);

            if (i == 0 && !closed) {
                vertices.Add(p1 - length1 * miter1);
                vertices.Add(p1 + length1 * miter1);
            }

            vertices.Add(p2 - length2 * miter2);
            vertices.Add(p2 + length2 * miter2);

            if (closed && i == numPts-1) {
                indices.Add(i * 2);
                indices.Add(i * 2 + 1);
                indices.Add(0);
                indices.Add(i * 2);
                indices.Add(0);
                indices.Add(1);
            } else {
                indices.Add(i * 2);
                indices.Add(i * 2 + 1);
                indices.Add(i * 2 + 2);
                indices.Add(i * 2);
                indices.Add(i * 2 + 2);
                indices.Add(i * 2 + 3);
            }
        }
    }

```

Feeding it a sequence of vectors would produce something a bit like this:

However, I want to complicate matters by introducing another problem - 3 way joints (or rather n-way).

It must be possible to do this by building on the algorithm, but I'm not sure how I would modify the above algorithm to draw an n-way miter joint with perfect angle distribution like so:

The highlighted lines represent the source lines that would be fattened up by the algorithm.

I calculated and drew these in blender, unfortunately I'm at a bit of a loss to do it programmatically.

Obviously this cannot be achieved with simple line sequences, but that's beside the problem. All that' needed is a central point and n-ammount of points that represent the ends of outcropping lines, and then an algorithm to calculate the outer edges of the required shape.

# Answer
You will need to operate on a graph data structure, rather than a list / array. So the flow of the algorithm will no longer be as linear as you are used to.

I'm assuming you're really only speaking in term of 2D *planar* problem, not the same structure built / jointed in 3D, as the latter would enhance the complexity by a considerable margin.

Iterate each node in your graph, each of which should contain a list of those edges connecting it to neighbouring nodes. Every time you have a conflux of lines meeting at this node (whether 2, 3, 4, 5 or whatever number) you need to get the angle between each pair of adjacent lines (meaning you'll need to have some way of knowing which lines are adjacent, by the way - I'd suggest first ordering them in a list by increasing angle). Then insert a new point (line) at an angle halfway between them. Your 2nd T-junction example above is useful in showing this: The left hand side has to split an angle of 180 degrees between the lines - the line going out is thus at 90 degrees to both of them. Again on the right hand side of the same drawing, the same principle applies, here splitting 90 degree corners into 45 degree angles, above and below the lateral line.

So, you can create those new separating lines / points, but you also need to know how long they need to be in order to keep the "band" thickness the same throughout. The diagonal lines in your 2nd diagram are longer than the matching lines at the end of structure, because they are the hypotenuse of a triangle whose one side is not marked in your diagram, but which runs from the tip of those diagonal 45 deg lines, directly inward and perpendicular to the "spine" until it touches the spine, and is parallel to that line which caps the arm. So in each case you need to use that half-width of each "band" to calculate the hypotenuse length. Indeed, that should be a parameter your specify as a setting before startup, or as a draggable slider "thickness" which reconfigures the mesh each time you drag it.

Obviously, once you've created all the necessary points in this way, you can create the actual lines by retriangulating those accordingly. I tend to triangulate meshes in a second pass after constructing the vertices. This may mean you need to store some intermediate data to know what you're doing once you get to the triangulation pass.

This should give you enough to work from.
> 1 votes

---
Tags: c#, opengl, mathematics, geometry
---


# Question
Title: How to get smoother transition between the surface normals rotation of player in Unity
I kinda have a problem that my player is snapping onto the other surface while I wanna move a ramp up. I want to have it rotate smooth to the normals of the ramp. How can I change the code below to a smoother rotation function of the player?

Code:

---

```
void NormalsOfGround()
{
    //RAYCASTS THE NORMALS ON THE GROUND THAT THE PLAYER MOVES ALONG SURFACE
    Debug.DrawRay(rayCastNormal.transform.position, -transform.up, Color.blue, 2.5f);
    Ray ray = new Ray (transform.position, -transform.up);
    RaycastHit hit;
    if(Physics.Raycast(ray, out hit, 2.5f, GroundLayer) == true)
    {
        transform.rotation = Quaternion.FromToRotation (transform.up, hit.normal) * transform.rotation;
    }
}

```

# Answer
You can rotate by a controlled number of degrees each frame with:

Quaternion.RotateTowards(from, to, maxDegreesDelta)

So your code can look something like this:

```
if(Physics.Raycast(ray, out hit, 2.5f, GroundLayer)) {

    var targetRotation = Quaternion.FromToRotation (
                 transform.up,
                 hit.normal
             ) * transform.rotation;

    transform.rotation = Quaternion.RotateTowards(
                transform.rotation,
                targetRotation,
                degreePerSecondSpeed * Time.deltaTime
             );
}

```
> 0 votes

---
Tags: unity, c#, rotation, movement, normals
---


# Question
Title: Blender: How to "meshify" an object I made from Bezier curves
I made a star shape using Bezier curves, and extruded it (see pic below):

What I want to do is give it a rounder look - not just around the edges by using beveling. I want it to kind of look like this (well, that shape anyway):

How would I go about doing this? Please keep in mind that I am extremely new to Blender.

I thought that I could somehow turn this star into those default shapes that have tonnes of squares which I could pull out, and apply a mirror to it so that the same thing happens on both sides. I really don't know how to do it, and would appreciate your help.

# Answer
`ALT+C` will help you to convert a path to a mesh, then select a loop like in figure

`E` for extruding and right after press `S` to scale and move the cursor to the center of the star.

Now you get how to extrude the shape to the center, to give a vertical extrusion just press `E` and right after `G` to grab and then the axis where you want to move the selection like `Z`.

To create the final point for closing the center of the star just press `E` again with the final edge loop selected and press `ALT+M` to collapse the selection to the center of the shape.

With this you can achieve what you want to do.

---

this star is simply generated through a script:

* go in the User Preferences panel
* Addons \> Add Mesh
* Enable `Extra Objects`
* just exit or *Save as default* as you wish
* `SHIFT+A` in the 3D viewport
* Mesh \> Extra Objects \> Basic Objects \> Star
> 5 votes

# Answer
I had a similar problem, wanting to convert NURBS curve-surfaces (curves with taper & bevel) into MESHes. I couldn't find a direct "convert to Mesh" command.

Select the objects to be converted. Export the selected objects to STL format. File \>\> Export \>\> Stl (.stl) Import the STL version back into blender (where it shows up as a mesh). File \>\> Import \>\> Stl (.stl)
> 0 votes

# Answer
In **Object Mode**, with your object selected, type **Alt+C** and a menu **"Convert to"** will show, in the menu chose: **"Mesh from Curve/Meta/Surf/Text"**.
> 0 votes

---
Tags: blender
---


# Question
Title: How player(sprite) in the phaser will opposite or reverse while going left and right?
I am developing a game where my player has to look to see forward when I am pressing right arrow key. But how can I make it look reverse after pressing left arrow? I can create a sprite of reverse look but how can load that while pressing left and at the same time forward player should be destroyed?

# Answer
Usually I set the sprite's scale.x to `-1` to flip it horizontally. You can see an example here: https://phaser.io/examples/v2/sprites/scale-a-sprite some of those sprites are scaled to negative values, and they appear mirrored.

Another approach is to flip the sprites in your assets. This has the added advantage of looking correct if the character is handed - if they were holding a gun, they won't be switching their gun hand depending on which direction they're facing. Phaser's platformer example does this, and has separate left and right animation frames:
> 1 votes

# Answer
When your character is looking rightward, his width is positive. So, all you need to do is to invert proportionally his width.

Visual example:

**This image's width is 779px**

**And this image's width is -779px**

When reversing, also remember to add the X-axis by the width, so that the character's sprite doesn't "walk" behind the total units that the width of the sprite has
> 0 votes

---
Tags: sprites, phaser
---


# Question
Title: How would I go about implementing a collision avoidance check, avoiding moving objects from multiple directions?
So I'm making a testbed for an AI actor(ship). It's a simple asteroids game using an AI controlled actor. I'm doing this using VS, monogame.

I have implemented a simple steering behaviour using a tutorial as a guideline, found here. https://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-collision-avoidance--gamedev-7777 It works somewhat.

The problem occurs when the objects(asteroids) are all moving around(at different speeds), using the guidelines from above, it only checks for collisions for whats infront, at specific points. Which would work if all other objects were static. My initial thought was to add a check for back,left,right. Then loop it to check all these positions in a 50-150 units radius. But the more I think about it, the more realize there must be a better way. As understand it, that wouldn't really solve it either, and would be performance heavy.

How would I go about implementing a collision avoidance check that 1; takes into account the approaching objects may come from any direction. 2; the differnt velocities of those objects.

Or might it be better to apply the existing check to the objects and passing the data to the actor?

Any references, tips, guide, code snippets or good old wisdom or simple pointer in the right direction, would be enormously appreciated!

# Answer
The first thing to do with any large collision sets is elimination. Range check in itself is a good start but another check is simply a direction check. Is the direction the asteroid in this case in the potential set of threats. Are they moving in a direction generally away or toward.

Similar to the principals of sql. What checks and their cost will determine the order of elimination. What set is left is what you apply as the threat set. There are some heavier intercept algorithms around that you can feed direction speed in of 2 objects to determine intercept point. I would then calculate when and where this intercept points occur and using that to know where to avoid. Heat maps and all sort of path finding routines could be used.

This is key part. You could use a very simple local grid system to add a weighting. The lowest weighting would be the safest. But you could also add some simple path finding to evaluate safest path also
> 1 votes

# Answer
One method I have used in the past is the creation of invisible objects (typically lines, so that you won't have to deal with objects being stuck in the middle) that are at a safe distance from the object (in this case, the ship), placed in the shape of a circle, that will use collision detection to sense objects hitting them. Of course, nothing will bounce off of them.

When it detects a collision on the side away from your object, you can make your AI turn away from it. When the invisible object detects a collision on the side closer to the object, it will then be able to return to a regular state, thus acting as if it has a more sophisticated AI system.

Other choices would include intercepts or your idea. There is also a possibility that you can create a circle that scales itself up and finds in what direction the nearest object to collide with would be, and then tells your AI to avoid it.
> 0 votes

---
Tags: c#, 2d, monogame, steering-behaviors, collision-avoidance
---


title: How can I make my game look pixelated?

text:
# Question
Title: How can I make my game look pixelated?
I played Nuclear Throne yesterday a few hours and I noticed that the whole game looks pixellated. I like this effect and I'd like to know how to recreate it in my own games.

# Answer
There are several possible ways to accomplish this. Two of the most straightforward are:

* Author your art assets in that style directly.
* Scale your art assets up an runtime by rendering to a half-size render target at native pixel resolution of your art, and then using that render target as a texture for a full-screen quad at full size (thus pixel-doubling everything), using a point-sampling filtering mode.

Neither of these approaches require specialized shaders. The first option, simply creating the art that way, is the simplest from a programming perspective, but it is less flexible. Certain kinds of art (for example the tracking laser from that video) that is dynamically generated at runtime might be harder to generate directly in this style, although for specific cases you can certain find specific solution. For example, the classic Bresenham's line algorithm could be employed to generate runtime lines of any particular pixelation level.

Scaling the art up at runtime is somewhat more involved but does not require you to author the art pre-pixel-doubled. This can give you some flexibility to adjust your desired scale factor without redoing lots of art, and can naturally handle some of the kinds of dynamically-generated art you might run into. It also affords you the option to use more complicated scaling filters than just pixel-doubling, if that's what your into. There's a whole host of pixel art scaling processes you can apply, many of these are popular among emulator developers for improving the fidelity of older games' art on modern, large high-resolution displays.

Note that while the most basic point-filter upscaling will not require you to use shaders, some of the more involved scaling algorithms might, or at the very least might benefit in performance from doing so.

Note also that the upscaling doesn't need to be applied to the whole scene; if you only want to pixel-double a handful of sprites you can do that as well, simply by doubling the dimensions of their quads and ensuring you use a point-sample filter.

I think upscaling gives you the most flexibility for the amount of effort it requires, and that's the route I recommend you go.
> 2 votes

# Answer
The reason why the whole game looks pixellated is because all the art assets are pixel art.

Pixel art is a very common style for indie games, as it requires a lot less time invested to create quality assets, and thus will probably be a good idea for your game, unless you are a very good artist.

Thus, what you are looking for are pixel art tutorials.

The most basic kinds tell you to do four things- find a graphics program specifically for pixel art, look at other's sprites/drawings, try to draw some sprites, keep drawing sprites over and over while experimenting.

This is what I do, as I only use pixel art in my games- look at an image, and draw it out of pixels with very few details and a few very obvious characteristics. Seldom have I ever drawn a sprite without a reference image.
> 2 votes

---
Tags: libgdx, graphic-effects
---


# Question
Title: Compare and copy two the same option but different in script(C# Unity)
I have 3 script which is **OptionPopup.cs**,**MC\_StreamingOption.cs**,**MC\_OptionPopUp.cs**. Now here is a screenshot of my UI so that you can fully understand my question.

The Option below on the left side the `Horse Racing Scene` must be the same value as on the Game Option Board which is on the right side.

For ex: I choose `Rendering` then on the **GameOption** the `Rendering` also will be checked the same as when i choose on the **GameOption** the `Rendering` then on the Horse Racing Scene below on the left side the `Rendering` will be checked.

So here is my script for the **Game Option**(On the right side option). Note: *They are on different scenes so basically i could not use static field on my UI's*

# OptionPopUp.cs

```
 public void LiveStreaming()
{

    if (livestream.normalSprite == RADIO_OFF_SPRITE_NAME && MC_StreamingOption.isLiveStreamingOutside)
    {
        livestream.normalSprite = RADIO_ON_SPRITE_NAME;
        isCheckedLivestream = true;
        PlayerPrefs.SetInt(LiveStreaming_, 1);

        if (isCheckedLivestream)
        {
            render.normalSprite = RADIO_OFF_SPRITE_NAME;
            PlayerPrefs.SetInt(Rendering_, 0);
        }
    } else
    {
        livestream.normalSprite = RADIO_OFF_SPRITE_NAME;
        isCheckedLivestream = false;
        PlayerPrefs.SetInt(LiveStreaming_, 0);

        if (!isCheckedLivestream && render.normalSprite == RADIO_OFF_SPRITE_NAME)
        {
            render.normalSprite = RADIO_ON_SPRITE_NAME;
            PlayerPrefs.SetInt(Rendering_, 1);
        }
    }
}

public void Rendering()
{

    if (render.normalSprite == RADIO_OFF_SPRITE_NAME && MC_StreamingOption.isRenderingOutside)
    {
        render.normalSprite = RADIO_ON_SPRITE_NAME;
        isCheckedRendering = true;
        PlayerPrefs.SetInt(Rendering_, 1);

        if (isCheckedRendering)
        {
            livestream.normalSprite = RADIO_OFF_SPRITE_NAME;
            PlayerPrefs.SetInt(LiveStreaming_, 0);
        }
    } else
    {
        render.normalSprite = RADIO_OFF_SPRITE_NAME;
        isCheckedRendering = false;
        PlayerPrefs.SetInt(Rendering_, 0);

        if (!isCheckedRendering && livestream.normalSprite == RADIO_OFF_SPRITE_NAME)
        {
            livestream.normalSprite = RADIO_ON_SPRITE_NAME;
            PlayerPrefs.SetInt(LiveStreaming_, 1);
        }
    }
}

```

Here's what i'm doing in the **Horce Racing Scene**(on the left side below)

# MC\_StreamingOption

```
//[PK Debug 2/6/2018]
public string RADIO_ON_SPRITE_NAME = "popup_radiobtn01_on";

public string RADIO_OFF_SPRITE_NAME = "popup_radiobtn01_off";

[SerializeField] UIButton livestream = null;

[SerializeField] UIButton render = null;

public static bool isLiveStreamingOutside = false;
public static bool isRenderingOutside = false;

public void LiveStreaming()
{
    if (livestream.normalSprite == RADIO_OFF_SPRITE_NAME)
    {
        livestream.normalSprite = RADIO_ON_SPRITE_NAME;
        //render.normalSprite = RADIO_OFF_SPRITE_NAME;

        if (livestream.normalSprite == RADIO_ON_SPRITE_NAME)
        {
            PlayerPrefs.GetInt(OptionPopup.LiveStreaming_, 1);
            isLiveStreamingOutside = true;
            render.normalSprite = RADIO_OFF_SPRITE_NAME;
        }
    }
    else
    {
        livestream.normalSprite = RADIO_OFF_SPRITE_NAME;
        render.normalSprite = RADIO_ON_SPRITE_NAME;

        if (livestream.normalSprite == RADIO_OFF_SPRITE_NAME)
        {
            PlayerPrefs.GetInt(OptionPopup.LiveStreaming_, 0);
            isLiveStreamingOutside = false;
            render.normalSprite = RADIO_ON_SPRITE_NAME;
        }
    }
}

public void Rendering()
{
    if (render.normalSprite == RADIO_OFF_SPRITE_NAME)
    {
        render.normalSprite = RADIO_ON_SPRITE_NAME;
        livestream.normalSprite = RADIO_OFF_SPRITE_NAME;

        if (render.normalSprite == RADIO_ON_SPRITE_NAME)
        {
            PlayerPrefs.GetInt(OptionPopup.Rendering_,1);
            isRenderingOutside = true;
            livestream.normalSprite = RADIO_OFF_SPRITE_NAME;
        }
    } else
    {
        render.normalSprite = RADIO_OFF_SPRITE_NAME;
        livestream.normalSprite = RADIO_ON_SPRITE_NAME;

        if (render.normalSprite == RADIO_OFF_SPRITE_NAME)
        {
            PlayerPrefs.GetInt(OptionPopup.Rendering_, 0);
            isRenderingOutside = false;
            livestream.normalSprite = RADIO_ON_SPRITE_NAME;
        }
    }
}

```

So I'm calling the Game Option(On the right side) by this code:

# MC\_OptionPopUp.cs

```
if (tzGlobal.Instance.UserConsoleType == tzGlobal.eGameRH_ConsoleType.LOBBY)
    {
        if (PlayerPrefs.GetInt(OptionPopup.LiveStreaming_) == 1)
        {
            livestream.normalSprite = RADIO_ON_SPRITE_NAME;
        }
        else
        {
            livestream.normalSprite = RADIO_OFF_SPRITE_NAME;
        }

        if (PlayerPrefs.GetInt(OptionPopup.Rendering_) == 1)
        {
            render.normalSprite = RADIO_ON_SPRITE_NAME;
        }
        else
        {
            render.normalSprite = RADIO_OFF_SPRITE_NAME;
        }
    }

```

Just like that so that you will know that i'm doing it like that. I would really appreciate if someone can help me out with my problem.

# Answer
What i did here is this

```
if (livestream.normalSprite == RADIO_OFF_SPRITE_NAME)
    {
        isLiveStreamingOutside = true;
        PlayerPrefs.SetInt(OptionPopup.LiveStreaming_, 1);

        if (isLiveStreamingOutside)
        {
            render.normalSprite = RADIO_OFF_SPRITE_NAME;
            livestream.normalSprite = RADIO_ON_SPRITE_NAME;
            PlayerPrefs.SetInt(OptionPopup.Rendering_, 0);
        }
    }
    else
    {

        isLiveStreamingOutside = false;
        PlayerPrefs.SetInt(OptionPopup.LiveStreaming_, 0);

        if (!isLiveStreamingOutside)
        {
            render.normalSprite = RADIO_ON_SPRITE_NAME;
            livestream.normalSprite = RADIO_OFF_SPRITE_NAME;
            PlayerPrefs.SetInt(OptionPopup.Rendering_, 1);
        }
    }

```

So from **MC\_StreamingOption.cs** I have no choice but to get the playerprefs again. And it works.
> 0 votes

# Answer
Not sure I completely understand the question but static fields of a class should stay the same regardless of whether or not you changed scenes.

For example if your class name is Foo and your static field is named bar, you should be able to access it via `Foo.bar` regardless of the scene you are currently in.

I would recommend making whatever variable you are using to store the option a static field (if it isn't already) and when a scene is loaded you can check whether the value of option has changed during `Start()` and then set your checkbox to the appropriate state.
> 0 votes

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


# Question
Title: How can I ungrab the grabbed Object in Unity?
I modified a grab Script to my purpose, I can grab the Object and make it a parent to the character with the Key "G" but I want to let it go and detach the parent of the picked Object with "H" with the Code: "hit.transform.parent = null;" but i cant get it to work, I dont know where to put it.

Code:

---

```
[SerializeField]
private Transform RayCastGrab;
[SerializeField]
private float raySize;
private Transform pickUpObj;
private Vector3 lastPos;

public LayerMask GrabLayer;

void Update ()
{
    PickRayLayer();
}

void PickRayLayer()
{
    Ray rayF = new Ray (RayCastGrab.position, transform.forward);
    Debug.DrawRay(rayF.origin, rayF.direction * raySize, Color.black);

    RaycastHit hit;

    if(Input.GetKey (KeyCode.G))
    {

        if (Physics.Raycast(rayF, out hit, 2f, GrabLayer))
        {
            //Picking up the Object and make it a parent of Player
            pickUpObj = hit.transform;
            hit.transform.parent = this.transform;
        }
    }

    if(Input.GetKey (KeyCode.H))
    {
        //Should let the grabbed Object go and detach it from parent of Player
        if(pickUpObj)
            pickUpObj = null;
        transform.parent = null;
    }

    if(pickUpObj)
    {
        pickUpObj.transform.position += transform.position - lastPos;
    }

```

# Answer
Since you saved the `Transform` of the object you picked up in the variable `pickUpObj`, it looks like you want:

```
if(Input.GetKeyDown(KeyCode.H))
{
     if(pickUpObj != null) {
         pickUpObj.parent = null;
         pickUpObj = null;
     }
}

```
> 1 votes

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


# Question
Title: Godot 3, multiplying by delta not making the object to move
I have a simple code which makes a sprite rotate and move,

```
extends Sprite

var vel = Vector2(1,1)

func _ready():
    print(position)
    pass

func _process(delta):
    rotation += PI * delta
    position = position + vel * delta
    pass

```

But in the line

```
position = position + vel * delta

```

when I multiply by delta, the sprite doesn't move, when I remove the delta, the sprite moves, why is that? I saw this tutorial and it seems to work fine.

# Answer
> 1 votes
Since delta time is in seconds, that means the character'll move 1 pixels every second if Godot can even handle sub-pixel values. Try increasing the velocity

---
Tags: godot
---


# Question
Title: Uncaught TypeError: Cannot read property 'Mesh' of undefined
I would like to use dragonBones with pixi.js. I got a problem.

When the following line executes in dragonBones, I am getting an error:

`slot.init(slotData, displays, new PIXI.Sprite(), new PIXI.mesh.Mesh(null, null, null, null, PIXI.mesh.Mesh.DRAW_MODES.TRIANGLES));`

The error says: `Uncaught TypeError: Cannot read property 'Mesh' of undefined.`. And yeah, while debugging, I noticed that `PIXI.mesh` is really undefined.

What can I undertake against the error?

I am using this file for a dragonbones.

May it be that the problem is in the fact that I am using `pixi.js - v4.5.6`?

# Answer
> 0 votes
The thing is that *pixi.js* consists of modules. In big projects it is common to turn off unused modules so that the library itself become lighter.

I just turned on necessary to get rid of errors modules and that is it.

I thought that enabling only `mesh` module would be enough, but actually it was not. After looking through the code I noticed that `mesh` is using a `particle` module in some places, so I enabled the `particle` module as well and it still was not enough.

I ended up enabling all of the modules.

---
Tags: javascript, pixi.js
---


# Question
Title: If Windows 10 store games aren't crackable, why continue to publish on Steam?
I never heard that any of those games that are exclusively sold on the Windows 10 store have ever been cracked. But some games on Steam are cracked days after release, even with the protection of something like Denuvo.

Given that, why should a game developer continue to sell games on Steam instead of just selling on the Windows store exclusively?

# Answer
The current operating system stats on Steam tell us that only 35% of Steam users even use Windows 10.

And of those who do use Windows 10, not everyone regularly use the Windows store to shop for new games. This might be a kind of chicken/egg problem. There aren't many interesting games on the Windows store, so nobody goes there to look for games, so nobody bothers to place any interesting games there. But that's a problem for Microsoft. Players and developers are quite content with doing their business on Steam right now. Most PC gamers nowadays use Steam as their primary source of new games, which makes it the one distribution channel you need to focus on. Any other distribution channels for PC games are secondary concerns.

And when it comes to the Windows store, making your game able to run from there might be a major additional investment. The Windows 10 store security concept puts a lot of restrictions on developers. That means when you want to put your game on the Windows store, you either need to keep those restrictions in mind during development from day 1, or you need to invest a serious amount of developer days into making the necessary changes afterwards. This investment often does not justify the additional customer base you can reach on the Windows store. Packaging a game for Steam, on the other hand, is a lot less work. If your game is run with a `.exe`, it will run from Steam. Steam features like achievements or workshop integration (Steamworks) are optional.

Regarding copy protection: There is no such thing as an uncrackable software. When a computer can run it then a computer can copy it. Copy protection can make it less convenient, but it can't prevent it. When there is a game which wasn't cracked yet, that's usually because nobody felt like investing the necessary effort. Effort invested by crackers is usually proportional to the interest in the cracked game. And people aren't interested much in Windows Store games, so you don't see many crackers who even bother.

And if you are one of the paranoid development studios who really care about copy protection, then the Windows store isn't for you either. Most 3rd party copy protection software (like the infamous Denuvo) do not work within the security restrictions mentioned in the 3rd paragraph. So the Windows store copy protection is your *only* line of defense. When anyone finds an universally applicable hole in the Windows Store DRM (and considering that it's a Microsoft product, that's not an unrealistic concern), you are screwed.
> 5 votes

# Answer
Because crackability is not the main consideration of game developers. Their main considerations are usually related to how many copies they can sell.

I've never used the windows 10 store and until just now i didn't know it had games. Steam is the best place to publish a game for a developer who cares about selling copies.
> 1 votes

---
Tags: windows, steam, publishing, platform
---


# Question
Title: How to move in between grid in crossword game
I am trying to create crossword game in my current app. As my current project is in iOS native so I wanted to implement this game only in UIKit so that it can be easily integrated.

**Requirement**

i need these types of movement in the crossword(as shown in below gif), like whenever I entered any char, it automatically moved to the next grid and when I entered the backspace button it clear that grid and automatically moves the previous grid.

**Issue**

Right now user have to select each and every grid to give input, which reduces the user interaction. So I wanted to implement this movement so that user can use crossword in a better way.

**What I have done?**

I successfully created the UI part by using the json structure which is similar to iPuz. But facing issue to implement this movement in crossword.

To check screen ui image, json structure & git repository, pls cleck here, if you need any further information pls ask in comment I will update the question.

# Answer
> 1 votes
If you aren't storing the word data in a grid yet, I'd suggest converting to that, as it will make stuff easier.

The file format gives you the location of each number in the crossword, so based on the "cursor's" location you can query the index of the word that the user is typing in.

The file format also specifies the direction that the words flow in. Combining this data, and the fact that the words flow either left-to-right or top-to-bottom, you can easily increment/decrement the cursor position.

I'm not sure how you want the typing to work (i.e. can the user choose an arbitrary cell and type there), but you could just store the current direction when the user starts typing in a word starting cell.

Here's some really rough pseudo code:

```
int CursorX, CursorY = 0;
int XDir, YDir = 0;

void OnKey(Key key) {
    if (key != Backspace) {
        // Gets the index of the word that starts here. Probably a lookup from some table.
        wordStart = QueryWordStartIndex(CursorX, CursorY);
        if (wordStart > 0)  // A word starts here, update direction.
        {
            if (WordDirection(wordStart) == "Across") XDir = 1, YDir = 0;
            else XDir = 0, YDir = 1;
        }

        Grid[CursorY][CursorX] = key.Char;

        // TODO: Check if the pos is valid here etc.
        CursorX += XDir;
        CursorY += YDir;
    }
    else {
        Grid[CursorY][CursorX] = "";
        CursorX -= XDir;
        CursorY -= YDir;
    }
}

```

You'll probably need to handle a lot of different cases and decide how to actually set `CursorX/Y` to a word start position.

Now, if the player starts typing in a grid where there isn't a word starting, this will be a lot harder if not impossible. In some cases you might be able to use empty cells around the cursor position to determine what word the player is trying to fill in (i.e. if there are empty cells in only one direction, that's the direction the cursor should be moved), but there will be situations where you can't deduce this information. In those situations, I'd just wait for the player to move the cursor to some direction, and remember this direction for convecutive character entries.

---
Tags: ios
---


# Question
Title: Static variable pre-declaration & memory heap expansion in Unity
When I profile my apps, I make sure that the code like this one:

```
private void Update(){
    int count = GetEnemyCount();
}

```

get's converted to this one:

```
private int count;
private void Update(){
    count = GetEnemyCount();
}

```

to prevent memory allocation and the heap expansion.

But what about the `static methods`, and allocations inside them?

Let's take this example (and assume I call it in `Update()`):

```
public static float GetPercentPositionX(Transform transform)
{
    float result;
    int screenWidth = GetScreenWidth();
    // some operations, result allocation, screenWidth usage
    return result;
}

```

What do I do here? Does it behave like a non-static function and expands the memory?

Shouldn't I declare static variables inside that class, to allocate the heap space at the start, for vars: `result` & `screenWidth`, just like I do in classic, non-static ones?

# Answer
> 3 votes
Local variables are not added to the heap. They are pushed onto the stack and immediately popped off the stack when they leave scope, thus already avoiding the heap (and the sort of memory allocation you are worried about) altogether. This is better memory management than what you are doing because your variables take up space on the heap when they don’t have to at all.

In short, you shouldn’t perform this optimization at all.

---
Tags: unity, memory-efficiency, memory
---


# Question
Title: In behavior trees, how do you retain your place in a sequence?
For context, I am coding a naive implementation of behavior trees myself, in C#. Let's say I have two scenarios that I want to create behaviors for. Both AI's will traverse/patrol four specific locations (markers), in order, and then repeat the path.

**AI 1**) Upon seeing the player, freeze. Once the player is out of sight, begin patrolling again, but from the very first marker (i.e. restart).

**AI 2**) Upon seeing the player, freeze. Once the player is out of sight, begin patrolling again, but from whatever marker it was previously on before being interrupted by the player (i.e. carry on).

I would expect both of these behaviors to be modeled by first checking for the player, and if that fails proceeding further down to a Sequence node that contains four children, each being a "traverse to maker" behavior.

In other words -\> after a behavior is *interrupted* by a node higher up the tree, how do I *retain* the current place in a sequence and carry on when we finally make it back down the tree again?

# Answer
Put all the information needed to restore the state you're interrupting into some structure representing the context of the current action. This is likely at least:

* a reference to the tree about to be interrupted (if you have more than one tree capable of processing at a time)
* a reference to the node about to be interrupted
* state specific to that node (e.g., destination if a "move to target" node, et cetera)

You may want to stuff in some extra information like the time of interruption, so that you can do some logic to enable AI to disregard old actions if their interruption ended up lasting more than X seconds, or whatever.

Put all that kind of stuff in something called, say, `InterruptedActionContext`. When a node is about to be interrupted, build one of those contexts from the node that is currently executing and stuff it onto a stack of interrupted actions, and then proceed with the interrupting node.

Whenever a node naturally completes (or a branch of the tree naturally completes; whatever criteria is most important to you), check the interruption stack to see if you should pop something from it and return to a previously-interrupted behavior. Otherwise continue as you would normally.
> 0 votes

---
Tags: ai, behavior-tree
---


# Question
Title: Does it matter what file type my save file is?
So, I am looking into game development, and I just learned how save files work and how to create and implement them. Here is the code that I was using on Dev C++:

```
// basic file operations
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main () {
    string line;
    ifstream saveFiles ("save.txt");
    if (saveFiles.is_open()) {
        getline (saveFiles, line);
        string arr[2];
        int i = 0;
        stringstream ssin(line);
        while (i < 2){
            ssin >> arr[i];
            ++i;
        }
        saveFiles.close();
        cout << "You have " << arr[0] << " hearts" << endl;
        cout << "You have " << arr[1] << " food";
    }
    else {
        cout << "Hearts > ";
        int hearts;
        cin >> hearts;
        cout << "Food > ";
        int food;
        cin >> food;
        ofstream saveFile;
        saveFile.open("save.txt");
        saveFile << hearts << " " << food;
        saveFile.close();
    }
    return 0;
}

```

For me, this checks if there is a save file, if there isn't, asks for input and then saves it. Then, when they come back, it checks again and it finds the file and gives you the data. This seems like it'd be how you make a save file (instead you likely wouldn't directly enter information like in my example).

As you can see, I create a `save.txt` file and it works fine. However, for games that I've run (like Minecraft), it doesn't use a `.txt` file. What difference does it make and what would work best for me (in any example)?

# Answer
> 9 votes
A file extension is not a file type.

A file extension is used (as a convention) by some OS's to *assume* the file type. But it doesn't *really* determine the file type. Ultimately the only thing that determines the file type is the *content of the file*.

So you can write a bunch of plain-old-ASCII to a file and call it `savegame.bob` if you like. It might deter casual introspection of the file, but it's still fundamentally a text file. And, for that matter, a perfectly fine way to save your games.

Eventually you may want to save your games by writing bytes that are not text, but rather are the numbers representing your game state directly. The advantage to such files (which are commonly called "binary files," even though that's a misnomer) is that they're usually easier and/or faster to load (since you don't have to *parse* the text. They're also slightly more difficult to casually inspect and hack (but not much so). The disadvantage is that they can be a bit more complicated.

But ultimately, no, it doesn't matter how you format your save file as long as it works for your game.

---
Tags: c++, savegame
---


# Question
Title: How to convert png images to True Type Font?
I'm doing a clone of Colonization and I'm trying to use the same font type as the original game. I'm able to get the pixels from the original font files (.ff) using the application from this thread https://forums.civfanatics.com/threads/colonization-picture-viewer.256665/page-2 but the outcome is a PNG file.

The question is how I can convert this PNG file to a True Type Font that I can load on my MonoGame application? Is there a way to do that? Do I have to consider using one texture per letter rather than a font type? If this has sense, how can I set different font sizes using textures?

# Answer
> 6 votes
Truetype fonts are vector based. So you would have to trace the glyphs with a vector editor and then use a program like FontForge (which also is a vector editor) to build a font from that.

That said, You do not need to use TTF fonts in MonoGame since it just renders the font to a texture at compile time.

There are many bitmap font programs/examples available for XNA/MonoGame: https://blogs.msdn.microsoft.com/shawnhar/2007/04/26/bitmap-fonts-in-xna/ https://craftworkgames.github.io/MonoGame.Extended/MonoGame.Extended/BitmapFonts/

---
Tags: monogame, fonts, png
---


# Question
Title: Using gametime.ElapsedGameTime to trigger an event
I have a splashscreen object that waits for a user input before loading the next screen, but I would also like the next screen to load after a certain amount of time has passed. I tried adding a check to see if the elapsed game time is greater than or equal to a set amount of time in seconds. The user input still changes the screen, but the screen will not change after that time requirement has been met. What am I doing wrong?

# Answer
> 1 votes
I figured it out. gameTime.ElapsedGameTime is a TimeSpan that refers to the amount of time that has passed since the last update, which is a fraction of a second. By using gameTime.TotalGameTime, I was able to get the total amount of time that has passed since the program started running. Also, for some reason I can't explain, using \> in when comparing gameTime.TotalGameTime.Seconds to autoChangeTime.Seconds will not work. It only worked when I used == to compare them, which is fine because there are quite a few Update cycles where gameTime.TotalGameTime.Seconds is equal to autoChangeTime.Seconds.

# Answer
> 0 votes
The problem is, if you use == and if update() is delayed for over a second when it reaches changeTime, then it wont ever be true. I cannot see why \> would not work either they are both Ints? Have you tried nesting the two parts of the if statement to see if it works on its own after you have checked for the key presses?

# Answer
> 0 votes
You are correct, if you simply set it (=) it will only ever be equal to the time since the last update call. If add that time each iteration however, you'll create the timer you originally needed.

```
 switch (currentState)
        {
            case States.otherStuff:
                timer = 0;
                if (!condition)
                    currentState = States.splashscreen;
                break;
            case States.splashscreen:
                timer += gameTime.ElapsedGameTime.TotalSeconds;
                if (condition || timer >= maxWaitTime)
                    currentState = States.otherStuff;
                break;
            default:
                break;
        }

```

---
Tags: monogame, screen-management
---


# Question
Title: Breaking up a map so countries can be colored separately in Spritekit
I'm currently trying to build a little strategy game where players take control of countries on an world. Each player's countries are represented by having a different color background but as each country is a different irregular shape I'm wondering how best to build this. To be clear I know how to change the color of a sprite or texture, but I'm wondering if there's a better approach to building the map then I outline below

My initial thought is that I export each individual country sprite and then use a shader etc. to change the background color when required. To do this I would obviously need to piece together each scene manually and make sure my countries line up correctly against each other to form the whole world.

This means I can't really create any 'dynamic' worlds. i.e. each map has to be hand curated.

Is there a better way to approach this without having uniform shaped countries? Bearing in mind this is a 2D game and there isn't really physics, could I use a physics body or something similar to get the actual shape of a country, and perhaps make sure each sprite has a white/transparent background then just change that particular color? Leaving the border black or whatever color I choose.

My fallback option is just having a building on each country that has a flag representing the faction color as this would be a lot easier to do.

# Answer
> 1 votes
There are a few methods one could use to create procedural irregular shapes that are individually capable of being colored. The simplest of these is likely to use SKShapeNode to create a Node based on a CoreGraphics path. You could use other means of creating procedural irregular shapes, but this is the most straight-forward when working with SpriteKit.

A less procedural but even more straight-forward solution, you could layer multiple sprites on top of one another. If you wanted shapes that were seemingly random but that gives you more control over the process, you can create small parcels of irregular shapes, assigning them to SKSpriteNodes and combining them to form a larger shape.

The number, types, rotations, and placements of these shapes could all be randomized to give significant diversity, and then they can be grouped together as children under the same (Empty) node. This node could then be given a color, applied to all the parcels, and would seem to the user as a single, indivisible, random shape of color.

---
Tags: spritekit, swift
---


title: How to Create Snakelike Objects

text:
# Question
Title: How to Create Snakelike Objects
I am working on a 2D action platformer in Python, though my question is a general one about creating snakelike objects which move in a variety of patterns.

I have noticed this kind of object in many 2D games. For example, this boss in Contra has snakelike arms.

And this enemy from Super Metroid clearly seems to be composed of multiple segments.

I want to create snakelike objects in my game, though I don't know where to begin or what I may need to add to my physics engine to support them.

So far, all my enemies and hazards consist of single sprites and are programmed using simple attributes like velocity, acceleration, parametric curves, etc.

Maybe I need to create a class for the segments, designate one segment instance as the leader, and update the positions of the other segments based on the position of the segment in front of it. But how do I program different patterns of movement? Do I need to learn about so-called *joints* and implement them between the segments? I currently don't have them in my engine.

I know I could easily create a segmented object where each non-leader segment is moved to the previous position of the segment in front of it (like in classic Snake, described here), but I want more complex patterns than this. Sometimes I may want the object to be flailing from an anchored point, and other times I may want it to be following some pattern across the screen.

I really don't know where to begin in trying to create this kind of object and would greatly appreciate any advice.

**How do you implement snakelike objects with a variety of movement patterns?**

(Given the ubiquity of this kind of object in games, I was surprised that I couldn't easily find much about it online. I think a detailed write-up on it would be cool.)

# Answer
> 1 votes
Yes, you would add a distance-constraint (known also as ball-socket joint) between the segments, and keep doing your normal physics on each segment.

There is a really simple and effective way to satisfy these constraints, which can be implemented in only a few lines of code.

The idea is that you reduce the error in a constraint partially, over and over for all constraints, in a loop. If you keep reducing the error by, let's say 20% in each iteration, it will eventually settle to a stable state where all the constraints are satisfied.

Note that it helps to keep the head position of the snake as-is, to make the tail follow the head, instead of vice versa.

So in pseudo code:

```
for i in range 1..10:
    for each link between segments:
        actual_dist = distance(body0, body1)
        error = actual_dist - desired_dist
        // fix 20% of the error in body0/body1 distance.
        if body0 is not snakehead:
            move body0 (0.1*error) units towards body1
        if body1 is not snakehead:
            move body1 (0.1*error) units towards body0

```

..which is all you need to have the tail follow the head.

NOTE: you get a slightly faster convergence, and more stable solution if you reduce the error in the links in a random order! So in the 10 times we scan over the links, we update them in a different order.

---
Tags: 2d, physics, movement, python, joints
---


# Question
Title: calculating the trajectory of an object in SpriteKit when an impulse is applied to it
I want to make a trajectory line of little balls of where the object is going to go after an impulse, sort of like what is in Angry Birds. I did some research and it seems that the physics in spriteKit are calculated just as in real life with si units and other stuff. Using the displacement formula ∆x = Vi∆t + 1/2a∆t^2 i used this formula to set the position of nine balls of where the object will be after the impulse.

This is what I have tried so far:

```
func calculateTrajectory(mass: CGFloat, force1: CGFloat, force2: CGFloat){

    for i in 0...8{

        var x = CGFloat()
        var y = CGFloat()

        let a1 = CGFloat(force1/mass)//I am taking the force applied to the object and calculating the acceleration from that
        let a2 = CGFloat((force1/mass) - 10)//I am subtracting 10 for y because of the -10m/s/s of gravity
        let t = CGFloat((i/16)^2)//I am taking the number that the ball is in the line and dividing it by 16 so the line can show where the object will be from 0-0.5 secnds

        x = 0.5 * a1 * t
        y = 0.5 * a2 * t

        trajectory.copiedNodes[i].position = CGPoint(x:ball.position.x + x, y: ball.position.y + y)

    }

}

```

I also use this in touches moved to do a drag back sling shot sort of thing.

```
calculateTrajectory(mass: (ball.physicsBody?.mass)!, force1: startPositionDrag.x - movedLocation.x, force2: startPositionDrag.y - movedLocation.y)

```

The force for calculation is the same as impulse that I will use to shoot the ball in touches ended:

```
ball.physicsBody?.applyImpulse(CGVector(dx:startPositionDrag.x - endPositionDrag.x, dy:startPositionDrag.y - endPositionDrag.y ))

```

When I calculate this the balls are not close to where the object goes, and when I make the time change for the balls a shorter time amount by dividing i by more, the balls get farther apart even though I am calculating their positions after less time. Is there any way I am doing this wrong? Are my conversions to CGFloat wrong? Please help me.

# Answer
> 0 votes
A much more straightforward solution is simply to make a hidden or transparent copy of the projectile, remove collision masks, and launch it. You can either leave a trail of small sprite nodes at various points in its lifespan, or you could utilize a particle emitter so it leaves a trail of short-life particles in its wake. Finally, remove the projectile and trail if the user changes angles, cancels the launch, or launches the real projectile.

No math, no random variables you didn't consider, and it doesn't break if you make the scenario more complicated in the future (changing gravity, adding gravitational fields, etc). Even if you decided to add wind speed that varied moment to moment, this model would compensate if updated consistently.

---
Tags: physics, spritekit, swift
---


# Question
Title: 3rd person camera rotate around player with mouse
I'm trying to make a 3rd person camera for a game with THREE.js and Physijs (if that's important), and so far I have set it up so that the camera follows behind the player using cos and sin etc. but I want to make it so that the user can rotate the camera in any direction around the player (and zoom in and out of course), and then when the player starts moving slowly lerp/reset the camera position to behind the player, but I'm not sure how to do this in THREE.js, I don't think OrbitControls let's it reset the position (or does it)?

# Answer
> 1 votes
I would recommend what I found in this stackexchange answer, second part.

In this answer, it gives a link to this website, using it as an example of rotation using your mouse in THREE.js.

Essentially what this link does is create a new `THREE.TrackballControls` object:

```
controls = new THREE.TrackballControls( camera );
controls.target.set( 0, 0, 0 )

```

It then sets the controls, which you can change to your liking, like so:

```
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;

controls.noZoom = false;
controls.noPan = false;

controls.staticMoving = false;
controls.dynamicDampingFactor = 0.15;

controls.keys = [ 65, 83, 68 ];

```

This is all you really need to do, although you don't want to forget your event listeners.

Another example will be on threejs.org, where it shows you trackball controls and has a link to the source, instead of making you use developer tools in Chrome or whatever your web browser uses.

I'm unsure about zooming while rotating, but I'm pretty certain you can zoom at any point after you are done rotating.

I am however, pretty certain that OrbitControls lets you reset it. I think this code should work:

```
this.resetCamera = function ( ) {
    this.object.position.x= camera_initial_position.xPosition;
    this.object.position.y = camera_initial_position.yPosition;
    this.object.position.z = camera_initial_position.zPosition;
    this.center.x= camera_initial_target.x;
    this.center.y= camera_initial_target.y;
    this.center.z= camera_initial_target.z;
};

```

As long as you set the function `resetCamera` to occur upon some key-press (I'm assuming), that should work. If not use this code:

```
this.resetCamera = function ( ) {
    this.object.position.x= camera_initial_position.xPosition;
    this.object.position.y = camera_initial_position.yPosition;
    this.object.position.z = camera_initial_position.zPosition;
    this.center.x= camera_initial_target.x;
    this.center.y= camera_initial_target.y;
    this.center.z= camera_initial_target.z;
};

```

---
Tags: three.js
---