# Question
Title: A logic error. canvas: balls physics, bounce
Hi I was making a program that simulate a bunch of balls bouncing, but the problem is some balls got stuck to the floor. Since it's a logic error, it is kind of difficult to find. Can someone help, I let the snipper code below thanks.

```
var output = document.getElementById('output');
var canvas = {};
var ball = [];

canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;
canvas.clear = function() {
  canvas.ctx.clearRect(0, 0, canvas.width, canvas.height);
};
canvas.preferences = function() {
  canvas.ctx.strokeStyle = 'rgb(210,210,210)';
  canvas.ctx.lineWidth = 1;
};

const FRICTION = .9;
const MIN_ACCELERATION = 1;
const FRICTION_INCREASE = .015;
const DIST = 20;
const N_BALLS = 50; // BALLS NUMBER
const GROUND = canvas.height;

var Object = function() {
  this.yVel = 0;
  this.gForce = 0.2;
  this.friction = FRICTION;
  this.full = false;
  this.run = true;

  this.draw = function() {
    canvas.ctx.beginPath();
    canvas.ctx.arc(this.x, this.y, this.radio, 0, Math.PI * 2);
    canvas.ctx.stroke();
  };

  this.physics = function() {

    this.y += this.yVel;

    if (this.y + this.radio < GROUND) {
      this.yVel += this.gForce;
    } else if (this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION) {
      this.yVel *= -this.friction;
      this.y = GROUND - this.radio;
      this.friction -= FRICTION_INCREASE;
    } else {
      this.yVel = 0;
      this.y = GROUND - this.radio;
      this.run = false;
    }
  };
};

var generateBalls = function(p) {

  var i, random;

  for (i = 0; i < N_BALLS; i++) {
    p[i] = new Object();

    random = Math.floor(Math.random() * 18) + 5;
    p[i].radio = random;

    random = Math.floor(Math.random() * 22) + 1;
    p[i].x = DIST * random;

    random = Math.floor(Math.random() * 15) + 1;
    p[i].y = DIST * random;

  }
};

var drawBalls = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].draw();
  }
};

var applyPhysics = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].physics();
  }
};

generateBalls(ball);
canvas.preferences();
var program = setInterval(function() {

  canvas.clear();
  drawBalls();
  applyPhysics();

}, 1000 / 60);
```

```
canvas {
  border: 1px solid rgb(210, 210, 210);
}

body {
  background: black;
  color: rgb(210, 210, 210);
}
```

```
<canvas id="canvas" width="450" height="400"></canvas>
<p id="output"></p>
```

# Answer
> 2 votes
To figure out what is going on, I started looking at the code that moves the balls. In this case it is `physics` (`fisicas`). I see two coditionals where you stop the ball:

```
if (this.y + this.radio < GROUND) {
  this.yVel += this.gForce;
} else if (this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION) {
  this.yVel *= -this.friction;
  this.y = GROUND - this.radio;
  this.friction -= FRICTION_INCREASE;
} else {
  this.yVel = 0; // <---- STOP CASE
  this.y = GROUND - this.radio;
  this.run = false;
}

```

The above is the code we will be working on.

---

To graps what is the problem I deviced a way to debug it visually. What I did is change the color of the balls depending on the condition. The first case will be cyan, the second magenta. Let's see what happens:

```
var output = document.getElementById('output');
var canvas = {};
var ball = [];

canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;
canvas.clear = function() {
  canvas.ctx.clearRect(0, 0, canvas.width, canvas.height);
};
canvas.preferences = function() {
  canvas.ctx.strokeStyle = 'rgb(210,210,210)';
  canvas.ctx.lineWidth = 1;
};

const FRICTION = .9;
const MIN_ACCELERATION = 1;
const FRICTION_INCREASE = .015;
const DIST = 20;
const N_BALLS = 50; // BALLS NUMBER
const GROUND = canvas.height;

var Object = function() {
  this.yVel = 0;
  this.gForce = 0.2;
  this.friction = FRICTION;
  this.full = false;
  this.run = true;
  this.stroke = 'rgb(210,210,210)';

  this.draw = function() {
    canvas.ctx.beginPath();
    canvas.ctx.arc(this.x, this.y, this.radio, 0, Math.PI * 2);
    canvas.ctx.strokeStyle = this.stroke;
    canvas.ctx.stroke();
  };

  this.physics = function() {

    this.y += this.yVel;

    if (this.y + this.radio < GROUND) {
      this.yVel += this.gForce;
    } else if (this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION) {
      this.yVel *= -this.friction;
      this.y = GROUND - this.radio;
      this.friction -= FRICTION_INCREASE;
      this.stroke = 'rgb(0,210,210)'; // Cyan
    } else {
      this.yVel = 0;
      this.y = GROUND - this.radio;
      this.run = false;
      this.stroke = 'rgb(210,0,210)'; // Magenta
    }
  };
};

var generateBalls = function(p) {

  var i, random;

  for (i = 0; i < N_BALLS; i++) {
    p[i] = new Object();

    random = Math.floor(Math.random() * 18) + 5;
    p[i].radio = random;

    random = Math.floor(Math.random() * 22) + 1;
    p[i].x = DIST * random;

    random = Math.floor(Math.random() * 15) + 1;
    p[i].y = DIST * random;

  }
};

var drawBalls = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].draw();
  }
};

var applyPhysics = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].physics();
  }
};

generateBalls(ball);
canvas.preferences();
var program = setInterval(function() {

  canvas.clear();
  drawBalls();
  applyPhysics();

}, 1000 / 60);
```

```
canvas {
  border: 1px solid rgb(210, 210, 210);
}

body {
  background: black;
  color: rgb(210, 210, 210);
}
```

```
<canvas id="canvas" width="450" height="400"></canvas>
<p id="output"></p>
```

As expected the balls turn magenta when they stop moving. This is just what we expected, we haven't discovered anything yet.

The next thing I will do is let the balls keep moving. This is the result:

```
var output = document.getElementById('output');
var canvas = {};
var ball = [];

canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;
canvas.clear = function() {
  canvas.ctx.clearRect(0, 0, canvas.width, canvas.height);
};
canvas.preferences = function() {
  canvas.ctx.strokeStyle = 'rgb(210,210,210)';
  canvas.ctx.lineWidth = 1;
};

const FRICTION = .9;
const MIN_ACCELERATION = 1;
const FRICTION_INCREASE = .015;
const DIST = 20;
const N_BALLS = 50; // BALLS NUMBER
const GROUND = canvas.height;

var Object = function() {
  this.yVel = 0;
  this.gForce = 0.2;
  this.friction = FRICTION;
  this.full = false;
  this.run = true;
  this.stroke = 'rgb(210,210,210)';

  this.draw = function() {
    canvas.ctx.beginPath();
    canvas.ctx.arc(this.x, this.y, this.radio, 0, Math.PI * 2);
    canvas.ctx.strokeStyle = this.stroke;
    canvas.ctx.stroke();
  };

  this.physics = function() {

    this.y += this.yVel;

    if (this.y + this.radio < GROUND) {
      this.yVel += this.gForce;
    } else if (this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION) {
      this.yVel *= -this.friction;
      this.y = GROUND - this.radio;
      this.friction -= FRICTION_INCREASE;
      if (this.stroke == 'rgb(210,210,210)')
      {
          this.stroke = 'rgb(0,210,210)'; // Cyan
      }
    } else {
//        this.yVel = 0;
      this.y = GROUND - this.radio;
      this.run = false;
      this.stroke = 'rgb(210,0,210)'; // Magenta
    }
  };
};

var generateBalls = function(p) {

  var i, random;

  for (i = 0; i < N_BALLS; i++) {
    p[i] = new Object();

    random = Math.floor(Math.random() * 18) + 5;
    p[i].radio = random;

    random = Math.floor(Math.random() * 22) + 1;
    p[i].x = DIST * random;

    random = Math.floor(Math.random() * 15) + 1;
    p[i].y = DIST * random;

  }
};

var drawBalls = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].draw();
  }
};

var applyPhysics = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].physics();
  }
};

generateBalls(ball);
canvas.preferences();
var program = setInterval(function() {

  canvas.clear();
  drawBalls();
  applyPhysics();

}, 1000 / 60);
```

```
canvas {
  border: 1px solid rgb(210, 210, 210);
}

body {
  background: black;
  color: rgb(210, 210, 210);
}
```

```
<canvas id="canvas" width="450" height="400"></canvas>
<p id="output"></p>
```

---

We observe that the magenta balls keep bouncing. Thus we know that they had **speed** when they reached the stop case. This tell us that we were stopping them prematurely.

What we learned is that we are stopping the balls when they still had plenty of speed left. We shouldn't stop them until their speed is marginal.

---

Enough of visual debugging. Let us have a closer look at the code...

What is the logic to get to the stop case?

```
if (this.y + this.radio < GROUND) {
  // ...
} else if (this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION) {
  // ...
} else {
  // STOP CASE
}

```

To get there these must be false:

```
this.y + this.radio < GROUND
this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION

```

Provided that you have already checked `this.y + this.radio < GROUND` in the first conditional, we can assume that for the other cases this is true:

```
this.y + this.radio >= GROUND

```

Thus, the conditional

```
this.y + this.radio > GROUND && this.yVel > MIN_ACCELERATION

```

will fail in either of these situations:

```
this.y + this.radio == GROUND
this.yVel <= MIN_ACCELERATION

```

The first situaton is unlikely. We are not taking into account floating point errors in the comparisons. Still, it is worth noting that **if the ball happens to hit the ground perfectly, it will be stuck, regardless of speed**.

The second situation is problematic. Any negative value for `this.yVel` will pass `this.yVel <= MIN_ACCELERATION`. In this case a negative value is a downward speed, meaning that the ball should bounce.

---

To fix it. First, I suggest to only check for GROUND once. Here:

```
if (this.y + this.radio < GROUND) {
  // ...
} else if (this.yVel > MIN_ACCELERATION) {
  // ...
} else {
  // STOP CASE
}

```

This removes the edge situation where the ball is stuck because it hit the ground perfectly. It also makes it easier to reason about the other situation.

You want to bounce when the magnitud of `this.yVel` is greater than `MIN_ACCELERATION`. Then write that:

```
if (this.y + this.radio < GROUND) {
  // ...
} else if (Math.abs(this.yVel) > MIN_ACCELERATION) {
  // ...
} else {
  // STOP CASE
}

```

Now, you will reach the STOP case when these are false:

```
this.y + this.radio < GROUND
Math.abs(this.yVel) > MIN_ACCELERATION

```

In other words, to reach the stop case these must be true:

```
this.y + this.radio > GROUND
Math.abs(this.yVel) <= MIN_ACCELERATION

```

I know the first one is weird. It says that the ball is slightly burried in the ground. Although, as I said, there are floating point errors. The relevant part is that the speed of the ball has a very small magnitud. That is, it wouldn't have bounced too high. Now it is matter of tweaking `MIN_ACCELERATION` for your taste.

Let us see the result:

```
var output = document.getElementById('output');
var canvas = {};
var ball = [];

canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;
canvas.clear = function() {
  canvas.ctx.clearRect(0, 0, canvas.width, canvas.height);
};
canvas.preferences = function() {
  canvas.ctx.strokeStyle = 'rgb(210,210,210)';
  canvas.ctx.lineWidth = 1;
};

const FRICTION = .9;
const MIN_ACCELERATION = 1;
const FRICTION_INCREASE = .015;
const DIST = 20;
const N_BALLS = 50; // BALLS NUMBER
const GROUND = canvas.height;

var Object = function() {
  this.yVel = 0;
  this.gForce = 0.2;
  this.friction = FRICTION;
  this.full = false;
  this.run = true;
  this.stroke = 'rgb(210,210,210)';

  this.draw = function() {
    canvas.ctx.beginPath();
    canvas.ctx.arc(this.x, this.y, this.radio, 0, Math.PI * 2);
    canvas.ctx.strokeStyle = this.stroke;
    canvas.ctx.stroke();
  };

  this.physics = function() {

    this.y += this.yVel;

    if (this.y + this.radio < GROUND) {
      this.yVel += this.gForce;
    } else if (Math.abs(this.yVel) > MIN_ACCELERATION) {
      this.yVel *= -this.friction;
      this.y = GROUND - this.radio;
      this.friction -= FRICTION_INCREASE;
      if (this.stroke == 'rgb(210,210,210)')
      {
          this.stroke = 'rgb(0,210,210)'; // Cyan
      }
    } else {
      this.yVel = 0;
      this.y = GROUND - this.radio;
      this.run = false;
      this.stroke = 'rgb(210,0,210)'; // Magenta
    }
  };
};

var generateBalls = function(p) {

  var i, random;

  for (i = 0; i < N_BALLS; i++) {
    p[i] = new Object();

    random = Math.floor(Math.random() * 18) + 5;
    p[i].radio = random;

    random = Math.floor(Math.random() * 22) + 1;
    p[i].x = DIST * random;

    random = Math.floor(Math.random() * 15) + 1;
    p[i].y = DIST * random;

  }
};

var drawBalls = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].draw();
  }
};

var applyPhysics = function() {
  var i;

  for (i = 0; i < N_BALLS; i++) {
    ball[i].physics();
  }
};

generateBalls(ball);
canvas.preferences();
var program = setInterval(function() {

  canvas.clear();
  drawBalls();
  applyPhysics();

}, 1000 / 60);
```

```
canvas {
  border: 1px solid rgb(210, 210, 210);
}

body {
  background: black;
  color: rgb(210, 210, 210);
}
```

```
<canvas id="canvas" width="450" height="400"></canvas>
<p id="output"></p>
```

I guess it is working correctly. The code depends on random... perhaps I am being lucky? I have confidence it is correct, I have tested it, it makes sense.

---

I could not help but think that having a repeatable test would have made things easier.

You are setting it up with random (which is ok for a data driven test), although, once you find a bug, we would advise to capture the initial conditions that lead to the bug and use them to make a reproducible test case.

In your particular problem, you may refactor the code to store a copy the initial conditions of the balls and write them to the console when they reach the stop case. If you can hardcode those the initial conditions, you can find situations when the ball gets stuck right away. That would serve as a test that predictably fails. Once you have that, it eaases debugging by stepping to you.

That is not a universal solution, racing conditions and other performance sensitive behavior creates “heisenbugs”, which resist repeatability.

---

If I had a test that didn't depend on random, I would have to guess it is working correctly. I would have evidence.

---

By the way, you are not using `this.run`. If you intend to use it as an optimization where you do not compute the motion of the ball when `this.run` is `true`. Then I suggest to remove the ball from the list instead, so that you don't even get an iteration for that ball... On that note, separate the list for physics from the list for drawing (that way you can remove them from the physics list but it will still be drawn). You would need that separation anyway if you want a large world and only draw what is visible to the "camera" but keep simulating the world.

---

There is another thing I want to mention: your physics assume the iterations happens at constant intervals. While `setInterval` should keep it relatively stable, there could be value in considering the elapsed time in the physics computation. Although that is not suitable for every game and it is off-topic for this question.

---
Tags: javascript, html-canvas, gameobject, objects
---


# Question
Title: How do I scale up pixel art without blur in GM Studio?
I'm creating a game in Game Maker Studio that uses pixel art. When I launch the game, all scaled-up textures are really blurry. (It doesn't happen to small ones.)

For example, this image

renders in the game like this:

Is there anyway to resize *small pixels* into *big pixels* instead of *blurred pixels*?

# Answer
> 15 votes
Found a solution from some resource. Go to Global Game Settings, then go to any platform spoiler(for example "Windows" or "Android"), there choose the spoiler titled "Graphics" and toggle "Interpolate colors between pixels" off. Have fun :)

# Answer
> 5 votes
Nobody wants to deal with having to manually scale up every sprite; not only is it a sloppy workspace but it yields to be very unprofessional. I found a solution when turning off interpolation in global game settings didn't work.

```
texture_set_interpolation(false);

```

:) I hope this helps you in your future endeavors.

# Answer
> 1 votes
Turn off the scale function in the backgrounds tab in the map. If it seems out of scale make sure your texture for the back ground is the same size as the room/map you're in.

Alternatively use this post here to create a background script that will upscale the back ground with (hopefully) crisp results.

This utilises surfaces so if you need some extra help on that - this post provides a lot of information.

---

**EDIT:**

Going back on my answers I realized this is not up to scratch and needs the tutorial content. Here it is:

**STEP 1**: Choose the scale you want. Use a view for every room and have the port W and port H scaled appropriately. So, for example, if you were using a scale of 2... it would look like this, in GM's room editor.

It is important that this is consistent for all rooms. If you have lots of rooms, it might be easier to do this via code\*. I prefer to do it that way, because then the values aren't constant and I can support multiple different scales.

**STEP 2**: Create 3 scripts, screen\_init, screen\_begin, and screen\_end. Here is what goes in each of the scripts...

Quote from: screen\_init

```
// screen base(view_wview and view_hview)
screen_x = 0;
screen_y = 0;
screen_w = 320;
screen_h = 240;
screen_scale = 2;

// create a surface for the whole screen to be drawn on
screen = surface_create(screen_w,screen_h);

// this will destroy the screen object if surfaces are not supported on the graphics card, reverting to the viewport method
if screen = -1{instance_destroy();}

```

Quote from: screen\_begin

```
// this draws the surface on the screen
surface_reset_target();
draw_clear(0);
draw_set_blend_mode_ext(bm_one, bm_zero);
draw_surface_stretched(screen,screen_x,screen_y,screen_w*screen_scale,screen_h*screen_scale);
draw_set_blend_mode(bm_normal);
screen_refresh();

```

Quote from: screen\_end

```
// this sets surface 'screen' as the drawing target for everything in the game, so all drawing will be done on this surface and not on the game screen
surface_set_target(screen);

```

**STEP 3**: Now we have are scripts, but where do they go? Create an object. Like, obj\_screen, objScreen, o\_screen, or whatever, and do the following:

* A) place the screen\_initscript in the Create event.
* B) place the screen\_begin script in the Begin Step event.
* C) place the screen\_end script in the End Step event.

And place that object in the first and foremost room of your game, mark it persistent, and make sure there are no duplicates of it.

You're done, and now have nice, crisp scaling =D

# Answer
> 1 votes
What I do generally for this is either using photoshop or GIMP ( scale/Nearest Neighbour)

But to do it in the GM:S sprite editor itslef, I use the Stretch command instead of scale and set it to POOR quality. That will keep the Blocky sort of feel

Above is a game im workin on ATM, i did just that!

# Answer
> -2 votes
Use `texture_set_interpolation(false)` to make it draw them as is.

---
Tags: pixel, game-maker, blur, scale
---


title: How to visualize objects in darkness

text:
# Question
Title: How to visualize objects in darkness
Below I've an image of my current scene, and two images of what I want to achieve. Now the question is, how can I visualize objects in low light, as you can see the current scene isn't that attractive however the pic from kentucky route zero is soul capturing, so what should I do? Any type of guidance will be appreciated c:

Current Scene:

Required Output:

# Answer
**Work with different shades of black**

The images you mention to be the goal you want to achieve do not care about the *real* colour of objects. Instead they make use of different shades of black to create an illusion of depth and to distinguish different silhouettes.

* Use a *clean black* for the frontmost objects. E.g. the motorcycle, the truck and the pier.
* Add more dark blues to the mix the farther an object is away to allow distinguishing shapes and silhouettes. E.g. the night sky, the stalagmites.
* Overlay greys to make things look fuzzy & blurred. E.g. the trees next to the street, the caverns.
* Add light-sources to *backlight* things you want to emphasize. E.g. the motorcycle, the truck.
> 2 votes

---
Tags: lighting, low-poly
---


# Question
Title: Object movement to a circular shape, with the grab of a VR controller?
I have a HTC Vive VR set, which has a controller. I have a sphere object, which I want to rotate in a circular motion around my VR Player object, based on the controller grab and its movement. The controller should first grab the object, then it will move left or right, in a circular motion, based on the controller movement. How can I achieve this?

---

So far, I have made a sphere, with a parent. The parent position is updating with respect to my camera head, so I can move my sphere with my player. The sphere object should move with the controller, but in a circular motion. This has not been achieved, yet, and I really don't know how to do it.

I am able to grip the sphere object using a VRTK script, and I can freely move it, but I want to restrict its movement; much like in the illustrated figure, below:

# Answer
> 1 votes
So you want to restrict the usual spherical movement that occurs as you move the Vive controller around, to a sort of equatorial, planar movement. I'm going to assume that as in this tutorial, your Vive controllers and head are all part of the same transform hierarchy (what they call `CameraRig` there).

**Option A: If you can get the Vive Controller's rotation around the camera (rig).** Put sphere into a swivel which is an empty `GameObject`, having a transform only. Zero the sphere's local position in the inspector. Make sure swivel's `transform.position` tracks that of the head camera. Set sphere's `transform.localPosition=1` to move it slightly forward of the player's head. Set swivel's `transform.localEulerAngles.y` and `.z` to the same as the Vive controller's `transform.localEulerAngles`, but limit `transform.localEulerAngles.x = 0` on each sphere `Update()`. This prevents tilting (up/down) while maintaining heading (north/south/east/west) just like the Vive controller's `transform` to which it is attached.

**Option B: Possibly Simpler.** You want that plane / circle to be around your head, and I think it is never tilted (the validity of this answer relies on this fact). In every sphere `Update()`, set sphere's `transform.position.x` and `.z` to that of the Vive controller's `transform.position`, but set sphere's `transform.localPosition.y` equal to desired (head camera) `y`, every frame. You can also set the `transform.rotation` to the same as the Vive controller, if you need that.

**For both options A & B** These will superficially work, but you will find that if you look up or down then the sphere will get slightly closer or further away. This is because we are essentially projecting the sphere co-ordinates onto a flat circle. To prevent this i.e. to keep a fixed radius, set sphere's `transform.localPosition.z` to the distance you want, which might be the distance between the Vive controller and your camera, which is easy to compute, or you could always set it to, say, 1 unit.

**Option C**: **If the sphere is a child of the Vive controller GameObject.** Set Vive controller's `transform.localEulerAngles.x` (or *maybe* `.z`) `= 0` each frame. Provided your logic runs *after* the Vive controller's logic, this will do the trick of keeping your object on the circle. Assuming you don't care whether you limit the controller object or the sphere itself, this is the easiest method.

From a mathematical standpoint, we are really just projecting a sphere onto a plane. Between these varied approaches, you should be able to work to a solution. Feel free to ask questions, below.

---
Tags: unity, c#, virtual-reality
---


# Question
Title: Entity-Component-System data storage design
I'm working on an ECS and I've already read a lot of articles about it. Most of these articles are talking about a simple case (store data contiguously, read it in a single for loop). However the real world is more complex: one system reads multiple components and those have to be read fast.

So I'm thinking on a new data storage model but before I start to implement it, I'd like to know what do you think: I'm not sure if this design would solve any (future) performance problem (I'm thinking about cache coherency, prefetching, etc. optimization).

So the basics are the same:

* Each Entity is a handle (id + version number together).
* Each Component is a(n ideally small) POD.
* Each System is responsible for the processing of a set of components.

**The first idea** in every article is to store the component data in an array (of each type) and use a fast-lookup map (eg. hash\_map) for the entity\_id-\>component\_id relation.

Eg. the Position component pack looks like this:

```
component data:
[pos_0][pos_1]...[pos_n]

entity->component map:
[entity_0 -> 1][entity_2 -> 0]...[entity_m -> n]

```

This works well if the systems are reading a single type of component linearly. If a system wants to read another component as well, it will generate at least two additional cache misses:

* one for the entity\_id-\>component\_id lookup (to find the other component from the entity)
* and one for the actual component data

**So my idea** is that instead of separating the components I could create groups. Each group has the same behaviour like before (the data laid out contiguously and an entity\_id-\>component\_id map is stored for fast component lookup) but the data stores multiple component data.

The point is that the component data is stored in the same order as the other components so if a system wants to read eg. the Position + Velocity component set it can iterate linearly on the array. Each component type has an offset to indicate where it starts on the big array.

So the Position+Velocity group looks like this:

```
component data:
[pos_0][pos_1]...[pos_n][... some space ...][vel_0][vel_1]...[vel_n]... and so on

entity->component map:
[entity_0 -> 1][entity_2 -> 0]...[entity_m -> n]

```

And if I'm interested in a component set of a single entity, I can use the map to find the component id then read the components using this id:

```
component_id = find(entity_id);
comp_0 = data[offset_of(comp_0_type) + component_id]
comp_1 = data[offset_of(comp_1_type) + component_id]

```

The biggest drawback is the larger array: when the array has to grow it has to allocate and copy more data at once. But IMHO the whole idea could work because most of the time (in my experience at least) an entity's components are not changing at run-time.

Note: I tagged c++ as well, because I'm using c++.

**Edit**

Actually I've found a problem with this approach. This way the components cannot refer to each other. Eg a Transform component is responsible for structuring the "objects" in a tree, so each Transform component has a parent and a children property. However with this design I don't know how I could refer to the other Transform component since it can be in any group's array.

**Edit 2**

For the first iteration I'm going to implement a simple design, similar to the "*Packed Array*" described here.

# Answer
> 1 votes
There are some problems with this data approach I want to point out.

First of all you assume that you have a fixed number of components for each type. If not, you either waste memory if you have to few of one component type, or no memory for to many. And you can't easily expand your it

Second is, you most likely still have the cache misses from your first idea, since the whole array won't fit into the L1-cache. Since your data is contiguous it's less problematic, but depending on what component your system is working on, it might be a problem: first you compare data from component type 1 with type 12 (maybe already out of cache), then read data from component 3 to write to component 12 again.

Third is just a speculation: do you create every component from the beginning or when you need it? It seems you want to do the first, in that case you have to check if a component is active or not. If you want to do it (or even iterate) over the hashmap, those will most likely generate cache misses again and again.

My approach is to have some sort Node, that has an ID and a copy of some components with the same ID. The systems are only working on those Nodes and only Nodes with all required components with the same ID exist. It has a bit of redundancy, but that's intentional with networking in mind and data changes are gated by its own system.

# Answer
> 0 votes
There is no perfect ECS. Each architetural approach to ECS have pros & cons.

Let me evolve your idea a bit. You have groups, then why not having group of entity types? That's it, for every different Entity type you make a group, so you know the Entity ID because when you are iterating you just need to know the index:

**Pros:**

* you already know the ID of the processed entity in your group
* you just need to store a short ID if you need to reference the ID of another entity in the same group (16 bits may suffice).
* best cache coerency for data
* Extremely simple to use (you don't have to manage groups, those are automatic)

**Cons:**

* Update order undefined (if you use instant event dispatch this is not a problem, you just need to be carefull with the few "Updated" stuff).
* Not best cache coerency for instructions (but usually this is ok).
* To refer another entity you need to identify both Group and Index inside group, but the good news is that you can probably just use 16 bits for Group and 16 bits for index.

**How to implement:**

```
foreach( var x in entityTree.EntityTypes())  // tree breadth traversal
    foreach( var s in x.UpdatableSystems()) // only a bunch of systems need actually udpating
        s.Update( x.ComponentsForSystem(s));

```

where

```
x.ComponentsForSystem(s)

```

is actually a IEnumerator, or another kind of structure that allow to decouple data layout from iteration so you can use what you want:

* Struct of Arrays
* Array of structs
* Linked List

The usual error with ECS is to find System based on "which" components, instead you have to find Components based on your system.

> Usually I see people creating entities by randomly sticking components togheter, then the ECS frameworks figure out how to map Entities to Systems, Instead I find much more natural just "registering" a empty entity in a system, it will be the system to add the components it needs (if those are not already added by another system, in that case we can even log a warning if desired). There's no longer need to filter entities to find them.

The only little problem to solve is how to identify "EntityType", but that is pretty simple:

* You sort components, then you just need to make a "types tree", if you find a leaf of your type you know already in which group spawn the entity, if you don't find the leaf you create a new group. (the previous code snippet infact refers to a "tree traversal").

You EntityHandle will be a 32 bit integer:

**Actually I use:**

* 1 bit to identify a special case, where groups have more than 65k entities (7 bit identify group, 24 bit identify entity)
* if the bit flag is not set then 15 bit are for group and 16 bit for entities.

And I can achieve better performance than ECS frameworks that have "Manual Groups". Still I have also less code to write, I just compose entities and new groups are added on the fly.

---
Tags: c++, architecture, component-based, entity-component
---


# Question
Title: How are walkable regions determined, and movements handled on a 3D map?
I've created a 3D scene with both indoor and outdoor parts. The outdoor part has bridges and caves also.

How is it possible to handle player movements on it?

My intuition is: To determine the walkable regions, I could create a large grid. If the normal under the segment is not too steep, then it is walkable. If the difference between the heights of two neighboring segments in not large, then the player can move between them.

My solution is far from optimal. It would consume a lot of memory, and it can't handle situations, when there are multiple walkable regions on the same XZ position (for example a bridge over a valley)

How to manage movements effectively? How is it solved in game engines like Unreal or Unity?

# Answer
You spawn a bot in a known accessible location and then tell it to move a little bit in a few directions (the 8 cardinal and half-cardinals is usually enough) from that spot.

If it didn't hit anything you teleport the bot to those new locations and repeat. Add a nearness filter to previously explored points so you don't over-sample.

if it did hit something then you can probe in that general direction to discover the boundaries If you find 2 edge points nearby each other you can try and move through the middle of it.

Here is an article detailing on how you can achieve that.

Note that this method assumes the player cannot jump. If he can then you need to add jumps to the probes.
> 2 votes

# Answer
I think you are on the right track. One possibility to create a walkable area is to create a navigation mesh.
They can be created automatically and on good resource how it can be done can be found here.
They also make pathfinding for bots/AI pretty easy but as you said use up some memory.

As you guessed you can create this navigation mesh basically by getting the normal of triangles and depending on the angle determine if the area is walkable, if yes you can create a duplicate triangle and add it to the navigation mesh. Each vertice of the triangle acts as navigation node. Depending on the player or other agents the pathfinding can apply different rules for pathfinding as size of the agent.
When generating the navigation meshes there are many parameters you can change to modify it to your needs. One big benefit is that jumping between navigation meshes can be handled as well. You can create on multi purpose navigation mesh or many meshes with specific criteria as it suits your needs better.
> 2 votes

---
Tags: opengl, c++, 3d, movement, maps
---


# Question
Title: Unity's CharacterController vs. Rigidbody with Collider
With a few friends I started to make a 3D game in the style of the old platformers à la Super Mario 64 / Spyro / Banjo Kazooie.

So now we are thinking about the controls and how to do them.

There seem to be two mutually-exclusive options: Giving our character a rigidbody and however many colliders we want OR using a character controller.

* At the moment we have a rigidbody with a collider which technically works, but we have to make our own grounded check, and movement, while those two in particular are relatively easy to implement.
* If we start to use a character controller OTOH, we won't have all the collisions anymore and programming logic needs to be applied in a different way.

Let's take a jumppad as example:

* If we use a `Rigidbody`, the jumppad itself checks if someone is standing on it, and if so it increases the jumpstrength while that someone stands on it.
* If we use a `CharacterController`, we'd have to check not only if we are standing on a jumppad, but also on which one, to determine the actual jumpstrength, as they might differ between pads.

So, is there a clear winner to use in a 3D platformer with fighting elements or do we have to work with limitations on either and just have to work around them?

# Answer
It's not either-or. It's both.

Stick with the `CharacterController` initially. Go through the initial pain of writing it the way you want it under normal (kinematic) control circumstances, as there are things that `Rigidbody`s do to player characters that you won't like under various circumstances. It's like RL - we're generally in fine motor control of our bodies until we get hit by a bus or fall off a ledge. Characters likewise are primarily kinematic bodies, and take on rigid body / ragdoll characteristics only in cases involving large forces.

Your `CharacterController` would be your primary control manager, and as such it would handle default kinematic controls, but turn on / turn over control to a local `Rigidbody` component only once it becomes appropriate to do so (for example, when the player jumps and falls, or dies in water and floats to the surface). And e.g. once you respawned, you could have the `Rigidbody` relinquish control.

In circumstances like the jump-pad you mentioned, if you're in a kinematic mode at that point, I would just make the checks explicitly, as you suggested. Whereas if you were already falling i.e. were in physics mode, then of course the thing should take care of itself as you hit the pad.
> 3 votes

---
Tags: unity, c#, control, rigidbody
---


# Question
Title: Do Google/Apple provide the multiplayer servers for an app themselves?
I have an app that I have been working on and I was wondering does Google/Apple host the server requirements for the multiplayer aspects of an app?

# Answer
> 1 votes
It's unlikely you will find a free service for your hosting needs.

Google Cloud might not be free, but it has some appealing features. They're currently running a 60 day free trial campaign, and if you decide to keep it, prices are not too high. At Google Cloud you don't pay a fixed monthly price. You pay based on load and usage.

Another option could be a discount provider like OVH. OVH have some pretty cheap VPS, and the performance is okay. The cheapest is only 2.99€/month + tax and includes "unlimited" bandwidth.

# Answer
> 0 votes
I would look into Amazon web services. They offer "free" services until you reach a certain tier. Many companies do this. Another good one for games would be Unity as well. They are free until you start making a decent amount of money or have a certain number of users.

# Answer
> -2 votes
No, Apple and google do not have free server solutions for apps. That would cost the money, something they want to keep.

---
Tags: android, networking, ios, server, mobile
---


# Question
Title: Rotation + Translate causes camera shakes
**UPDATE:** I have found that the delays happen when i press a key in the keyboard and move the mouse at the same time, how can i solve it?

I checked it setting a constant speed to the camera(going forward) and disabled the interactions with the keyboard. The lag didnt appear when i was moving forward while rotating the camera, but happened when i pressed keys(with no functions because i disabled them) while i was moving the mouse

I will let here my initial question, but the problem is not because of the code, it is about the keyboard + mouse use. **IGNORE WHAT FOLLOWS**

**=======================================================================**

I am running out of ideas of what could be the reason for this, but when i move and rotate the camera an insane lag appers(but it doesnt show of in the FPS, they are always around 120). It doesnt happen when i just rotate the camera or translate it.

Video to show the problem:

https://www.youtube.com/watch?v=3UuXZLzU-As&feature=youtu.be

What could be the reason for this? I tried:

* To use raw input, but because it didnt solve it i rolled back.
* Rewrite the camera view calculations.

I am using Vulkan, at the moment on Windows.

Ill include some code:

View update:

```
void Camera::UpdateView()
{
    glm::mat4 rotate = glm::mat4_cast(GetRotation());
    glm::mat4 translate = glm::mat4(1.0f);
    translate = glm::translate(translate, -GetPosition());

    Matrices.view = rotate*translate;

    glm::mat4 matInverseView = glm::inverse(Matrices.view);
    forward = glm::normalize(glm::vec3(matInverseView[2]));
    right = glm::normalize(glm::vec3(matInverseView[0]));
}

```

Pitch and yaw update:

```
void Camera::ActiveMouseUpdate(Input * input, double deltaTime)
{
    if (input->MouseMoved())
    {
        yaw -= MOUSE_SENSIBILITY * input->GetMouseSpeed().x*deltaTime;
        pitch += MOUSE_SENSIBILITY * input->GetMouseSpeed().y*deltaTime;
        pitch = glm::clamp(pitch, glm::radians(-85.0f), glm::radians(85.0f));
        CalculateComponents();
        cameraChanged = true;
    }

}

```

Rotation update:

```
void Camera::CalculateComponents()
{
    glm::quat qPitch = glm::angleAxis(pitch, glm::vec3(1, 0, 0));
    glm::quat qYaw = glm::angleAxis(yaw, glm::vec3(0, 1, 0));
    glm::quat qRoll = glm::angleAxis(roll, glm::vec3(0, 0, 1));
    glm::quat orientation = glm::normalize(qPitch * qYaw*qRoll);

    SetRotation(orientation);
}

```

Movement:

```
void Camera::PassiveKeyboardUpdate(Input * input, double deltaTime)
{
    cameraChanged = false;

    glm::vec3 pos = GetPosition();

    if (input->isKeyDown(KEY_W))
    {
        pos -= (float)deltaTime*forward*speed;
        cameraChanged = true;
    }
    if (input->isKeyDown(KEY_S))
    {
        pos += (float)deltaTime*forward*speed;
        cameraChanged = true;
    }
    if (input->isKeyDown(KEY_D))
    {
        pos += (float)deltaTime*right*speed;
        cameraChanged = true;
    }
    if (input->isKeyDown(KEY_A))
    {
        pos -= (float)deltaTime*right*speed;
        cameraChanged = true;
    }
}

```

How my loop works:

```
void CoreEngine::Loop()
{
    while (renderer->Run())
    {
        UpdateFPS();
        UpdateInput();
        Update();
        Draw();
    }
}

```

Update input:

```
void CoreEngine::UpdateInput()
{
    input->Update();
    if(input->KeyboardChanged())
        root->ActiveKeyboardUpdate(input, deltaTime);
    root->PassiveKeyboardUpdate(input, deltaTime);
    if (input->MouseChanged())
        root->ActiveMouseUpdate(input, deltaTime);
}

```

Update:

```
void CoreEngine::Update()
{
    root->Update(deltaTime,enlapse);
}

```

Draw:

```
void CoreEngine::Draw()
{
    renderer->PrepareFrame();
    renderer->Draw();
    renderer->DrawTextOverlay();
    renderer->PresentDraw();
    renderer->UpdateUniformBuffers(false);
}

```

Root is the root node of my object tree which call all objects(nodes) attached updates, which nodes also call their own nodes updates.

**UPDATE**: I found that if i change this:

```
case WM_MOUSEMOVE:
    if (captureWindow)
    {
        mousePosition.x = LOWORD(lParam);
        mousePosition.y = HIWORD(lParam);
        mouseChangeState = true;
        if (forcedMouseMove)
        {
            lastUpdatePosition = mousePosition;
            forcedMouseMove = false;
        }
        else
            SetCursorCenter();
    }
    break;

```

For this:

```
case WM_MOUSEMOVE:
    if (captureWindow)
    {
        mousePosition.x = LOWORD(lParam);
        mousePosition.y = HIWORD(lParam);
        mouseChangeState = true;
        if (forcedMouseMove)
        {
            lastUpdatePosition = mousePosition;
            forcedMouseMove = false;
        }
        else if(glm::abs(mousePosition.x + screen.left - Middle.x ) > 400 || glm::abs(mousePosition.y + screen.top - Middle.y) > 300)
            SetCursorCenter();
    }
    break;

```

Where:

```
void Input::SetCursorCenter()
{
    SetCursorPos(Middle.x, Middle.y);
    ForceMove(true);
}

```
* Middle: Is the center of the window
* screen: Is the rectangle that contains the window.

The effect is less appreciable, but still there(i still want to solve this less appreciation). I also interpolated the movement, rotation and forward and right vectors.

# Answer
After tons of checks and time, i solved the problem.

Just add

```
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

```

At the beginning of your loop if you have this problem. It will take care of all messages from your inputs before the loop begins solving the problem.
> 1 votes

---
Tags: camera
---


# Question
Title: Dual Contouring - Finding the feature point, normals off
I am following this tutorial to implement Dual Contouring http://www.sandboxie.com/misc/isosurf/isosurfaces.html

My data source is a grid 16x16x16; I traverse this grid bottom to top, left to right, near to far.

For each index of my grid, I create a cube structure :

```
public Cube(int x, int y, int z, Func<int, int, int, IsoData> d, float isoLevel) {
            this.pos = new Vector3(x,y,z);
            //only create vertices need for edges
            Vector3[] v = new Vector3[4];
            v[0] = new Vector3 (x + 1, y + 1, z);
            v[1] = new Vector3 (x + 1, y, z + 1);
            v[2] = new Vector3 (x + 1, y + 1, z + 1);
            v[3] = new Vector3 (x, y + 1, z + 1);
            //create edges from vertices
            this.edges = new Edge[3];
            edges[0] = new Edge (v[1], v[2], d, isoLevel);
            edges[1] = new Edge (v[2], v[3], d, isoLevel);
            edges[2] = new Edge (v[0], v[2], d, isoLevel);
        }

```

Due to how I traverse the grid, I only need to look at 4 vertice and 3 edges. In this picure, the vertices 2, 5, 6, 7 correspond to my vertices 0, 1, 2, 3, and the edges 5, 6, 10 correspond to my edges 0, 1, 2.

An edge looks like this :

```
    public Edge(Vector3 p0, Vector3 p1, Func<int, int, int, IsoData> d, float isoLevel) {
        //get density values for edge vertices, save in vector , d = density function, data.z = isolevel
        this.data = new Vector3(d ((int)p0.x, (int)p0.y, (int)p0.z).Value, d ((int)p1.x, (int)p1.y, (int)p1.z).Value, isoLevel);
        //get intersection point
        this.mid = LerpByDensity(p0,p1,data);
        //calculate normals by gradient of surface
        Vector3 n0 = new Vector3(d((int)(p0.x+1),   (int)p0.y,      (int)p0.z       ).Value - data.x,
                                 d((int)p0.x,       (int)(p0.y+1),  (int)p0.z       ).Value - data.x,
                                 d((int)p0.x,       (int)p0.y,      (int)(p0.z+1)   ).Value - data.x);

        Vector3 n1 = new Vector3(d((int)(p1.x+1),   (int)p1.y,      (int)p1.z       ).Value - data.y,
                                 d((int)p1.x,       (int)(p1.y+1),  (int)p1.z       ).Value - data.y,
                                 d((int)p1.x,       (int)p1.y,      (int)(p1.z+1)   ).Value - data.y);
        //calculate normal by averaging normal of edge vertices
        this.normal = LerpByDensity(n0,n1,data);
    }

```

I then check all the edges for a sign change, if there is one I find the surrounding cubes and get the feature point of those cubes.

Now that works if I set the feature point to the cube center, I then get the blocky minecraft look. But that's not what I want.

To find the feature point, I wanted to do it as in this post : https://gamedev.stackexchange.com/a/83757/49583

> Basically, you start the vertex in the centre of the cell. Then you average all the vectors taken from the vertex to each plane and move the vertex along that resultant, and repeat this step a fixed number of times. I found moving it ~70% along the resultant would stabilize in the least amount of iterations.

So I got a Plane class :

```
private class Plane {

        public Vector3 normal;
        public float distance;

        public Plane(Vector3 point, Vector3 normal) {
            this.normal = Vector3.Normalize(normal);
            this.distance = -Vector3.Dot(normal,point);
        }

        public float Distance(Vector3 point) {
            return Vector3.Dot(this.normal, point) + this.distance;
        }

        public Vector3 ShortestDistanceVector(Vector3 point) {
            return this.normal * Distance(point);
        }
 }

```

and a function to get the feature point, where I create 3 planes, one for each edge and average the distance to the center :

```
 public Vector3 FeaturePoint {
            get {
                Vector3 c = Center;
 //                 return c; //minecraft style

                Plane p0 = new Plane(edges[0].mid,edges[0].normal);
                Plane p1 = new Plane(edges[1].mid,edges[1].normal);
                Plane p2 = new Plane(edges[2].mid,edges[2].normal);

                int iterations = 5;
                for(int i = 0; i < iterations; i++) {
                    Vector3 v0 = p0.ShortestDistanceVector(c);
                    Vector3 v1 = p1.ShortestDistanceVector(c);
                    Vector3 v2 = p2.ShortestDistanceVector(c);
                    Vector3 avg = (v0+v1+v2)/3;
                    c += avg * 0.7f;
                }

                return c;
            }
        }

```

But it's not working, the vertices are all over the place. Where is the error? Can I actually calculate the edge normal by averaging the normal of the edge vertices? I cannot get the density at the edge midpoint, as I only have an integer grid as datasource ...

Edit : I also found here http://www.mathsisfun.com/algebra/systems-linear-equations-matrices.html that I can use matrices to compute the intersection of the 3 planes, at least that's how I understood it, so I created this method

```
 public static Vector3 GetIntersection(Plane p0, Plane p1, Plane p2) {
            Vector3 b = new Vector3(-p0.distance, -p1.distance, -p2.distance);

            Matrix4x4 A = new Matrix4x4 ();
            A.SetRow (0, new Vector4 (p0.normal.x, p0.normal.y, p0.normal.z, 0));
            A.SetRow (1, new Vector4 (p1.normal.x, p1.normal.y, p1.normal.z, 0));
            A.SetRow (2, new Vector4 (p2.normal.x, p2.normal.y, p2.normal.z, 0));
            A.SetRow (3, new Vector4 (0, 0, 0, 1));

            Matrix4x4 Ainv = Matrix4x4.Inverse(A);

            Vector3 result = Ainv * b;
            return result;
        }

```

which with this data

```
        Plane p0 = new Plane (new Vector3 (2, 0, 0), new Vector3 (1, 0, 0));
        Plane p1 = new Plane (new Vector3 (0, 2, 0), new Vector3 (0, 1, 0));
        Plane p2 = new Plane (new Vector3 (0, 0, 2), new Vector3 (0, 0, 1));

        Vector3 cq = Plane.GetIntersection (p0, p1, p2);

```

calculates an intersection at (2.0, 2.0, 2.0), so I assume it works correct. Still, not the correct vertices. I really think it is my normals.

# Answer
> 1 votes
First of all your normals should be totaly fine if they are calculated through forward- / backward- / central- differences. The problem is, that you moved your center point torwards the wrong direction in your FeaturePoint function which results in going further away from the minimum.

```
Vector3 c = Center;
Plane p0 = new Plane(edges[0].mid,edges[0].normal);
Plane p1 = new Plane(edges[1].mid,edges[1].normal);
Plane p2 = new Plane(edges[2].mid,edges[2].normal);

int iterations = 5;
for(int i = 0; i < iterations; i++) {
    Vector3 v0 = p0.GetDistanceToPoint(c) * edges[0].normal;
    Vector3 v1 = p1.GetDistanceToPoint(c) * edges[1].normal;
    Vector3 v2 = p2.GetDistanceToPoint(c) * edges[2].normal;
    Vector3 avg = (v0+v1+v2)/3;
    c -= avg * 0.7f; // Error was here!
}
return c;

```

This happend because your code does not converge against a point and therfore jump out of your voxel box. I don't know if the code from Can someone explain dual contouring? was intended to use a projection approach where the point gets projected onto the plane through:

```
distance = Vector3.Dot(point - origin, normal);
projectedPoint = point - distance * normal;

```

but it's the same method. If you rewrite the projection into your original code this results in:

```
    Vector3 v0 = c - p0.GetDistanceToPoint(c) * edges[0].normal;
    Vector3 v1 = c - p1.GetDistanceToPoint(c) * edges[1].normal;
    Vector3 v2 = c - p2.GetDistanceToPoint(c) * edges[2].normal;
    c = (v0+v1+v2)/3;

```

which can be rewritten to:

```
    Vector3 v0 = p0.GetDistanceToPoint(c) * edges[0].normal;
    Vector3 v1 = p1.GetDistanceToPoint(c) * edges[1].normal;
    Vector3 v2 = p2.GetDistanceToPoint(c) * edges[2].normal;
    c = c - (v0+v1+v2)/3;

```

and therefore result in the first code. By projecting the point on three non planar planes it slowly converges towards a minimum because you minimize the distance from each plane to your point as show in the picture.

The red dots denote the feature point, the blue lines the normals and the purple point the point projected on the plane. You also don't need to use the factor 0.7 because it should converge faster without it. If you using this method beware, that the algorithm may not be working if you have non intersecting planes.

---
Tags: c#, geometry
---


# Question
Title: Is there a term for the sounds that play when text is printed out letter by letter?
Take a game like Undertale: whenever a character "talks", the text is printed out one by one, and a sound is played for each letter, as if the character is actually talking (even if it's just gibberish). These sounds are usually different for each character. What are those types of sounds called? If I wanted to get placeholder sounds for such a dialog system, how do I find them?

# Answer
TV Tropes calls this Voice Grunting:

> Voice acting is ubiquitous in video games today, but in the old days, when budgets were smaller, sound hardware was more basic, and disk/cartridge space was limited, developers had to resort to text. In games where story was emphasized, they figured some of the drama was lost when a potentially emotional scene was pantomimed like a silent movie. So some games incorporated "sort of" voice acting, in two forms.
>
> One form is a sort of beeps at various pitches, generally speeding up or slowing down depending on how quickly the speaker is talking. ...

Or, when the sounds are nonsense syllables rather than beeps & typing, Speaking Simlish:

> The language of NPCs and other AI constructs in simulation games and some RPGs, made up of nonsense sounds strung together like actual words. It's not a cypher, normal speech spoken backwards or anything like that, it is quite simply gibberish or "Simlish" as the Sims Manual says
>
> This became especially popular in cartridge and floppy-based releases once fully voiced CD-ROM releases began showing up, as something of a compromise between the expression provided by voice acting and the enormous amount of storage required for it

Something like the voices in Banjo Kazooie could be considered either of the above, I'd say.
> 16 votes

# Answer
There's no specific word to describe this particular effect. On the other hand, we can think of printing words letter by letter and playing a sound for each letter written as a typewriter-like animation. This said, you may call those sounds just 'typewriter typing' or similar.

If you had some sound resources in a project, you could name them '*sndTextTyping1*', '*sndTextTyping2*'...

If you don't want to rely on those terms and want to know the exact word (in case it actually exists), you may want to ask this question on the English Language & Usage Stack Exchange site.
> 2 votes

# Answer
In addition to the other answers, this 'grunting' is used to simplify game localization. This way the developers don't have to hire voice actors in every supported language, and manage those different recordings per region.

To replicate this effect, you could record various random 'syllables' in each voice (10 samples might do). Manually store the number of syllables for each text word in your dialog. Then play a random 'grunt' sound for each syllable in each dialog word. You could fudge it and just play random grunts regardless of the actual number of syllables.
> 2 votes

---
Tags: sound, terminology, sound-effects
---


# Question
Title: Positioning 2D (non-UI system) game objects
As an old Flash dev I'm slightly confused about how you position game objects on the screen in Unity since game objects have no width or height (only a scale).

Let's say I have a container `gameobject` that has several child game objects with sprite renderers representing tiles on them. If I set the container to x0, y0, the whole tile layout will extend from the screen center upwards and to the right.

What are the commonly used ways to position the game object so that it would be centered on the screen? I could calculate the width/height of my container but that would still not be very useful because the x/y coordinates work in a different scale than pixel (right?). E.g. my test screen is 640x1024 and to center my container (while running in the editor) I'd have to set x/y to -4.5. How does that make any sense?

Of course Unity's UI system would be a solution but I don't want to create the playfield with the UI system.

# Answer
It is not that complex as you think. May be you are confusing because you have a tiled map. So the basic solution is to keep object at center (0,0) and if it has children then keep children's position (local position, position w.r.t its parent) should also be at center (0,0).

Now in case of tiles you have to make sure that the whole tiled map should be centered to its parent. For example if you have tile's dimension **5x5** and in **1x1** tile size then Top-Left tile should be at **-2,2**, Top-Right tile should be at **2,2**, Bottom-Left tile should be at **-2,-2**, Bottom-Right tile should be at **2,-2**

Similarly in case of **2x2** tile size then the Top-Left tile should be at **-4,4** and so on...

So if your tiles positioned like this and your parent object is at center (0,0) then I believe that no power on this earth can stop to be centered on the screen.
> 1 votes

# Answer
I think it's a good enough way to position the items as children of a GameObject that is centered in front of your camera. Since you have an actual camera to mess with you can easily change it to fit your needs. And also test that the different resolutions look good in the game window.

If you are using an orthographic camera you can set the size depending on your screen size and the size of your items.

```
Camera.main.orthograpthicSize = gridWidth * (Screen.height / Screen.width) * 0.5f;

```
> 1 votes

# Answer
Aside from the other answers here, I've got two more:

Option 1:

* Move the camera. After constructing your grid you can relocate the camera so that its position is the same as the position of the center-most tiles. Of course, this might be a problem if a user's screensize is smaller than your board...

Option 2:

* Use the New UI system, all of which operates under a RectTransform hierarchy which *does* have a width and height and is inherently based in Screen Space. The pivot and anchor values allow you to even set things up to be flexible and arrange based on how wide and tall the screen is. Admittedly you asked for Non-UI solutions, but for a 2D game, this might be fine for someone else (I'm doing it!).
> 1 votes

---
Tags: unity, 2d, sprites
---


# Question
Title: Infinite Seamless Background HLSL Shader in Monogame doesn't work with non square textures
I'm trying to write a shader that draws a seamless background infinitely in Monogame.

```
sampler TextureSampler : register(s0);
float2 ViewportSize;
float4x4 ScrollMatrix;
struct VertexToPixel {
    float4 Position : SV_Position0;
    float4 TexCoord : TEXCOORD0;
    float4 Color : COLOR0;
};
VertexToPixel SpriteVertexShader(float4 color : COLOR0, float4 texCoord : TEXCOORD0, float4 position : POSITION0) {
    VertexToPixel Output = (VertexToPixel)0;

    // Half pixel offset for correct texel centering.
    position.xy -= 0.5;

    // Viewport adjustment.
    position.xy = position.xy / ViewportSize;
    position.xy *= float2(2, -2);
    position.xy -= float2(1, -1);

    // Transform our texture coordinates to account for camera
    texCoord = mul(texCoord, ScrollMatrix);

    //pass position and color to PS
    Output.Color = color;
    Output.Position = position;
    Output.TexCoord = texCoord;

    return Output;
}

technique SpriteBatch {
    pass {
        VertexShader = compile vs_2_0 SpriteVertexShader();
    }
}

```

I'm using Monogame.Extended so I can use their Camera2D class. I have this function to draw my texture:

```
public static void drawSeamlessBackground(SpriteBatch s, Texture2D t, GraphicsDevice gd, float parallax, Camera2D cam) {
    //TODO: Make this work with non square textures.
    Vector2 textureSize = new Vector2(t.Width, t.Height);
    Rectangle view = gd.Viewport.Bounds;
    Matrix m = Matrix.CreateTranslation(new Vector3(-cam.Origin / textureSize, 0.0f)) *
                Matrix.CreateScale(1f / cam.Zoom) *
                Matrix.CreateRotationZ(-cam.Rotation) *
                Matrix.CreateTranslation(new Vector3(cam.Origin / textureSize, 0.0f)) *
                Matrix.CreateTranslation(new Vector3((cam.Position * parallax) / textureSize, 0.0f));

    infiniteShader.Parameters["ScrollMatrix"].SetValue(m);
    //Normally this next line would not be here since the viewport doesn't usually change.
    infiniteShader.Parameters["ViewportSize"].SetValue(new Vector2(view.Width, view.Height));

    s.Begin(samplerState: SamplerState.LinearWrap, effect: infiniteShader);
    s.Draw(t, new Vector2(0, 0), view, Color.White);
    s.End();
}

```

This whole thing works fine for square textures, but when the width and the height are different, there's distortion that happens when I rotate my camera.

In the next image, there are two textures, one that is square and one that is a rectangle.

Here is what it looks like with no rotation:

Here is what it looks like with some rotation:

The red texture has square dimensions (500x500). The white texture has rectangular dimensions (1280x720).

I'm sure this is a simple fix, but I can't figure it out.

# Answer
After working on this for a while, I found a solution. Just like someone else said in a comment, a shear happens when scaling is done before a rotation. It turns out my texCoord had the wrong ratio. It needed to use the texture's ratio. The shader is perfectly fine, but I need to apply the texture's ratio to my matrix before the rotation.

```
public static void drawSeamlessBackground(SpriteBatch s, Texture2D t, GraphicsDevice gd, float parallax, Camera2D cam) {
    Vector2 textureSize = new Vector2(t.Width, t.Height);
    Rectangle view = gd.Viewport.Bounds;

    Vector2 textureRatio = new Vector2(t.Width / t.Height, 1);
    if (t.Width < t.Height) {
        textureRatio = new Vector2(1, t.Height / t.Width);
    }

    Matrix m = Matrix.CreateTranslation(new Vector3(-cam.Origin / textureSize, 0.0f)) *
                Matrix.CreateScale(1f / cam.Zoom) *
                Matrix.CreateScale(textureRatio.X, textureRatio.Y, 1) *
                Matrix.CreateRotationZ(-cam.Rotation) *
                Matrix.CreateScale(1f / textureRatio.X, 1f /textureRatio.Y, 1) *
                Matrix.CreateTranslation(new Vector3(cam.Origin / textureSize, 0.0f)) *
                Matrix.CreateTranslation(new Vector3((cam.Position * parallax) / textureSize, 0.0f));

    infiniteShader.Parameters["ScrollMatrix"].SetValue(m);
    infiniteShader.Parameters["ViewportSize"].SetValue(new Vector2(view.Width, view.Height));

    s.Begin(samplerState: SamplerState.LinearWrap, effect: infiniteShader);
    s.Draw(t, new Vector2(0, 0), view, Color.White);
    s.End();
}

```

Because of rounding errors though, it's best to use textures that have nice ratios. For example, if I have a texture that is 1920x1080 in size (ratio of 1,777777777777778), I will still get shearing, but if I make that 2000x1000 (ratio of 2), I don't get any.
> 1 votes

---
Tags: c#, monogame, hlsl, monogame-extended
---


# Question
Title: My game scene is very busy and I am afraid it may hurt the players' eyes, how can I fix this?
I recently added many layers to my 2D game scene (multiple background sprites that scroll at different speeds via a parallaxing script) and it hurts my eyes to look at it. I have multiple layers of trees in different shades of green and as I move along I get a jagged movement as the trees overlap each other.

>

I tried fixing this by removing a layer of the trees, but it did not help. I also tried lowering my movement speed and, while it helped some, I cannot lower it any lower without making the movement painfully slow. I found the antiAliasing script on the unity Scripting API, but I am not sure where to put it, or if that is even what I need. Can anyone help? Have I made my question clear?

# Answer
> 5 votes
The biggest problem is that your background has too much **contrast** and your player character has not enough. This is causing attention to be directed at the busy background and not at the player character.

There's an entire discipline - Visual Design \- that deals with how to direct users' attention and make things look good. The principle of dominance and emphasis in particular gives you a bunch of tricks to focus the player's attention. Here's a few powerful examples:

* **Isolation**: placing the subject among a plain background
* **Contrast**: such as colour, brightness. A colourful and/or bright subject stands out among dull, darker surroundings
* **Placement**: things placed at the centre gets more attention

See how Rembrandt uses these principles to attract the viewer's attention at the painting's subjects:

There's one more principle which is applicable for games: **motion**. Things that are moving (or otherwise changing rapidly, like flashing/pulsing) are more attractive.

So back to your example, here are some practical changes you can make that are based on these principles:

* **Make your character brighter, and the background darker.** The last layer of your background is bright green, which is very distracting. Make it a darker or duller colour. Your character ought to be bright, or at least have bright highlights and a strong silhouette.
* **Make your background scroll slower.** Normally parallax layers are placed quite a bit further behind the main layer, so that they scroll noticeably slower and attract less attention. Non-gameplay layers that scroll as fast or faster than the gameplay layers should be used very judiciously.

Further reading:

# Answer
> 0 votes
The parallax effect looks nice, actually. I think the problem is the frame rate of the animation. The trees seems to "teleport" in a few frames, so animation is not that smooth **(but it is not ugly, keep that in mind)**.

One thing you should try is make the trees contrast with your character, or vice-versa, so the colors of the background doesn't end up mixing with your character. Maybe put some shadows in the trees' sprites so they don't "interfere" with the green of your character.

Or maybe look up some kind of motion blur for the movement of the parallax, or the scene in general, I don't know. Since AA is used to make pixels edges look smoother, I don't think that this is what your design is missing.

Hope I helped in some way. Keep up the good work, you scene looks beautiful.

---
Tags: unity, c#, 2d
---


# Question
Title: LIBGDX - How do I change the loaded file by the TmxMapLoader from class that extends from the playscreen screen?
So I was following this guy's tutorial on how to create the Super Mario Bros game, and I was wondering how it would be possible to change levels (screens), in the tutorial he creates a PlayScreen, I was wondering if when I create a class like "level2" I could make it extend from the playscreen and only change the file that the tmx map loader uses, I thought about doing a whole nem class with all the already created functions and just change the file, but there's other classes that uses the PlayScreen as a reference (B2WorldCreator). I know how I would do to end the level, I would do a object that when in colision would trigger the setScreen method.

(PLAYSCREEN)

```
public class PlayScreen implements Screen {

private MarioBros game;
private TextureAtlas atlas;

private OrthographicCamera gamecam;
private Viewport gamePort;
private Hud hud;

private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;

private World world;
private Box2DDebugRenderer b2dr;
private B2WorldCreator creator;

private Mario player;

private Music music;

private Array<Item> items;
private LinkedBlockingQueue<ItemDef> itemsToSpawn;

Controller controller;

public PlayScreen(MarioBros game){
    atlas = new TextureAtlas("Mario_and_Enemies.pack");
    this.game = game;
    gamecam = new OrthographicCamera();
    gamePort = new FitViewport(MarioBros.V_WIDTH / MarioBros.PPM, MarioBros.V_HEIGHT / MarioBros.PPM, gamecam);
    hud = new Hud(game.batch);

    mapLoader = new TmxMapLoader();
    map = mapLoader.load("level1.tmx");

    renderer = new OrthogonalTiledMapRenderer(map, 1 / MarioBros.PPM);
    gamecam.position.set(gamePort.getWorldWidth()/2, gamePort.getWorldHeight()/2, 0);
    world = new World(new Vector2(0,-10), true);
    b2dr = new Box2DDebugRenderer();
    controller = new Controller();
    creator = new B2WorldCreator(this);
    player = new Mario(this);
    world.setContactListener(new WorldContactListener());
    music = MarioBros.manager.get("audio/music/mario_music.ogg", Music.class);
    music.setLooping(true);
    music.play();
    items = new Array<Item>();
    itemsToSpawn = new LinkedBlockingQueue<ItemDef>();
}

```

/*i tried to create a function to change the file but it didn't worked as planned*/

```
public void mudarMapa(String mapa){
    map = mapLoader.load(mapa);
}

public void spawnItem(ItemDef idef){
    itemsToSpawn.add(idef);
}

public void handleSpawningItems(){
    if (!itemsToSpawn.isEmpty()){
        ItemDef idef = itemsToSpawn.poll();
        if(idef.type == Mushroom.class){
            items.add(new Mushroom(this, idef.position.x, idef.position.y));
        }
    }
}

public TextureAtlas getAtlas(){
    return atlas;
}

@Override
public void show() {

}

public void handleInput(float dt){
if (player.currentState != Mario.State.DEAD){
    if(controller.isRightPressed())
        player.b2body.setLinearVelocity(new Vector2(1,
player.b2body.getLinearVelocity().y));
    else if(controller.isLeftPressed())
        player.b2body.setLinearVelocity(new Vector2(-1,
player.b2body.getLinearVelocity().y));
    else
        player.b2body.setLinearVelocity(new Vector2(0,
player.b2body.getLinearVelocity().y));
    if (controller.isUpPressed() && player.b2body.getLinearVelocity().y==0)
        player.b2body.applyLinearImpulse(new Vector2(0, 5f),
player.b2body.getWorldCenter(), true);

    }
}

public  void  update(float dt){
    handleInput(dt);
    handleSpawningItems();

    world.step(1/60f, 6, 2);

    player.update(dt);
    for (Enemy enemy : creator.getEnemies()){
        enemy.update(dt);
        if (enemy.getX() < player.getX() + 224/ MarioBros.PPM)
            enemy.b2body.setActive(true);
    }

    for (Item item: items)
        item.update(dt);

    hud.update(dt);

    if (player.currentState != Mario.State.DEAD){
    gamecam.position.x = player.b2body.getPosition().x;
    }

    gamecam.update();
    renderer.setView(gamecam);
}

@Override
public void render(float delta) {
    update(delta);

    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    renderer.render();

    b2dr.render(world, gamecam.combined);

    game.batch.setProjectionMatrix(gamecam.combined);
    game.batch.begin();
    player.draw(game.batch);
    for (Enemy enemy : creator.getEnemies())
        enemy.draw(game.batch);
    for (Item item: items)
        item.draw(game.batch);

    game.batch.end();

    //hud
    game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
    hud.stage.draw();
    //controller
    if (Gdx.app.getType() == Application.ApplicationType.Android)
    controller.draw();

    if (gameOver()){
        game.setScreen(new GameOverScreen(game));
        dispose();
    }
}

public boolean gameOver(){
    if (player.currentState == Mario.State.DEAD && player.getStateTimer() > 3){
        return true;
    }
    return false;
}

@Override
public void resize(int width, int height) {
    gamePort.update(width, height);
    controller.resize(width, height);
}

public TiledMap getMap(){
    return map;
}

public World getWorld(){
    return world;
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {
    map.dispose();
    renderer.dispose();
    world.dispose();
    b2dr.dispose();
    hud.dispose();
    controller.dispose();
}

```

}

//level 2 screen

```
public class TESTE_TROCA_FASES extends PlayScreen{

public TESTE_TROCA_FASES(MarioBros game) {
    super(game);
}

@Override
public void mudarMapa(String mapa) {
    mudarMapa("level2.tmx");
}

@Override
public void spawnItem(ItemDef idef) {
    super.spawnItem(idef);
}

@Override
public void handleSpawningItems() {
    super.handleSpawningItems();
}

@Override
public TextureAtlas getAtlas() {
    return super.getAtlas();
}

@Override
public void show() {
    super.show();
}

@Override
public void handleInput(float dt) {
    super.handleInput(dt);
}

@Override
public void update(float dt) {
    super.update(dt);
}

@Override
public void render(float delta) {
    super.render(delta);
}

@Override
public boolean gameOver() {
    return super.gameOver();
}

@Override
public void resize(int width, int height) {
    super.resize(width, height);
}

@Override
public TiledMap getMap() {
    return super.getMap();
}

@Override
public World getWorld() {
    return super.getWorld();
}

@Override
public void pause() {
    super.pause();
}

@Override
public void resume() {
    super.resume();
}

@Override
public void hide() {
    super.hide();
}

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

```

}

# Answer
> 0 votes
What you're doing here has no sense:

```
@Override
public void mudarMapa(String mapa) {
    mudarMapa("level2.tmx");
}

```

Firstly, you're calling the same method from the `TESTE_TROCA_FASES` class over and over again instead of calling the `PlayScreen` method, so you must add `super` in order to call the super method.

Anyway, if you want to load a different map, you need to change the `map` variable before creating `OrthogonalTiledMapRenderer` and everything else (box2d, etc), so what I would do is pass the map name in the class constructor:

```
public PlayScreen(MarioBros game, String mapName){
    atlas = new TextureAtlas("Mario_and_Enemies.pack");
    this.game = game;

    [...]

    mapLoader = new TmxMapLoader();
    map = mapLoader.load(mapName); //<--Here, the map is loaded whith the name

    renderer = new OrthogonalTiledMapRenderer(map, 1 / MarioBros.PPM);

    [...]

```

So anytime you want to load any map you just need to pass it as a parameter:

```
new PlayScreen(game, "level2.tmx");

```

---
Tags: java, android, libgdx
---


# Question
Title: In Unity, how do I set up a delay before an action?
I want an object to rotate after a delay. I tried using `StartCoroutine`, `yield` and `WaitForSeconds`, but failed. How can I do it?

# Answer
You could create a variable for example called `timer` of type float and make it equal to the amount of seconds you would like to wait, then in the `Update()` function subtract `Time.deltaTime` from your `timer` variable. Afterwards use if statement to check if the `timer` variable is equal to zero, if so rotate the object.
> 3 votes

# Answer
Multiple choices, but you will have to use Coroutine sometimes, so try to figure out why its not working here.

My tips : careful to not call StartCoroutine in Update() without protection.

Exemple:

```
private bool enter = false;

Update() {
    if (enter == false)
        StartCoroutine(your_timer());
}

IEnumerator your_timer() {
    enter = true;
    Debug.Log("Your enter Coroutine at" + Time.time);
    yield return new WaitForSeconds(2.0f);
    enter = false;
}

```
> 2 votes

# Answer
From here

```
public void Invoke(string methodName, float time);

```

> Invokes the method *methodName* in *time* seconds.

There is a restriction that the method needs to take no parameters and return `void`, so you should wrap your rotation in another function, like so:

```
void delayedRotation() {
    transform.Rotate (new Vector3 (0, 0, 1) * Time.deltaTime);
}

```

and then adjust your code:

```
if (isRolling)
{
    transform.position += new Vector3 (0,1,2)
    Invoke("delayedRotation", 0.5f);
}

```
> 1 votes

# Answer
```
void Update(){
    if(INSERT_CONDITION_HERE){

        StartCoroutine(Timer);
     }
}

```

Then

```
IEnumerator Timer(){
    yield return new WaitForSeconds(Time);
    CODEGOESHERE
}

```
> 0 votes

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


# Question
Title: GUI Layering (Enemy health bars appear above Inventory)
I have set up an enemy prefab that gets instantiated during Start. Each enemy object has a health bar GUI object attached to a Canvas which is a child of these spawned enemy objects. So, when I spawn 10 enemies, 10 health bars get spawned as well. I have another GUI object for the inventory which I can open and close at the press of a button. When I open my inventory and there are enemies behind it, their health bars show on top of my inventory. I would like to layer the GUI objects such that these enemy health bars do not appear above my inventory. How do I do this? I have tried ordering them differently in the hierarchy as per someone's suggestion in a forum post, but that didn't seem to work.

Again, every enemy object has its own Canvas of which the health bar is a child. The inventory GUI object is attached to a different Canvas which has no parent.

# Answer
If the health bars are in "World Space" mode, which they should be in, and the inventory canvas is in "Screen Space - Camera" mode then you need to set the distance of the canvas from the camera.

If the inventory canvas is in "Screen Space - Overlay" mode, there really shouldn't be a problem like this, since it will be overlaid on top of everything else.

If the inventory canvas is in "World Space" mode, then you just need to make it closer to the camera than the other World Space canvas elements.

See also: Canvas.renderMode and RenderModes you can set it to.
> 1 votes

# Answer
If you want the canvases of both UI elements to be rendered in Screen Space - Overlay mode, you can use Sort order to layer them in the desired way. The higher the sort order number, the later it gets rendered, and thus, the "closer to the front" it is.
> 0 votes

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


# Question
Title: Convert 2d generated level to graph or analyze
Do you have any idea how to extract graph data from this type of procedurally generated level?

Well, actually we need to analyze only top level (gray). Background (black) does not matter. What I am looking for is a way to statistically analyze such type of generated maps. For example how much isolated areas I have (it's not hard, I know), how much branches in each area I have and which areas has exit.

Do you remember any algorithm or math instrument to do that? Memory does not matter, algorithm complexity does not matter too. It's not runtime task.

P.S. A desired result can look like this:

# Answer
> 5 votes
Here's something you can try. First, take a map like this:

Record the **distance from the edge** of each empty cell. You can do this iteratively using cellular automation. I've used Manhattan distance but you can use others, although I think your choice affects a few of the following steps.

Find the cells that are **more distant than all their neighbours**, a.k.a. local maxima. Mark these as peaks .

Find all the cells that are **at least as distant as all their neighbours**. I guess you can call these ranges ; they form groups that are local maxima for the most part.

From here you can connect most of the ranges to peaks or other ranges by looking at their neighbours and **hill climbing**; these will form ridges .

You might notice that not everything is connected, particularly on the right part at some narrow passageways. You can connect them up by finding such passageways and hill climbing away from them; eventually you'll reach a range or peak. Here's one way to identify these: find cells that are:

* neighbours
* have minimum distance from the edge
* have opposing directions of ascension

For example, given this group of four cells:

The top-left cell can ascend to the left, and the top-right cell can ascend to the right and bottom. Since left and right are opposites, those two cells form what you might call a col . Similarly the top-left and bottom-left cells are also opposites and part of a col. Just like with the ranges, you can hill climb to connect the cols to the rest of the graph (if they weren't already).

That's it; you should have connected graphs for each contiguous area. You can convert the peaks , ranges and cols into nodes, and the connecting ridges into edges, for graph analysis.

You also have some metadata to play around with; the distances of the peaks and ranges represent how wide those areas are, and cols tend to be choke points.

I'm not familiar with the various Computer Vision algorithms for finding topological skeletons (like straight skeleton or medial axis), but the general idea seems to be the same.

---
Tags: 2d, algorithm, procedural-generation, graph
---


# Question
Title: How to draw a circle on the ground like in "Warcraft 3"?
I've been watching *"Warcraft 3*", and suddenly realized that I have no idea how to draw a circle on a surface.

Here is an example:

I guess this is projection? I also have very little idea of how to draw a shadow. I only somewhat know OpenGL.

It is also interesting how this circle seems to not perfectly repeat the shape of that cliff. My guess is that it's drawn using a height map, which is stored somewhere separately, and not as the cliff, itself. It looks like it actually goes underwater, but it may be just a compression artifact.

# Answer
The best way to do this efficiently (without dynamic meshes) would probably be done using the fragment shader.

You pass the circle centers to the terrain's fragment shader, you get the fragment's position from the vertex shader, and using the

```
dist = length(fragment.xz - center.xz)

```

You get the distance from the circle's center. If it equals the radius of the circle, then you make the fragment green for example.
> 4 votes

---
Tags: opengl, graphics
---


# Question
Title: How could I implement art similar to the Gwent cards?
Here is an example of the Gwent artwork when moving the card around: https://i.stack.imgur.com/uSFja.jpg

What is the most likely way this has been implemented? Is it a 3D model or is it just many layers of 2D art? But then, what about the jiggling?

The character seems to look correct from all perspectives, with body parts closer to the camera properly occluding the parts behind them. This makes me think it is simply a 3D model but it looks incredibly 2D as well.

# Answer
> -1 votes
To me it looks like an orthographic projected 3D figure with baked lights on a parallax 2D image.

The deadly man in the front looks like a sprite too, it doesn't have any depth, that's why the girl seems to be comming out the card.

There's also some kind of reflection applied on the main figure, but I would say it's the only "light direction reactive" element in the scene.

So, summarizing:

2D background

3D figure

Baked lights and shadows

little reflaction effects in the figure

2D dead man in the front

EDIT: the dead man has 2 layers, one for the legs and one for the rest of it

---
Tags: graphics
---


# Question
Title: Why does collision only work when keys are being pressed?
My `player` object containing a `rigidbody` that is controlled using `Input`, is not colliding with an `enemy` unless keys are pressed. When no `keys` are pressed, the `enemy` simply goes through the `player` without `collision`. I'm using Unity 5.6.1f1.

I figured the problem is in the `Patrol` class because when I don't attach the script to the `enemy` object the `collision` appears to take place fine. But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the `enemy` object move between points in `patrolPoints` which are just some `empty`'s in the game world.

So, I would like to know if I'm doing it right or is there another way to do it.

**Patrol.cs**

```
public class Patrol : MonoBehaviour {
    public Transform[] patrolPoints;
    public float speed;
    private int currentPoint;
    private bool forward;

    // Use this for initialization
    void Start () {
        transform.position = patrolPoints [0].position;
        currentPoint = 0;
        forward = true;
    }

    // Update is called once per frame
    void Update () {
        if (transform.position == patrolPoints [currentPoint].position) {
            if (currentPoint < patrolPoints.Length - 1 && forward) {
                currentPoint++;
            } else {
                currentPoint--;
                forward = false;
            }

            if (currentPoint == 0)
                forward = true;
        }

        transform.position = Vector3.MoveTowards (transform.position,
            patrolPoints [currentPoint].position, speed * Time.deltaTime);
    }
}

```

# Answer
Move your bodies around using Rigidbody.AddForce, by modifying Rigidbody.velocity vector, or using Rigidbody.MovePosition. These should ensure that collisions continue to work, whereas your line

`transform.position = Vector3.MoveTowards (transform.position, patrolPoints [currentPoint].position, speed * Time.deltaTime);`

will break collision functionality.
> 2 votes

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


# Question
Title: How do I avoid my objects jumping to the other side, when I change rotation direction?
I implemented an algorithm for circular movement:

```
angle += Time.deltaTime * speed;

float x = (float)( Mathf.Cos(angle) * radius);
float y = (float)( Mathf.Sin(angle) * radius);

```

I want the player to be able to change the direction of the movement between clockwise and counter-clockwise.

If I do it like this:

```
if(clockwise)
        transform.position = new Vector3(-x, y);
    else
        transform.position = new Vector3(x, y);

```

it generally works, but my object jumps to the other side of the object it's rotating around. This makes sense, to me, because the x-coordinate changes. How do I avoid this?

# Answer
In the provided example, your increasing `angle` over time, based off `speed` and `Time.deltaTime`. However, when you mean to change direction by providing a positive or negative value, your actually *inverting* the angle.

---

Instead, you should be changing your `angle` value *over time*, based on the direction.

```
if(clockwise)
{
    angle -= Time.deltaTime * speed;
}
else
{
    angle += Time.deltaTime * speed;
}

```

---

An alternate solution, if you do not have any other use for the `clockwise` boolean, would be to turn it into an integer that should always be `1` for counter-clockwise, or `-1` for clockwise. This only simplifies your code to a minor degree.

```
int clockwise;

// ...

angle -= Time.deltaTime * speed * clockwise;

// .. and depending on how you intend to set direction..

void SetClockwise()
{
    clockwise = -1;
}

void SetCounterClockwise()
{
    clockwise = 1;
}

void ChangeRotationDirection
{
    clockwise *= -1;
}

```
> 1 votes

# Answer
You'll have to decrease angle if you want to make the object go in the other direction.
> 1 votes

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


# Question
Title: How should I design an easing class in C++?
I'm currently struggling to find a good approach for an easing class for my game.

The class holds some easing effects, like elastic-in-out, and should be called by menu buttons, players and enemies to polish my animations a bit. (think about a cool bouncing button that fades in)..

This is my very basic easing class so far:

```
class Easing {

protected:
    double currentTime;
    double startTime;
    double endTime;

public:
    virtual double ease(double t) { return 0.0f; }

};

class Easing_ElasticInOut : Easing {

public:
    virtual double ease(double t) override {
        t--;
        return sqrt(1 - t*t);
    };

};

```

In my menu I've got a bunch of buttons and I'd like to animate them to ease in when they appear.

```
void EditorMenu::render() {

    if (is_open()) {
         // Easing_ElasticInOut ???
         // Draw a button with circle_radius depending on the easing
    }
}

```

This `render()` method gets called all the time.

How would you design these effects? I'm not sure about how to only call them once and let them finish, especially when there are more buttons or things at once, that need to be animated...

# Answer
> 2 votes
I've myself implemented this using a helper class called `InterpolationHelper` and a class that handles the actual easing, called `InterpolationCurve`. In addition, there's an enum `InterpolationCurveType`, which decides which type of easing is used. You could replace the enum with overloads of the `InterpolationCurve`, but I felt that going with an enum was the easiest way to implement this, while still supporting inheritance if needed.

```
class InterpolationHelper
{
public:
    InterpolationHelper() {}
    InterpolationHelper(float duration, const InterpolationCurve& curve) : m_Duration(duration), m_Curve(curve)
    {
        m_StartTime = GetCurrentGlobalTime();
        m_FinishTime = m_StartTime + duration;  // Make sure that the units match up here.
    }

    bool IsFinished() const { return GetCurrentGlobalTime() >= m_FinishTime; }
    bool IsEmpty() const { return m_Duration == 0.0f && m_StartTime == 0.0f && m_FinishTime == 0.0f; }

    float GetPercentage() const
    {
        const float progress = (GetCurrentGlobalTime() - m_StartTime) / (m_Duration);
        return m_Curve.GetCurveValue(std::clamp(progress, 0.0f, 1.0f));
    }
protected:
private:
    float m_Duration = 0.0f;
    float m_StartTime = 0.0f;
    float m_FinishTime = 0.0f;
    InterpolationCurve m_Curve;
}

```

So first we declare the class that helps you with the actual interpolation helper. You would instantiate an `InterpolationHelper` in your class, and pair it up with some start/begin values, and use the value returned by `GetPercentage()` as your `Lerp` progress value. The pattern which I use in my code very often looks something like this:

```
if (!m_CircleInterpolationHelper.IsEmpty())
{
    myCircleRadius = Lerp(0.0f, 25.0f, m_CircleInterpolationHelper.GetPercentage());
    // Clears the interpolation once done.
    if (m_CircleInterpolationHelper.IsFinished())
    {
        m_CircleInterpolationHelper = InterpolationHelper()
    }
}

```

One thing you really want to watch out for is only instantiating the interpolation once you want your animation to start, so for an example you would create your interpolation helper when the menu is opened.

```
void Editor::OnMenuOpen()
{
    m_CircleInterpolationHelper = InterpolationHelper(1.0f, InterpolationCurve(EInterpolationCurveType::LINEAR));
}

```

So, now we just need to take care of the actual easing implementation. This is just a wrapper class for your easings. For the linear type, we can just fall through with the progress value fed to the function. You can add whatever math-curves you'd like to use for your interpolations to the case-statement.

```
enum class InterpolationCurveType
{
    LINEAR,
    SMOOTHSTEP
}

class InterpolationCurve
{
public:
    InterpolationCurve(InterpolationCurveType type) : m_Type(type) {}

    float GetCurveValue(float progress) const
    {
        switch(m_Type)
        {
            case InterpolationCurveType::LINEAR: return progress;
            case InterpolationCurveType::SMOOTHSTEP: return progress * progress * (3 - 2 * progress);
            // More cases here, maybe allow sampling a bezier curve or something other cool.
        }

        return 0.0f;
    }
protected:
private:
    InterpolationCurveType m_Type;
}

```

As a final disclaimer, the code above is untested and might not work right out of the box, but I'm sure the idea behind the code gets through.

---
Tags: c++, software-engineering, easing
---


# Question
Title: How do I call a method from a subclass in Unity?
So here is my base class:

```
using System;
using UnityEngine;

public class Enemy : MonoBehaviour
{

    public Vector3 MoveBy;
    public float movingSpeed = 0.2f;
    public float waitTime = 4f;

    private float _waitTime;
    private SpriteRenderer spriteRenderer;
    private Animator animator;
    private Transform rabbitTransform;

    Vector3 pointA;
    Vector3 pointB;
    Vector3 target;
    Vector3 destinationVector;

    protected virtual void Start()
    {
        initializeNeededComponents();
        initializePointsToMoveToAndFrom();
        setFirstTargetToInitializedPointB();
        setFirstDestinationVector();
        setFirstWaitTime();
    }

    private void initializeNeededComponents()
    {
        spriteRenderer = this.gameObject.GetComponent<SpriteRenderer>();
        animator = this.gameObject.GetComponent<Animator>();
        rabbitTransform = LevelController.getRabbit().GetComponent<Transform>();
    }

    private void initializePointsToMoveToAndFrom()
    {
        this.pointA = this.transform.position;
        this.pointB = this.pointA + MoveBy;
    }

    private void setFirstTargetToInitializedPointB()
    {
        this.target = this.pointB;
    }

    private void setFirstDestinationVector()
    {
        Vector3 _destinationVector = this.target - this.transform.position;
        _destinationVector.z = 0;
        this.destinationVector = Vector3.Normalize(_destinationVector);
    }

    private void setFirstWaitTime()
    {
        _waitTime = waitTime;
    }

    protected virtual void Update()
    {
        moveAndIfArrivedWait();
        ifRabbitNearAttack();
    }

    private void ifRabbitNearAttack()
    {
        if (ifRabbitNear()) ;
        { AttackTheRabbit(LevelController.getRabbit()); }
    }

    private bool ifRabbitNear()
    {
        if(itIsBetween(rabbitTransform.position.x, pointB.x, pointA.x))
        {return true;}

        return false;

    }

    private bool itIsBetween(float it, float left, float right)
    {
        return (left < it) && (it < right);
    }

    private void moveAndIfArrivedWait()
    {
        if (isArrived(this.transform.position, target))
        {
            if (_waitTime == waitTime)
            { stopWalkigAndStartBeingIdle(); }

            _waitTime -= Time.deltaTime;
            if (_waitTime <= 0)
            {
                turnAround();
                changeTarget();
                resetWaitTimeForFutureWaitOnTheArriving();
                stopBeingIdleAndStartWalkig();
            }
        }
        else
        {
            this.transform.Translate(destinationVector * movingSpeed);
        }
    }

    private void stopBeingIdleAndStartWalkig()
    {
        AnimateContiniously("idle", false);
        AnimateContiniously("walking", true);
    }

    private void stopWalkigAndStartBeingIdle()
    {
        AnimateContiniously("walking", false);
        AnimateContiniously("idle", true);
    }

    private void resetWaitTimeForFutureWaitOnTheArriving()
    {
        _waitTime = waitTime;
    }

    private void changeTarget()
    {
        target = (target == pointA) ? pointB : pointA;
    }

    private void turnAround()
    {
        destinationVector = (-1) * destinationVector;
        spriteRenderer.flipX = !spriteRenderer.flipX;
    }

    bool isArrived(Vector3 pos, Vector3 target)
    {
        pos.z = 0;
        target.z = 0;
        return Vector3.Distance(pos, target) < 0.06f;
    }

    private void AnimateContiniously(string what, bool toAnimate)
    {
        animator.SetBool(what, toAnimate);
    }

    protected virtual void AttackTheRabbit(GameObject rabbit)
    {
        Debug.Log("In a base class");
    }
}

```

Here is my subclass:

```
using UnityEngine;

public class GreenEnemy : Enemy
{
    protected override void Start()
    {
        base.Start();
    }

    // Update is called once per frame
    protected override void Update ()
    {
        base.Update();
    }

    protected virtual void AttackTheRabbit(GameObject rabbit)
    {
        Debug.Log("in subclass!");
    }
}

```

I would like make it in such a way that implementation of AttackTheRabbit will always be called from the subclass. Is it possible at all? If so show me the way, please.

# Answer
> 4 votes
Your subclass just needs

```
protected virtual void AttackTheRabbit()

```

to be

```
protected override void AttackTheRabbit()

```

and it will always be called by the base class when its `ifRabbitNearAttack()` is called.

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