# Question
Title: Tiling of a material, independent of its size
I am using Textures and Materials to tile my sprites, for instance when building a wall in my game.

The problem with this is that everytime I resize the plane or size of my game object, I have to retouch the tiling property of the material.

I have asked around about how to solve this, and they told me to write my own shader, but after reading around a little, that seems quite a deep and long topic, to solve this small issue.

Would anyone know a way to solve this issue, or at least recommend me a shader that already does that (and if possible a small explanation on how to use it)?

# Answer
One simple way to do this without a script modifying the tiling per object is to apply the texture in worldspace. That way you'll always have a consistent repeat rate, no matter where or how stretched your objects are.

They'll also automatically tile seamlessly where two similarly-textured objects meet, even if they're using different scales (provided you've used a seamless tiling texture)

In this example you can see conventional texture mapping on the left, using four standard quads at different scales with one material. On the right are the same four quads textured in worldspace using a single material. (The brick texture is a free asset from Kenney.nl)

To do this, create a new shader something like the following:

```
Shader "Unlit/WorldspaceTiling"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);

                // Gets the xy position of the vertex in worldspace.
                float2 worldXY = mul(_Object2World, v.vertex).xy;
                // Use the worldspace coords instead of the mesh's UVs.
                o.uv = TRANSFORM_TEX(worldXY, _MainTex);

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

```

(Here I've used an unlit opaque shader without fog as a base, but other effects can be incorporated in a straightforward way if you need.) You can use the regular texture tiling & offset fields to fine-tune how many repeats you want per world unit and the alignment of the tiling.

This approach has some limitations:

* If the object moves through worldspace (eg. a moving platform), the texture will appear to crawl along it.
* Rotating the object won't rotate the texture, so it will tile across it diagonally.
* An object that's not aligned to the texture's repetition grid can show the texture cropped incorrectly (eg. if you have a border that should always sit right at the edge of a tile)

These problems can all be worked around, the fixes just require a bit more information about your setup. If you have only a few objects that need special treatment, you can use the script approach described in the other answers for those, while the worldspace tiling handles the bulk of the simpler cases.

There are also some significant advantages:

* No additional material instances created (which can leak if you're not careful - they're not garbage collected as readily as other objects)
* Many differently-scaled objects can be rendered in one draw call since they use the same material (under the hood, Unity will often pre-transform vertices in order to send multiple scaled objects using the same material in one batch)
* It "just works" without needing to add extra script instances
> 16 votes

# Answer
Here is the script which takes care of what you need. Just attach to the game object where the material is assigned. You may remove this script when you are done editing the level, it wont be needed at all.

Added a few more optimization

* Update only on change in transform
* Update only if it is Unity editor and not in play mode
* Scale factor

TextureResize.cs

```
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class TextureResize : MonoBehaviour
{

    public float scaleFactor = 5.0f;
    Material mat;
    // Use this for initialization
    void Start ()
    {
        Debug.Log("Start");
        GetComponent<Renderer>().material.mainTextureScale = new Vector2 (transform.localScale.x / scaleFactor , transform.localScale.z / scaleFactor);
    }

    // Update is called once per frame
    void Update ()
    {

        if (transform.hasChanged && Application.isEditor && !Application.isPlaying)
        {
            Debug.Log("The transform has changed!");
            GetComponent<Renderer>().material.mainTextureScale = new Vector2 (transform.localScale.x / scaleFactor , transform.localScale.z / scaleFactor);
            transform.hasChanged = false;
        }

    }
}

```

Edit:- All these things are going to be pretty straight forward with unity's upcoming updates. Hopefully it will be out soon :)

Link:- https://www.youtube.com/watch?v=muRhea-JaIM
> 1 votes

# Answer
It appears that you have not marked the top answer (DMGregory) as accepted, and that this is because it seems a little confusing to use the shader. I'm new, too. Here's how I made that answer work:

* Right-Click \> Create \> Shader \> Unlit Shader
* Select the shader you just created. In the inspector, up at the top, click "Open". This will open it in MonoDevelop (or whatever program you have set). Copy Gregory's code into the .shader text file. Save it.
* You can now select that shader from the dropdown menu. Wallabing. You're done.

The only problem with this approach is that it doesn't have the texture on all 3 axes. Works for a 2D game, but not for a 3D game. So yes, there is confusion with creating your own shader on that level. But if you're making a 2D game, Gregory's code will work out of the box.
> 0 votes

# Answer
This little snippet did the job for me:

```
    GetComponent<Renderer>().material.mainTextureScale = new Vector2(transform.localScale.x / textureSize.x, transform.localScale.y / textureSize.y);

```

I made it work in the 3D case to using a cube with 3 identical materials. One for the sides facing in the X-direction (+ or -), one for the Y direction, and one for the Z direction (I dont know which are which). Realtime rescaling looks ok.

```
public Vector2 textureSize;
private Material wallMaterial;

// Update is called once per frame
void Update() //or Start, if you don't need realtime rescaling.
{
    GetComponent<Renderer>().materials[0].mainTextureScale = new Vector2(transform.localScale.x / textureSize.x, transform.localScale.y / textureSize.y);
    GetComponent<Renderer>().materials[1].mainTextureScale = new Vector2(transform.localScale.x / textureSize.x, transform.localScale.z / textureSize.y);
    GetComponent<Renderer>().materials[2].mainTextureScale = new Vector2(transform.localScale.z / textureSize.x, transform.localScale.y / textureSize.y);
}

```
> 0 votes

# Answer
Just edit the tiling via a script?

So if the wall when it is 1 units long, and has a tiling of 1, looks correct, when a wall that is 10 units long is made, just adjust the value in a script so the tiling is 10 units long.

Simple.
> -2 votes

---
Tags: unity, 2d, materials
---


# Question
Title: MMORPG - Representing Money in a DB table
Where to begin... I'm currently busy with a few Udemy courses on game development using Unreal Engine 4. My end goal is to develop an MMORPG that I've always wanted to play, but never found online.

Q: How would I represent in-game money in a database table?

I've thought of adding it as a field in the "character" table, but then I struggle to see how I can implement it as a field in the "bank" table... Bank already has a quantity field, so I though about adding the money values as "items", but I just can't get myself to approve that...

Some information on the table fields:

* Each players bank will have a size limit (upgrade-able) on how many items they can place in it. I was thinking of moving it out to the "character" table as it doesn't really have anything to do with the bank table...

As for the rest of the tables, I'm still working on them. For now I just wanted to get the communities opinion on how to represent money in an mmorpg database.

# Answer
> 0 votes
Every player has one "cash money" value and one "bank money" value, so you could add both as integers values to the `character` table. If you really want to separate the banking system from the character system, you could create another table `bank_accounts` with the columns `character_id` and `money`.

---
Tags: mmo, databases
---


# Question
Title: How can I make my camera follow the player movement in a different position
Basically my camera follows the character rotation and position, although the position of it its pretty uncomfortable to use, this is what I needed:

But this is what the I get:

I used a code that someone suggested me yesterday to use, I got a bit creative with it and changed some stuff to get other camera positions, but no matter how much I tweak the values the camera never gets the position that I need:

```
void LateUpdate()
{
    transform.position = player.transform.position - (player.transform.up * -10) + (player.transform.forward * -15);
    transform.LookAt(player.transform);

}

```

I have no idea how I can make it show less of the player back

# Answer
> 1 votes
You need to elevate camera position upwards, add some arbitrary value you like as the `elevation` variable and you're good to go.

```
float elevation = 1.0f;//Value that you'd want to tweak
transform.LookAt(
    player.transform.position + player.transform.up * elevation,
    player.transform.up
);

```

Also you'll probably need to decrease distance between camera and the player.

```
(player.transform.forward * -15)//It's here, tweak it

```

---
Tags: unity, camera
---


# Question
Title: MMORPG - Auction House and Bank Primary Keys
On to the next... So I've been sitting with the idea of how to better future proof my database tables when it comes to things like auction houses, inventories and banks.

Q: Is it really necessary to have a primary key value in an auction-house / bank tables? I've already got a link going to the characters ID as well as the item ID.

The reason I'm asking this is because if I use a primary key value of type int or long, what will happen if there are too many entries for type int or long to handle? I'm planning on removing the DB entry as soon as the item is sold, but wouldn't "auto increment" just carry on from the last ID value used?

In short, what would be the down side to not using primary keys in those tables?

# Answer
The debate about natural keys vs synthetic keys is as old as SQL databases themselves. The opinions about this are all over the place and you can read many different opinions about this all around the Internet (if you want to search for some, note that some people also call synthetic keys "artificial keys", "surrogate keys" or "technical keys") .

If the combination of `character_id` and `item_id` fully describes every entry in your `bank` table, then there is no technical reason why you **must** have an otherwise meaningless `id` field in addition to that. However, having synthetic keys gives more flexibility in the future, because if you decide to refactor your database and suddenly you **do** allow multiple entries with the same `character_id` and `item_id` in that table, the primary key of the table doesn't need to change which reduces the overall impact of that change. But you will only really feel that impact if you actually use that `id` field for anything else besides satisfying the requirement for a primary key on every SQL table.
> 1 votes

# Answer
I would use a separate key for every listing. What if a player lists an item, then somehow that item gets back to the same player and gets listed again? Then you can't properly keep a history of transactions.

Also, I wouldn't worry about overflow so much. A long integer in SQL is 8 bytes, which means it can hold up to 2^64 before overflowing. Which is 18,446,744,073,709,551,616 (20 digits).
> 1 votes

---
Tags: mmo, databases
---


title: frame rate drop in html5 game

text:
# Question
Title: frame rate drop in html5 game
i have Incorporated gravity mechanics and collision mechanics to my game. the game works fine for some period of time after that i am getting significant amount of frame rate drop.i am doing some heavy computation but i don't see any other approach to it.can anyone suggest improvement for frame rate drop. i have added code and output as snippet

```
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
    width: 100%;
}
body
{
    overflow-x: hidden;
    overflow-y: hidden;
    margin:0px 0px 0px 0px;
}
</style>
</head>
<body onload="startGame()">
</body>
<script>
var blackhole;
var planet=[];
var flag=[];
var canvasWidth=window.innerWidth;
var canvasHieght=window.innerHeight;
var mousex=0;
var mousey=0;
var numofplanets=15;
function startGame() {
    myGameArea.start();
    blackhole = new BlackHole(canvasWidth/2,canvasHieght/2, 30,"black",70);
    for(let i=0;i<numofplanets;i++)
    {
      var plnt=new Planet(Math.floor((Math.random() *300) + 1),Math.floor((Math.random() * 300) + 1),10,"blue",20);
      planet.push(plnt);
    }
}
var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = canvasWidth;
        this.canvas.height = canvasHieght;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        this.interval = setInterval(updateCanvas,1);
    },
clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
}
function BlackHole(x,y,radius,color,mass) {
    this.x = x;
    this.y = y;
    this.color=color;
    this.mass=mass;
    this.radius=radius;
    this.outerradius=radius*6;
    ctx = myGameArea.context;

    this.stay=function(){
        ctx = myGameArea.context;
        ctx.save();
        ctx.fillStyle=color;
        ctx.beginPath();
        ctx.arc(this.x, this.y,this.radius, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(this.x,this.y,this.outerradius,0,2*Math.PI);
        ctx.stroke();
    }
    this.attract=function(i){
            if(planet[i].r>this.radius)
            {
             planet[i].acclx=(blackhole.mass*(blackhole.x-planet[i].x))/Math.pow(planet[i].r,3);
             planet[i].accly=(blackhole.mass*(blackhole.y-planet[i].y))/Math.pow(planet[i].r,3);
             planet[i].speedx+=planet[i].acclx;
             planet[i].speedy+=planet[i].accly;
             planet[i].x+=planet[i].speedx;
             planet[i].y+=planet[i].speedy;
             ctx.save();
             ctx.fillStyle = color;
             ctx.beginPath();
             ctx.arc(planet[i].x, planet[i].y, planet[i].radius, 0, 2 * Math.PI);
             //ctx.stroke();
            }
            else
            {
              max=1;
              min=-1;
              planet[i].x=Math.floor((Math.random() *1000) + 1);
              planet[i].y=Math.floor((Math.random() *900) + 1);
              planet[i].acclx=0.001;
              planet[i].accly=0.0001;
              planet[i].dirx=Math.floor(Math.random() * (+max - +min)) + +min;
              planet[i].diry=Math.floor(Math.random() * (+max - +min)) + +min;
              if(planet[i].dirx==0 && planet[i].diry==0)
              {
                  planet[i].dirx=-1;
                  planet[i].diry=1;
              }
              planet[i].speedx=Math.sqrt(Math.sqrt(Math.pow(this.x-planet[i].x,2)+Math.pow(this.y-planet[i].y,2))*planet[i].acclx)*planet[i].dirx;
              planet[i].speedy=Math.sqrt(Math.sqrt(Math.pow(this.x-planet[i].x,2)+Math.pow(this.y-planet[i].y,2))*planet[i].accly)*planet[i].diry;
            }
        }
    }
function Planet(x,y,radius,color,mass){
    this.x = x;
    this.y = y;
    this.acclx=0.001;
    this.accly=0.0001;
    this.mass=mass;
    this.r=0.0;
    max=1;
    min=-1;
    this.radius=radius;
    this.dirx=Math.floor(Math.random() * (+max - +min)) + +min;
    this.diry=Math.floor(Math.random() * (+max - +min)) + +min;

    if(this.dirx==0 && this.diry==0)
    {
        this.dirx=-1;
        this.diry=1
    }
    this.speedx=Math.sqrt(Math.sqrt(Math.pow(blackhole.x-this.x,2)+Math.pow(blackhole.y-this.y,2))*this.acclx)*this.dirx;
    this.speedy=Math.sqrt(Math.sqrt(Math.pow(blackhole.x-this.x,2)+Math.pow(blackhole.y-this.y,2))*this.accly)*this.diry;

    this.move=function(){

            if(this.x>canvasWidth)
               this.x=0;
            else if(this.x<0)
                this.x=canvasWidth;
            else if(this.y<0)
                this.y=canvasHieght;
            else if(this.y>canvasWidth)
                this.y=0;
            this.x+=this.speedx;
            this.y+=this.speedy;
            ctx.save();
            ctx.fillStyle = color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
           // ctx.stroke();
    }
    this.checkcollision=function(i)
    {
      for(let k=0;k<numofplanets;k++)
      {
        if(k==i)
          continue;
        if(this.x+this.radius+planet[k].radius>planet[k].x && this.x<planet[k].x+this.radius+planet[k].radius && this.y+this.radius+planet[k].radius>planet[k].y && this.y<planet[k].y+planet[k].radius+this.radius)
        {
         /* this.speedx=this.speedx-((2*planet[k].mass/this.mass+planet[k].mass)*(Math.sqrt(Math.pow(this.speedx-planet[k].speedx,2)+Math.pow(this.x-planet[k].x,2))))*(this.x-planet[k].x);
          this.speedy=this.speedy-((2*planet[k].mass/this.mass+planet[k].mass)*(Math.sqrt(Math.pow(this.speedy-planet[k].speedy,2)+Math.pow(this.y-planet[k].y,2))))*(this.y-planet[k].y);
          planet[k].speedx=planet[k].speedx-((2*this.mass/this.mass+planet[k].mass)*(Math.sqrt(Math.pow(planet[k].speedx-this.speedx,2)+Math.pow(planet[k].x-this.x,2))))*(planet[k].x-this.x);
          planet[k].speedy=planet[k].speedy-((2*this.mass/this.mass+planet[k].mass)*(Math.sqrt(Math.pow(planet[k].speedy-this.speedy,2)+Math.pow(planet[k].y-this.y,2))))*(planet[k].y-this.y);*/
          var tempx=this.speedx;
          var tempy=this.speedy;
          this.speedx=planet[k].speedx;
          this.speedy=planet[k].speedy;
          planet[k].speedx=tempx;
          planet[k].speedy=tempy;
        }
      }
    }
}
function getcordinates(event)
{
  mousex=event.clientX;
  mousey=event.clientY;
}
function updateCanvas()
{
  myGameArea.clear();
  blackhole.stay();
  for(let i=0;i<numofplanets;i++)
  {
    planet[i].r=Math.sqrt(Math.pow(blackhole.x-planet[i].x,2)+Math.pow(blackhole.y-planet[i].y,2));
    planet[i].move();
    planet[i].checkcollision(i);

    if(planet[i].r<blackhole.outerradius)
        blackhole.attract(i);
    ctx.stroke();

  }
}
</script>
```

# Answer
> 1 votes
*"i am doing some heavy computation"*
from what I've seen from your code, 15 planets is not heavy (even tho there are some nested `for's` to check collisions). The FPS drop must be something related to Javascript memory leak or something.

I'm not quite sure what may be causing it, but, after reading the code and inspecting the behaviour on Dev Tools, it might be **the way you wrote your code.**

You are using a deprecated syntax that, if not wrote properly, might cause Javascript to be very unoptimized.
The way you should do it is using ES6 syntax. I rewrote your code using ES6 syntax and now it runs smoother. I tried not to change it too much from what you did, there are somethings that can still be optimized, but it will help you for now, I guess.

*"Why does it runs smoother just by changing the syntax"* you might ask. The answer is: ES6's Sugar Syntax tells Javascript to work differently with objects, in a more optimized way, implementing prototypes for methods and optimizing memory usage in general.

Pro tip: Do some research on ES6 and also on Chrome Dev Tools.

```
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
width: 100%;
}
body
{
overflow-x: hidden;
overflow-y: hidden;
margin:0px 0px 0px 0px;
}
</style>
</head>
<body onload="startGame()">
</body>
<script>
  class Game {
constructor() {
  // game area
  this.canvas = document.createElement("canvas");
  this.context = this.canvas.getContext("2d");
  this.frameNo = 0;
  this.canvas.width = window.innerWidth;
  this.canvas.height = window.innerHeight;
  document.body.insertBefore(this.canvas, document.body.childNodes[0]);

  // general game props
  this.canvasWidth = window.innerWidth;
  this.canvasHieght = window.innerHeight;
  this.blackhole = new BlackHole(this.canvasWidth / 2, this.canvasHieght / 2, 30, "black", 70, this.context);
  this.planets = [];
  this.mousex = 0;
  this.mousey = 0;
  this.numberOfPlanets = 15;

  this.startGame();

  setInterval(this.update.bind(this), 1);
  // if you plan player interaction on the future, use this
  // window.requestAnimationFrame(this.update.bind(this));
}

startGame() {
  for (let i = 0; i < this.numberOfPlanets; i++) {
    const planet = new Planet(Math.floor((Math.random() * 300) + 1), Math.floor((Math.random() * 300) + 1), 10, "blue", 20, this.context, this.blackhole, this.canvas.width, this.canvas.height);
    this.planets.push(planet);
  }
}

clearCanvas() {
  this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}

update() {
  this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  this.blackhole.stay();
  for (let i = 0; i < this.numberOfPlanets; i++) {
    this.planets[i].r = Math.sqrt(Math.pow(this.blackhole.x - this.planets[i].x, 2) + Math.pow(this.blackhole.y - this.planets[i].y, 2));
    this.planets[i].move();
    this.checkPlanetsCollision(this.planets[i]);

    if (this.planets[i].r < this.blackhole.outerradius)
      this.blackhole.attract(this.planets[i]);
    this.context.stroke();
  }
  // window.requestAnimationFrame(this.update.bind(this));
}

checkPlanetsCollision(planet) {
  for (let k = 0; k < this.numberOfPlanets; k++) {
    if (k == planet.id)
      continue;
    if (planet.x + planet.radius + this.planets[k].radius > this.planets[k].x && planet.x < this.planets[k].x + planet.radius + this.planets[k].radius && planet.y + planet.radius + this.planets[k].radius > this.planets[k].y && planet.y < this.planets[k].y + this.planets[k].radius + planet.radius) {
      var tempx = planet.speedx;
      var tempy = planet.speedy;
      planet.speedx = this.planets[k].speedx;
      planet.speedy = this.planets[k].speedy;
      this.planets[k].speedx = tempx;
      this.planets[k].speedy = tempy;
    }
  }
}
  }

  class BlackHole {
  constructor(x, y, radius, color, mass, context) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.mass = mass;
    this.radius = radius;
    this.outerradius = radius * 6;
    this.ctx = context;
  }

  stay() {
      this.ctx.save();
      this.ctx.fillStyle = this.color;
      this.ctx.beginPath();
      this.ctx.arc(this.x, this.y,this.radius, 0, 2 * Math.PI);
      this.ctx.stroke();
      this.ctx.beginPath();
      this.ctx.arc(this.x,this.y,this.outerradius,0,2*Math.PI);
      this.ctx.stroke();
  }

  attract(planet){
    if(planet.r>this.radius)
    {
      planet.acclx=(this.mass*(this.x-planet.x))/Math.pow(planet.r,3);
      planet.accly=(this.mass*(this.y-planet.y))/Math.pow(planet.r,3);
      planet.speedx+=planet.acclx;
      planet.speedy+=planet.accly;
      planet.x+=planet.speedx;
      planet.y+=planet.speedy;
      this.ctx.save();
      this.ctx.fillStyle = this.color;
      this.ctx.beginPath();
      this.ctx.arc(planet.x, planet.y, planet.radius, 0, 2 * Math.PI);
      //ctx.stroke();
    }
    else
    {
      planet.x=Math.floor((Math.random() *1000) + 1);
      planet.y=Math.floor((Math.random() *900) + 1);
      planet.acclx=0.001;
      planet.accly=0.0001;
      planet.dirx=Math.floor(Math.random() * (+planet.max - +planet.min)) + +planet.min;
      planet.diry=Math.floor(Math.random() * (+planet.max - +planet.min)) + +planet.min;
      if(planet.dirx==0 && planet.diry==0)
      {
          planet.dirx=-1;
          planet.diry=1;
      }
      planet.speedx=Math.sqrt(Math.sqrt(Math.pow(this.x-planet.x,2)+Math.pow(this.y-planet.y,2))*planet.acclx)*planet.dirx;
      planet.speedy=Math.sqrt(Math.sqrt(Math.pow(this.x-planet.x,2)+Math.pow(this.y-planet.y,2))*planet.accly)*planet.diry;
    }
  }
}

  class Planet{
constructor(x, y, radius, color, mass, context, blackhole, canvasWidth, canvasHieght) {
  this.canvasWidth = canvasWidth;
  this.canvasHieght = canvasHieght;
  this.x = x;
  this.y = y;
  this.acclx = 0.001;
  this.accly = 0.0001;
  this.mass = mass;
  this.r = 0.0;
  this.ctx = context;
  this.max = 1;
  this.min = -1;
  this.radius = radius;
  this.dirx = Math.floor(Math.random() * (+this.max - +this.min)) + +this.min;
  this.diry = Math.floor(Math.random() * (+this.max - +this.min)) + +this.min;
  if (this.dirx == 0 && this.diry == 0) {
    this.dirx = -1;
    this.diry = 1
  }
  this.speedx = Math.sqrt(Math.sqrt(Math.pow(blackhole.x - this.x, 2) + Math.pow(blackhole.y - this.y, 2)) * this.acclx) * this.dirx;
  this.speedy = Math.sqrt(Math.sqrt(Math.pow(blackhole.x - this.x, 2) + Math.pow(blackhole.y - this.y, 2)) * this.accly) * this.diry;
}

move() {
  if(this.x> this.canvasWidth)
    this.x=0;
  else if(this.x<0)
      this.x= this.canvasWidth;
  else if(this.y<0)
      this.y= this.canvasHieght;
  else if(this.y> this.canvasWidth)
      this.y=0;
  this.x+=this.speedx;
  this.y+=this.speedy;
  this.ctx.save();
  this.ctx.fillStyle = this.color;
  this.ctx.beginPath();
  this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
  // ctx.stroke();
}
  }

  function startGame() {
const game = new Game();
  }
</script>
```

---
Tags: javascript, performance, html-canvas, frame-rate, memory-efficiency
---


title: Opengl Airplane Camera

text:
# Question
Title: Opengl Airplane Camera
I am making a game in opengl and am trying to get a camera to follow an airplane. How can I get the camera to match the roll, pitch, and yaw of the plane? I am using glm as my math library. Thanks!

# Answer
> 0 votes
If you really need to **match** the camera with the plane, all you have to do is use same transformation data as you do for your plane, to generate a view matrix for your camera.

But here's a catch, though. Camera positioning works in reverse for rasterization, so you need to invert your plane position to use it as a basis for camera transformation matrix.

```
//I suggest using quaternion for rotations (glm::quat), but for now
//let's consider to use Euler angles, as they are stated in the question
glm::vec3 plane_rotation_euler;
glm::vec3 plane_position;
//Presumingly, this is how you do plane transformation
glm::mat4 plane_world_transform = glm::mat4(1.0f);
plane_world_transform =
    glm::translate(plane_world_transform, plane_position);
plane_world_transform =
    glm::rotate(plane_world_transform, plane_rotation_euler.x, glm::vec3(1, 0, 0));
plane_world_transform =
    glm::rotate(plane_world_transform, plane_rotation_euler.y, glm::vec3(0, 1, 0));
plane_world_transform =
    glm::rotate(plane_world_transform, plane_rotation_euler.z, glm::vec3(0, 0, 1));

//Then this is how you calculate camera view transformation matrix
glm::mat4 view_transform = glm::mat4(1.0f);
view_transform =
    glm::translate(view_transform , -plane_position);//Note the inversion
view_transform =
    glm::rotate(view_transform , plane_rotation_euler.x, glm::vec3(1, 0, 0));
view_transform  =
    glm::rotate(view_transform , plane_rotation_euler.y, glm::vec3(0, 1, 0));
view_transform =
    glm::rotate(view_transform , plane_rotation_euler.z, glm::vec3(0, 0, 1));

```

---
Tags: opengl, c++, glm
---


title: Unity how to set Off mesh link speed

text:
# Question
Title: Unity how to set Off mesh link speed
How can I set agent's speed on off mesh link? I want it to look like a jump, but now it looks like it was in slow motion.

# Answer
You can have an Update or FixedUpdate function check when the agent is on an off-mesh link, and modify its speed in response, as shown here:

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

public class LinkSpeedScript : MonoBehaviour
{

    public NavMeshAgent agent;
    public bool linking;
    public float origSpeed;

    // just change linkspeed to alter off mesh link traverse speed;
    public float linkSpeed;

    void Start()
    {
        origSpeed = agent.speed;
        linking = false;
    }

    void FixedUpdate()
    {
        if (agent.isOnOffMeshLink && linking == false)
        {
            linking = true;
            agent.speed = agent.speed * linkSpeed;
        }
        else if (agent.isOnNavMesh && linking == true)
        {
            linking = false;
            agent.velocity = Vector3.zero;
            agent.speed = origSpeed;
        }
    }
}

```

This seems to work with my NavMeshAgent settings.
> 1 votes

# Answer
This unity forum post suggests handling the traversing yourself.

> ```
> if(agent.isOnOffMeshLink && !MoveAcrossNavMeshesStarted){
>     StartCoRoutine(MoveAcrossNavMeshLink());
>     MoveAcrossNavMeshesStarted=true;
> }
>
> IEnumerator MoveAcrossNavMeshLink()
> {
>         OffMeshLinkData data = agent.currentOffMeshLinkData;
>         agent.updateRotation = false;
>
>         Vector3 startPos = agent.transform.position;
>         Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
>         float duration = (endPos-startPos).magnitude/agent.Velocity.magnitude;
>         float t = 0.0f;
>         float tStep = 1.0f/duration;
>         while(t<1.0f){
>             transform.position = Vector3.Lerp(startPos,endPos,t);
>             agent.destination = transform.position;
>             t+=tStep*Time.deltaTime;
>             yield return null;
>         }
>         transform.position = endPos;
>         agent.updateRotation = true;
>         agent.CompleteOffMeshLink();
>         MoveAcrossNavMeshesStarted= false;
>
> }
>
> ```

To make it look like a jump, you could

1. lerp between the two positions and play a jump animation on a child node of the hierarchy
2. calculate the y-position yourself, e.g.
`s = 0,5 · a · t2 + vo · t + s0`
with `vo` being the initial velocity and `s0` being the inital position. Use this formula for y.
> 0 votes

---
Tags: unity, ai, navmesh
---


title: Find out reason for automatic break

text:
# Question
Title: Find out reason for automatic break
Soon after I press the Play button, the Unity break button automatically gets activated: Unity gets into Pause mode:

I have attached the Unity debugger to my C# code, but Visual Studio doesn't break.

How could I find out the reason why Unity goes into Break mode?

Thank you!

Edit: Per request, here is the button before pressing Play:

And here is what the console looks like after the error occured:

# Answer
> 1 votes
I had a Debug.Break(); statement in my code. Even though attached, the VS debugger didn't indicate where it stopped.

I'm not sure if that is bug. I was expecting VS to indicate where it stops if the debugger is attached.

I have asked the bug report team this question, and I will update my answer as soon as I hear back from them.

# Answer
> 0 votes
Try opening the console (bottom left). If the "pause on error" option is enabled and you get an error, it will pause the game. Maybe you had it on.

---
Tags: unity, c#, visual-studio
---


# Question
Title: Unity console error with only a timestamp
I am getting console errors that only have a timestamp. I am running Unity 2019.1.9f1 on Ubuntu 19.04. I have installed dotnet core 2.2.5 on my machine.

Here is the full error log: https://pastebin.com/7vfAK9fZ

Here is a particularly suspect part of the log:

```
-----CompilerOutput:-stdout--exitcode: 134--compilationhadfailure: True--outfile: Temp/Unity.TextMeshPro.dll
-----CompilerOutput:-stderr----------
No usable version of the libssl was found
/home/username/Unity/Hub/Editor/2019.1.9f1/Editor/Data/Tools/RoslynScripts/unity_csc.sh: line 64:  3902 Aborted
"/home/username/Unity/Hub/Editor/2019.1.9f1/Editor/Data/Tools/RoslynScripts/../../Tools/Roslyn/csc" /shared /noconfig @Temp/UnityTempFile-2773a2345220fccdfb0171165a73fa25
-----EndCompilerOutput---------------
- Finished compile Library/ScriptAssemblies/Unity.TextMeshPro.dll

```

How do I fix it?

# Answer
Looks like Ubuntu 19.04 is not supported https://forum.unity.com/threads/empty-log-errors-in-2019-1-0f2.669961/
> 1 votes

# Answer
Check the editor log:

* Click the console's window dropdown icon
* Select `Open Editor Log`
> 0 votes

---
Tags: unity, console
---


title: Unity - UI Raycast Hits Problem

text:
# Question
Title: Unity - UI Raycast Hits Problem
I'm having a hard time getting a UI to work and I'd love some advice on what I'm doing wrong.

I have a GameObject (P1 below) which holds a hand of cards (a script containing an array of GameObjects). Everything instantiates correctly from prefabs.

I followed this drag-and-drop example to create a draggable script applied to each prefab. Initially, I had the DropZone script from the tutorial video applied to the PlayMat object and had no problem (in tutorial video #2 it adds a Debug.Log message to the DropZone script to indicate when a successful drop has taken place.

Canvas1 and Canvas2 (same X scale as PlayMat but both are half the Y scale..imagine a card game field like Yu-Gi-Oh so Canvas1 is for Player 1 to place cards and Canvas2 is where Player 2 places cards) have coordinates that place them **ABOVE** the PlayMat but when I attempt a drop, only the PlayMat object registers. How can I make only Canvas1 or Canvas2 register the raycast hits?

Heirarchy as follows:

```
 Main Camera
 Canvas
     Canvas1
     Canvas2
     PlayMat (RectTransform with Canvas Renderer and holds the background image)
 EventSystem
 P1

```

# Answer
If I'm not mistaken, the default Canvas object does not have any colliders, and rays won't hit stuff with no colliders on them. Add a box collider component to the canvas, and if it still doesn't register, check the `isTrigger` bool on the box collider.

Also, rays might or might not hit UI layer, depending on the raycast function's parameters. If you want them to absolutely register the canvases, change their layer from UI to default.

> Physics.Raycast: Casts a ray, from point `origin`, in direction `direction`, of length `maxDistance`, against all colliders in the scene.
> 1 votes

# Answer
You can give them different layers and use a layermask.

Here is one example of letting a raycast only hit specific layers:

```
        //Ray from mouse to the underlying object
        Ray         ray         =   Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.localPosition.y / 2f));
        RaycastHit  raychit;
        //Ray should only collide with layer X (index of the layer)
        LayerMask   lymMask     =   1 << X;

        m_bCanvasHit = Physics.Raycast(ray, out raychit, Mathf.Infinity, lymMask);

```

X is the index of the layer in your Project Settings -\> Tags and Layer. You can more layers which can be hit by the raycast by shifting more 1 into the layer mask, using other indices.
> 1 votes

# Answer
You need to add a GraphicsRaycaster to the canvases that you'd like to raycast onto.

As stated above, the physics raycast only hits colliders, so you need to use EventSystem.current.RaycastAll to hit your canvas.
> 0 votes

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


title: Translate operation is rotating?

text:
# Question
Title: Translate operation is rotating?
```
cube
 [[ 1.  0.  0. 6.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

view
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

final
[[ 1.  0.  0. 6.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

```

Hello! I have a cube and I'm trying to move it around. The above are the calculated matricies for the cube, viewport, and the combined matrix after multiplication. The result is this:

I'm not sure why it's being warped like this instead of scooting over a bit. Any idea?

# Answer
Your matrix is row major, so you should transpose it in order to get behaviour you expect, since OpenGL memory layout is more column-major friendly, because translation is located in the memory at the fourth vector of the 4x4 matrix.
> 2 votes

---
Tags: opengl, matrix
---


# Question
Title: How to improve the look/aspect/resolution of a Text Render in my game?
In my game there are warriors who walk the map following a path. Above their heads is shown their life (text render).

It turns out that unlike when I'm simulating the game (I'm not possessing the character) the visualization of the warriors life is practically impossible.

**Image of when the warrior and my character are walking:**

**Even with my character stopped the visualization of life is horrible:**

**I have not changed much since the creation of the Text Render, but if it helps:**

I want the improvement to be simply in the sense that I can easily identify the value of the warrior's life.

# Answer
> 1 votes
This is likely because of the motion blur effect, you can either try to disable it in the rendering section of the project settings, or you can use 2D UI instead of the current approach involving real 3D geometry in your game world.

# Answer
> 0 votes
Just to supplement the information on my problem and show a possible solution for anyone who has the same problem..

**I discovered today that this blurring is largely due to the fact that I defined the value of the Text Render at all times (Event Tick):**

I discovered that was the main cause of the problem when using this same code in my character.

It was not as bad as the warriors, but it was very out of focus.

I opted for the definition of the Text Render so that the display of the warrior's life (and later the character) is as accurate as possible, however, it gives equal (or near) precision when defining the Text Render only when there is a change in value.

**Examples of when to set the Text Render:**

* character/warrior raise the level (with that his maximum life increased)
* character/warrior received damage

From these events is just call an event that updates the Text Render, or even the very action of losing life. The mode is at the discretion of each one.

---
Tags: unreal-4, text
---


# Question
Title: How to control JavaFX's animations execution order when animations "queue" is being altered in run-time?
**What is the proper way of handling synchronization between GUI animations' execution order and the user's dynamic input?**

More specifically, I would like to know how to enforce some logical conditioning on the execution's order, while remembering, that the user's input cannot be foreseen.

**For instance, a greatly simplified example:**

* 9 rectangles are shown on a screen.
* A click on a rectangle fades it out.
* The user clicks whichever rectangle he wants in whatever order he likes and as fast as he feels is right.
* **The condition** here breaks into two simple ones:
    + The rectangles must not fade out simultaneously.
    + The rectangles' fade out effect occurs in the same order as their clicks.

I would assume a simple FIFO methodology here where threads would register themselves in some ordered queue and be allowed to enter the critical code only on their turn would be sufficient.

**A slightly more complicated scenario:**

* 8 rectangles are shown on a screen - the 9th is an invisible rectangle.
* A click on a rectangle that is a neighbor of the invisible one, activates a translate animation that swipes between the two.
* The user clicks whichever rectangle he wants in whatever order he likes and as fast as he feels is right.
* A "shuffle" button is shown on the screen - shuffles the rectangles in a legal manner, i.e., by randomly moving the rectangles many times.
* **The conditions:**
    + The rectangles **must not** get swiped simultaneously when clicked directly, their animations must be played in the order they were clicked.
    + The rectangles **must** get swiped simultaneously when the "shuffle" button is clicked. Meaning, the user must only see each rectangle move to its final position.
* **Some constraints:**
    + Each rectangle has a `Coordinate` field that itself contains `xCoordinate` & `yCoordinate`.
    + Checking if the clicked rectangle is a neighbor of the invisible one will be done by comparing the rectangles' `Coordinate`s and **not** their positioning on the screen, i.e., `translateX`, `translateY`.
    + **If they are neighbors:** the rectangles swipe places.
    + **Else:** the rectangle shows a nudge animation (as in invalid move).
    + **Only** after the animation is finished, rectangles' `Coordinates` can be swiped.
    + Each process (containing the needed steps after a click) apart from the animation itself, should be handled in a different thread.

**A question**: If the `Coordinates` can be swiped only after the animation is done, meaning each click activates a thread that holds all other threads(clicks that came after) until it is done so it can swipe the coordinates so the next thread's neighbor check is based on correct data, how would it be possible to allow the "shuffle option" without creating an entirely different execution path, i.e., by reusing most of the already written code and leveraging the Java & JavaFX's strengths?

What if we add a constraint that only every second click should be executed?

**My point being, these problems can appear in various ways. There must be someone who thought of providing some kind of framework or an abstract solution to this kind of problems. Or is it each case for itself?**

# Answer
> 1 votes
I have no experience with JavaFX, but for what you described, I guess the most natural solution is to have a command queue which **is completely independent from the specific animation technology**. Let us focus on the a simple case where running animations don't have to be interrupted.

* The command queue gets its input from the UI thread. It maps the UI actions (like "mouse-click at X,Y") to some high-level commands like "fade-out one rectangle", "shuffle all rectangles", or whatever commands your program requires.
* Commands are taken out of the queue whenever the previous animation sequence is completed, and then processed in order.

Now, all of the conditions in your example can be handled by simply managing the insertion into the queue correctly, not necessarily in a FIFO manner. If certain actions require a higher priority than others, just adapt the order of insertion.

* user clicks on a some rectangles in order: new "fade-out rectangle" command is generated and appended to the end of the queue
* user clicks on "shuffle" button: the swipe command is generated and pushed to the beginning of the queue. The unprocessed "fade-out rectangle" commands can be removed, if that should happen, or they can still kept, if that is the idea.

For starting the animations, you then simply need a command processor which takes the next element out of the queue and starts either an animation sequence (containing one or more basic animation), and using as many threads as required. When the sequence ends, the next command is processed.

An additional constrained like "only every second click should be executed" is probably handled best at the UI level by counting clicks (the command queue does not know anything about "mouse clicks", only high-level commands). Other constraints may require to query the current animation status - which is no information the command queue can provide, so it has to be queried from the "animation controlling part".

In short, the key to keep this manageable is simply **separation of concerns**: separate clearly

* the UI event part
* the command processing part
* the animation part

then you can easily add more constraints without making the code messy.

---
Tags: java, design-patterns, multithreading, synchronization, javafx
---


# Question
Title: Check If a 2D Collider Is Completely Inside / Outside of a Polygon Collider
How can I check if one 2d collider (circle, capsule, polygon etc.) is completely inside / outside of a polygon collider?

# Answer
> 1 votes
As noted in the comments, you can check whether two colliders do not intersect at all with:

```
Physics2D.IsTouching(colliderToCheck, polygonRegion) == false;

```

If the two colliders are touching, then you have two possibilities:

1. the `colliderToCheck` is contained entirely inside the `polygonRegion`
2. the `colliderToCheck` crosses the perimeter of the `polygonRegion`

So, if we want to eliminate case 2, then we just need to check each edge along the perimeter of the polygon.

For 3D colliders we could use `Collider.Raycast`to check just the one collider against a sequence of lines, but for some reason `Collider2D.Raycast` does the exact opposite thing, checking *every **other** collider* instead.

But, we can use the same `IsTouching` trick as before, just using a different collider. Add an `EdgeCollider2D` to the mix, setting `edges.points = polygonRegion.points`. Then you can check whether `colliderToCheck` is touching/crossing any edge of the polygon's perimeter, with a tolerance you can control via the `edgeRadius` parameter.

Note that `IsTouching` just queries the contact state as of the last physics step. If you've moved your colliders around, you'll need to `SyncTransforms()` to update the contact information. It also only works if the physics engine is checking for collisions/overlaps between the colliders in the first place, so they can't be both static or both kinematic (cases the physics engine ignores, since by marking them that way you've told it you don't want it to process those collisions).

---
Tags: unity, physics, collider
---


# Question
Title: Why does the code in Unity affect objects differently?
There are 2 objects made in a blender and imported into Unity.

**Eye of the Cyclops.blend**

**Flask.blend**:

The problem is that after using the code, which should create an object in the hand-body area (I'm still working on it), one object is created far from the character.

***Example:***

Everything is OK.

It's not ok.

***Code:***
***PlayerInteraction:***

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

public class PlayerInteraction : MonoBehaviour
{

    public GameObject target = null;

    public KeyCode interactKey;

    public GameObject itemHolder;

    private void Update()
    {
        if (Input.GetKeyDown(interactKey))
        {
            if (target == null)
            {
                return;
            }

            FoodBox food = target.GetComponent<FoodBox>();
            if (food != null && itemHolder == null)
            {
                food.Interact(this);
            }

            TableBox table = target.GetComponent<TableBox>();
            if (table != null)
            {
                table.Interact(itemHolder, this);
            }

        }
    }

    public void SetItem(GameObject c)
    {
        if (c != null)
        {
            Debug.Log("Взяли предмет!");
            itemHolder = Instantiate(c, transform.position + new Vector3(0f, 2.15f, -0.65f), Quaternion.Euler(-90f, 0f, 180f), transform);
        }
        else
        {
            Destroy(itemHolder);
        }
    }

    private void OnTriggerEnter(Collider col)
    {
        if (target != col.gameObject && target != null)
        {
            return;
        }
        else {
            target = col.gameObject;
            Debug.Log("Мы дошли сюда до " + target.name);
        }

    }

    private void OnTriggerExit(Collider col)
    {
        if (col.gameObject == target)
        {
            target = null;
        }
    }
}

```

***TableBox:***

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

public class TableBox : MonoBehaviour
{

    public GameObject itemHolder;

    private void Start()
    {
        if (itemHolder != null)
        {
            itemHolder = Instantiate(itemHolder, transform.position + new Vector3(0f, 1.9f, 0f), Quaternion.Euler(-90f, 45f, 0f),transform);
            Debug.Log("Мы создались!!");
        }
    }

    public void Interact(GameObject i, PlayerInteraction player)
    {
        if ((i == null || itemHolder == null))
        {
            player.SetItem(this.itemHolder);
            Destroy(this.itemHolder);
            //Debug.Log(itemHolder);
            this.itemHolder = i;

            if (this.itemHolder != null)
            {
                this.itemHolder = Instantiate(this.itemHolder, transform.position + new Vector3(0f, 1.9f, 0f), Quaternion.Euler(-90f, 0f, -135f),transform);
                Debug.Log("Мы ингридиенты из ТейблБокса!");
            }
        }
        else
        {
            return;
        }
    }
}

```

***FoodBox:***

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

public class FoodBox : MonoBehaviour
{

    public GameObject ingredient;
    private Animator anim;

    // Use this for initialization
    void Start()
    {
        anim = GetComponent<Animator>();
        anim.SetBool("openFoodBox",false);
    }
    public void Interact(PlayerInteraction player)
    {
        anim.SetBool("openFoodBox", true);

        if (anim.GetBool("openFoodBox")) {
            anim.Play("Opening");
            player.SetItem(ingredient);
            Debug.Log("Мы ингридиенты из ФудБокса!");
        }

        anim.SetBool("openFoodBox",false);
    }
}

```

There is also an assumption that this is due to the initial position of the models. Because for me, some models are stored normally vertically, and some lie horizontally.

I also add the prefab inspector:

Eye of the Cyclops:

Flask:

# Answer
> 5 votes
As usual, the answer to "Why is Unity doing this bizarre thing" is "Unity is doing an entirely normal thing with bizarre data you gave it"

In this case, the origin of your flasks in Blender sits far outside the object itself, where the blue & red arrows cross in the image below:

This is the point that becomes the local (0, 0, 0) point when you import the mesh into Unity.

To make the object sit where you wanted it, you had to add a substantial vertical offset to your object position (`+ new Vector3(0f, 1.9f, 0f)` in your code), to place this origin high above your character, so that the visible mesh way below it would line up where you wanted it.

But when you spawn an object with the origin in a more expected position - the cyclops eye's origin is at its center - the result is the visible mesh sitting higher than you want it.

So, the best solution is to model your objects with the origin in a standardized place relative to the visible mesh (say, around its center of mass or at its base). See how to modify the origin of an object in Blender here.

If for some reason correcting the source mesh is not an option, you can also wrap it in an empty parent game object, and move the child mesh until it sits where you want relative to the parent's origin. Then, spawn and manipulate the parent, rather than the mesh directly.

---
Tags: unity, blender
---


# Question
Title: Creating a victory zone / Count units inside zone
So I am attempting to create a zone implementation where if the amount of units with a certain tag exceeds the number of units with another tag an objective will be captured standing in the zone will capture an objective.

However, the problem occurs when counting the units and what the most optimal way of doing it is which is what I hope you guys can help me with! (Also if you have a better way of implementing it then I am all ears).

So in **my** implementation, I have added a game object with a box collider which is set as a `trigger` collider

my idea was that as soon as a unit enters or leaves the script will update the count of users with a certain tag.

Should the count of one tag type be greater than the other the victory/capture condition will begin.

This is an ok solution however it has a major problem. Should one of the NPC's inside of the box collider die the script will never detect it as the body has never left the box.

So how do i overcome this problem in a sensable way?

# Answer
> 0 votes
I'd say the simplest way to handle this is to add to each agent an extra collider for counting, on a dedicated "Counting" layer. You can give it a simple shape, and size it independent of the colliders you use for hit detection, which can help with fairness. (For instance, you might not want a character with big wings to be able to hold a control point from further away than a small compact character can)

You can set up your physics layers so that your victory zones detect collisions/overlaps only with these counting colliders, and vice versa, so you don't have to process & filter uninteresting trigger messages.

Now, when an agent dies, set its counting collider's `.enabled` property to `false`. This will fire an `OnTriggerExit` on its containing victory zone just the same as if it had left the zone or been destroyed. And as a bonus, you can always set it back to `true` if you resurrect the agent or recycle it via an object pool.

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


# Question
Title: Maintaining/Updating Large Amount of Player States
I am developing a fighting game to practice my skills in Java and I would like to know what would be the best approach for figuring out how to easily expand the amount of states a player can have without fiddling with a large amount of code. With a small amount of states such as, inAir, isHurt, isRunning, I can hard code all the conditions I need. Things like 'jumping' can only occur when '!inAir', etc. However, for my project there are a large amount of states I do not know how to organize. Here is a small diagram I redrew:

My approach is to make an enumeration called State and do a switch case between them. I am not sure if this is a good way of doing this and I am trying to learn a better method if there are any.

# Answer
> 1 votes
I'd organise it similarly to what you described.

Pseudo-code:

```
enum totalStates = {STATE_1, STATE_2, ..., STATE_N};
totalStates state = totalStates.STATE_1;

void Update() {

    switch (state) {

        case totalStates.STATE_1:
            // update STATE_1
            break;

        // ... other states ...

    }

}

bool initState(totalStates newState) {

    switch (newState) {

        case totalStates.STATE_1:
            // check if the object's data allow the object to move to STATE_1
            if (canState1) {
                state = totalStates.STATE_1;
                return true;
            }
            return false;

        // ... other states ...
    }

```

So every time you want your object to move to a new state, call `initState(totalStates.STATE_2)` (or any other state) and if it returns `true` the object has moved to that state, if it returns `false`, the object refuses to move to that state. For example if a character is in the air, and user presses the jump button again, the program would ask the object to go to jumping state, the object would see it is already in the air, and refuse.

If you are worried about being scalable and organisation because you have too many states, you can separate state logic to use different functions, like `updateState1()` or `updateState2()` etc etc.

# Answer
> 1 votes
Alternatively, you could try to restructure your code so there are a few different State categories that are set independently, like Stance, Movement, IsDazed, etc. Also, you could make a State/SubState system where the SubState provides more detail on top of the general State.

---
Tags: software-engineering, fsm, fighting-game
---


title: How are 3D game levels built?

text:
# Question
Title: How are 3D game levels built?
I am wondering what is the best / most common practice in 3D games (mostly shooters) like Quake or Doom. How are the levels built?

With larger, open spaces the answer is probably some kind of terrain editor, that is what I understand. But what about things like houses or closed areas?

I see two main solutions. One is to make a whole house, factory, dungeon (or generally a level) in other tool, like Blender, and then put it in the game. Other is to make the most simple elements like walls, floor, doorways and make the level from them (like Lego blocks).

Is one of the ways more common? More "industry standard"? Are there some obvious advantages or disadvantages?

# Answer
Both options are used. Both have advantages. However, big games tend towards a moduler design.

Creating in an external tool will give you more control. However, it will not scale well. So, for large games, it is better idea to make pieces in an external tool and let the designer place them.

A big advantage of of making pieces is that the level designer can focus on the structure of the level (where is cover, etc.) instead of having to worry about dealing with meshes, et. al. This means that 3D designers can improve the look of the pieces at the same time as the level designer is working.

The drawback, of course, is that elements can appear repetitive. Because they are. Creating everything as a custom model will make sure everything is unique. On the other hand, it will make the game heavier because it has less re-utilization, as I said, does not scale well.

There are ways to mitigate the drawback of repetitive elements, the more common is to be able to layer things on top of each other. Besides, after the level is done, you will need testing, and if something looks wrong, it should be flagged for review and change.

See GDC talk Fallout 4's Modular Level Design.
> 2 votes

---
Tags: blender, unreal-4
---


# Question
Title: How can I make an OpenGl/GLSL varying vary throughout a quad instead of a triangle in OpenGl 3.3?
I am, like many others, currently working on a block-based game in C++ and OpenGl. Recently, I added ambient occlusion support. This ambient occlusion is created by modulating the brightness of a point on the face of a block by an OpenGl varying from each corner. The corner's darkness is proportional to the amount of blocks that intersect that corner. This usually works very well, as can be seen in this screenshot:

It does create some artifacts, however. One good example is seen at the base of a tree trunk:

In this example, the size of the pseudo-shadow varies based on the orientation of the triangles around the chunk as described here:

> Notice that the ambient occlusion is different for the vertices on the side than it is for the vertices on the top and bottom. To fix this, we just need to pick a consistent orientation for the quads. This can be done by comparing the ambient occlusion terms for each quad and selecting an appropriate orientation.

Their proposed solution, however, is not of the kind that I prefer. It seems more like a trick to cover up the fact that the varyings aren't being interpolated over the whole quad, as opposed to a real solution. As such, I thought that it may work to render with GL\_QUADS instead of GL\_TRIANGLES, as perhaps that would allow the varyings to vary as I want. Unfortunately, this is not possible in the version of OpenGl that I am targeting (3.3 core). As such, I ask: how can I interpolate the varying values (eg. the brightness) over a quad instead of a triangle? Is there some algorithm that I can use to change the brightness value at each corner of a quad to produce the same result? I have tried searching for this via a search engine, but no useful results came up.

# Answer
> 2 votes
There is no "the whole quad" for OpenGL to interpolate values across. It doesn't exist, in your current setup, so you're not going to be able to make OpenGL do that, and you'll need to make it happen yourself.

It seems to me that an easy way to approach this would be to make a tiny 2x2 pixel texture for each face of each cube and put the occlusion data for each vertex of the face into those four texture pixels. Then in your fragment shader, sample the face's occlusion data from those tiny textures. Sampling a 2D texture is interpolated between the four texels around the sample point, and since you're doing it inside the fragment shader, you're avoiding the problematic triangle-based interpolation that OpenGL does.

Of course, doing that for each face of each cube would require a huge number of textures, even if you only do it for the exposed faces. If you do want to do this, you'd probably want to bundle all these tiny textures together into a single texture array, just to simplify how many texture objects you need to bind and unbind during rendering, and to simplify sampling.

To me, this still seems like a lot of work for something that seems like a pretty minor graphical anomaly.. but I don't immediately see any obviously better approaches. Up to you whether it's worth the bother to satisfy your demands of not doing something that feels like a "trick"?

---
Tags: opengl, glsl, voxels, block-world, ambient-occlusion
---


# Question
Title: Why does releasing a pressed "f" key not prevent the coroutine from spinning?
I am learning Unity and the following is my simplification of the code presented on Coroutines.

My expectation is that the `Fade()` just spins in a very very short period of time because the `GetKeyDown("f")` is `true` only at the transition from "unpressed" to "pressed" states.

However in the following code, the `Fade()` spins from `f=0` to `f=999` continuously (non stop in one go) rather than for example, from `f=0` to `f=100` at the first key press and from `f=101` to `f=159` at the second key press, etc.

```
IEnumerator Fade()
{
    for (int f = 0; f < 1000; f++)
    {
        Debug.Log($"{f}");
        yield return null;
    }
}

void Update()
{
    if (Input.GetKeyDown("f"))
    {
        StartCoroutine("Fade");
    }
}

```

# Question

What causes this unexpected result and how to solve it?

# Answer
> 2 votes
`StartCoroutine` does exactly that: it *starts* the coroutine. The coroutine then continues running independently of the code that started it (when its turn comes in the engine's single-threaded script update loop, not in parallel), until you tell it to stop.

You can stop it from an outside method, the same way you started it, by holding a reference to the running coroutine:

```
Coroutine myFade;

void Update()
{
    if (Input.GetKeyDown("f"))
    {   // Start the coroutine when the F key transitions from up to down.
        myFade = StartCoroutine(Fade());
    }
    // The coroutine will continue running since we don't tell it otherwise.
    if (Input.GetKeyUp("f"))
    {   // Stop the coroutine when the F key transitions from down to up.
        StopCoroutine(myFade);
        myFade = null;
    }
}

```

Or you could make the coroutine check for its own stopping condition:

```
IEnumerator Fade()
{
    for (int f = 0; f < 1000; f++)
    {
        if(Input.GetKeyUp("f"))
            yield break;

        Debug.Log($"{f}");
        yield return null;
    }
}

```

It sounds like what you're expecting rather than `StartCoroutine()` is something like a "`StepCoroutine()`" method, where the coroutine advances only when you ask it to in Update. You can manage something similar with your original `IEnumerator` like so:

```
IEnumerator myFade;

void Update() {
    // When we strike the key, start the enumeration if we didn't already.
    if (Input.GetKeyDown("f") && myFade == null)
        myFade = Fade();

    // As long as the key is held, step the enumeration.
    if (Input.GetKey("f"))
        myFade.MoveNext();
}

```

Here because we're managing the frames when we want to run the enumerator's code ourselves, we don't need to wrap it in a Unity coroutine for the engine to manage its lifetime and keep stepping it without us.

Though we could simplify this example further to just:

```
int iterationCount = 0;
void Update() {
    if(Input.GetKey("f") && iterationCount < 1000)
        Debug.Log(iterationCount++);
}

```

With no `IEnumerator` at all.

---
Tags: unity
---


# Question
Title: Quaternion.RotateTowards not working as expected when parent object moves/rotates
I have a Tank with a rigidbody. A Turret Base is attached to the Tank via a Hinge Joint. The below `TurretController` script is attached to the Turret Base in order to rotate it to point towards the direction of the mouse.

The turret rotates flawlessly when the tank is stationary. But once I start moving the rotation behavior becomes very erratic: https://youtu.be/v1VuTbMtcCM

If anyone is able to help/explain this behavior it would be much appreciated!

```
/// <summary>
/// Rotates a turret towards a point at a fixed angular velocity.
/// </summary>
public class TurretController : MonoBehaviour
{
    public float m_DegreesPerSecond = 40f;

    private Vector3 m_TargetPosition;

    // Received from mouse move event
    public void Rotate(PointInputInfo inputInfo)
    {
        m_TargetPosition = inputInfo.Point;
    }

    private void RotateTurret()
    {
        Vector3 direction = Vector3.Scale(m_TargetPosition - transform.position, new Vector3(1, 0, 1));
        Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up);
        Debug.DrawLine(transform.position, m_TargetPosition);

        // Rotate at a fixed angular velocity.
        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * m_DegreesPerSecond);
    }

    private void FixedUpdate()
    {
        RotateTurret();
    }
}

```

# Answer
As DMGregory pointed out it's unwise to mix `Rigidbody` physics and direct transform manipulation.

Below is my solution using torque to rotate at a fixed angular velocity (in degrees per second). I apply an instant counter force when the direction is within tolerance to avoid constant adjustment jitter.

Note that for high values of `m_DegreesPerSecond`, the tolerance values have to be increased in order to stop jitter, which isn't ideal.

```
    private void RotateTurret()
    {
        // Direction of the target from our current position.
        Vector3 direction = Vector3.Scale(m_TargetPosition - transform.position, new Vector3(1, 0, 1));

        // Get the angle between transform.forward and target delta.
        float angleDiff = Vector3.Angle(transform.forward, direction);

        // Get the cross product, which is the axis of rotation to get from one vector to the other.
        Vector3 rotationForce = Vector3.Cross(transform.forward, direction);

        Debug.DrawRay(transform.position, direction, Color.magenta);

        // The difference between current velocity and the velocity I want.
        float velocityAdjustmentScalar = (m_DegreesPerSecond * Mathf.Deg2Rad) - m_Rigidbody.angularVelocity.magnitude;

        // If we're within tolerence
        if (angleDiff < 1.5 && angleDiff > -1.5)
        {
            // Apply counter torque, to prevent constant adjustment jitter.
            m_Rigidbody.AddTorque(-m_Rigidbody.angularVelocity, ForceMode.Impulse);
        }
        else
        {
            // Add torque towards the target,
            // scaled by the velocityAdjustmentScalar in order to maintain a fixed angular velocity.
            m_Rigidbody.AddTorque(rotationForce * velocityAdjustmentScalar, ForceMode.Force);
        }
    }

```

**EDIT:**

For anyone that's interested and for future reference, **my final solution was to make use of the `HingeJoint`'s `JointMotor`.** This comes with the added advantage of being able to easily set a fixed target velocity and a maximum force to apply to maintain that velocity. For example you can mimic resistance/breaking force by setting the target velocity to 0 and the force parameter to some higher value, which provides resistance up to the maximum force.

```
    private void RotateTurretUsingMotor()
    {
        // Direction of the target from our current position.
        Vector3 targetDirection = Vector3.Scale(m_TargetPosition - transform.position, new Vector3(1, 0, 1));

        // Get the angle between transform.forward and target delta.
        float angleDiff = Vector3.Angle(transform.forward, targetDirection);

        // Get the cross product of the transforms forward and target direction,
        // resulting in an orthogonal vector in the direction of the axis of rotation.
        Vector3 rotationDirection = Vector3.Cross(transform.forward, targetDirection);

        // Divide the angular tolerence by 2 to represent the number of degrees tolerance.
        if (angleDiff > m_AngularTolerance / 2 || angleDiff < -m_AngularTolerance / 2)
        {
            // Add positive or negative angular velocity depending on the rotation direction.
            if (rotationDirection.y > 0)
            {
                m_JointMotor.targetVelocity = m_TargetAngularVelocity;
            }
            else
            {
                m_JointMotor.targetVelocity = -m_TargetAngularVelocity;
            }

            m_JointMotor.force = m_Force;
        }
        else
        {
            // Set the motor to maintain a target velocity of 0 up to a maximum level of force.
            m_JointMotor.force = m_Force;
            m_JointMotor.targetVelocity = 0;
        }

        // Apply the changes to the motor.
        m_HingeJoint.motor = m_JointMotor;
    }

```
> 1 votes

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


# Question
Title: OpenGL tile map rendering with 1 quad for all tiles and 1 texture atlas
I'm using lwjgl to experiment with 2D games.

I made some maps with Tiled (small 30x30 maps) and currently I draw them by loading the tileset image as one texture and extracting from it the texture coordinates for each tile (so a texture atlas).

Every tile is one quad model (vao + 3 vbos: indices, vertices, texCoords) and to render the map I bind the texture atlas, then for each tile I bind the vao and call glDrawElements to draw the model of the tile.

To improve this, I thought I could have one single little quad that represents one tile and move it around changing its texture. This way I'd only have 1 vao+vbos in memory. The problem is that I'm not sure how to handle changing the tex coords.

I could put in the texCoords vbo of this model, all the "regions" of the texture atlas, but then how do I tell the draw call to use some specific 4 coordinates in the long list of coords of the vbo? Maybe I could use the fragment shader in some way?

# Answer
> 2 votes
I suggest you to read about the vertex input layout and geometry shaders.

In general: define your goal first, let's say the goal is to use only one draw call and least vertexbuffer updates because you want to keep the gl calls to a minimum. first calculate the uv coordinates for every region in your texture atlas and store them in a hashmap in ram. Then define what parts of your tiles are static and which are dynamic in terms of transformation matrices, this is required to determine the best method of least updates. Using Drawelements is ok for tile rendering.

Let's reformulate your problem: I want to draw a dynamic amount of 2d vertex quads at dynamic positions with dynamic texcoords. That's 3 dynamics, namely the amount of vertex quads, each quads transformation and each quads vertex to texcoord mapping. Maybe each quad should have an dynamic size?

Oldschool solution: 1. Calculate every quad transform on cpu and update all gl buffers every frame. A quad are 6 vertices unindexed or 4 vertices indexed and 2 ushort indices. 2. Use drawelements or if you are even oldschooler use the draw, which means you have to use an indexbuffer and vertexbuffer combination. 3. When your quads should move just update the buffer on cpu, for rendering the whole buffer or portions of it will be updated to vram via glbuffersubdata or glmapbuffer. It means you have a total of 3 - 4 gl calls every frame.

Modern solution. 1. Use uniform buffers to store texcoords and matrices per quad of all tiles if you have lots of dynamic tiles and few static. The uniform buffer is just a struct with two arrays of texcoords and matrices. This way you can manipulate each tiles position and texture without having to modify vbo or vao. 2. Use drawelements and lookup uniformbuffer matrix inside vertexshader. 3. Use a geometry shader to generate your vertex quad inside gpu per matrix texcoord tuple. For simple quads it's faster to be calculated in geometry shader, for geometry like arcs with lots of cos and sin it's slower in geometry shader. In fragment shader just do regular texture mapping. 4. Update uniform buffer and call drawelements. This way you have only 2 gl calls, one to update the uniform buffer and the other to drawelements. On cpu you just update the individual matrices and tecoords inside uniform buffer struct.

---
Tags: opengl, tilemap, lwjgl, texture-atlas, tiles
---


# Question
Title: How do I draw multiple irregular polygons with OpenGL ES?
In this post I was asking how to program a map of a Risk-like game.

Now that the map is pretty coded, both client and server-side, I'd like to finally draw the map.

I'll try to keep least broad as possible in this question, and also avoid XY problem.

So, my X problem is that I need an interactive map, based on (irregular) polygons.

Now, since this question would be really broad (there is a heavy number of possible solutions and libraries for a skilled programmer), this is how I imagined my Y solution:

Since the polygons have to be 10, touch-interactive, filled with plain color, I think that OpenGL ES should go fine for me. I'm also attracted by Path and Point classes, but the problem is that

1. The map should be displayed for lot of different screen sizes, but at the same time it should keep its ratio, instead of appearing more large or more little in the Activity.
2. The polygons have to be drawn to fit each others.
3. Every polygon should be touchable and the event should differ from the others. Also their color could change depending of the situation.

I don't know if Path and Point classes would fit for this. My intent is more game-like than generic, so I think I'll stick with OpenGL ES solution.

The problem is that I don't understand

1. How can I map the polygons vertex and dimension for different screen sizes?

(considering we're talking about 10 polygons, there is a kind of environnment for doing this?)

2. Should I use triangulation or not? I've done lot of research but this point wasn't clear to me.

I followed Android Open GL tutorial, but it only shows simple polygons and alone, I'd need 10 with lot of vertexes and above all that can fit each others.

How can I do this?

EDIT: I also tried to follow this tutorial. This is an image taken from that one:

<sub>(source: xamarin.com)</sub>

To me instead, it's more little and near top-left corner. This is another trouble I'd like to avoid (as I said in point 1 above): my polygons should always fit the screen (and this is also why I want to use OpenGL ES).

# Answer
> 1 votes
So you want to draw polygons that fit the screen and have touch support? Opengl can be used to draw the polygons, touch support can be realised independent from opengl by a thing that is called ray triangle intersection and requires you to understand a bit of math.

Here's how you maintain the correct size on different screen resolutions: you use what is called projection matrix. In your case an orthographic projection is sufficient. Please read about opengl matrices here: https://learnopengl.com/Getting-started/Coordinate-Systems

In depth what you do is you map from screenpixels to NDC range which is -1 to 1, where the center 0,0 is exactly the center of your screen. You then define your polygon 2d layout by relative positioning like starting from top left. Now in order to maintain correct relative sizes on different resolutions you have to adjust the orthographic size, think about it like optical zoom. For big screens you have bigger orthographic size. To calculate the orthographic size you must know your bounding rect in ndc and adjust your orthographic size according to it. Note that if you support landscape mode you have to adjust the orthographic size different because width is bigger than height, or you layout your polygons different.

How to touch those polygons? First you have to calculate a picking ray by going from screen pixel position aka the screen space to world space. Easiest way to understand the picking ray is to understand the projection matrix. Everything you see on screen starts at the near plane and ends at the far plane. So if you want to test if you are touching an object you have to project your screen position to the nearplane and the far plane, those 2 points form a 3d line which is the ray I'm talking about. Now you go through all your polygons and test each triangle for intersection with the ray. An example can be found on github in sharpdx repository and collision.cs. you can simplify the intersection test because you only need 2d test in which case it's enough to project screen coordinates to ndc space and test all triangles if the ndc touch coordinate is inside the triangle.

Or if you don't want to learn maths you can simply put your polygons as pictures and use them as backgrounds of buttons. Not very precise but maybe enough.

---
Tags: java, android, opengl-es, opengl-es2
---


# Question
Title: Calculate position given velocity and acceleration at a given timestep
I am following a Pixar course at Khan Academy and I came across a simulation of a double spring with a given timestep. I understand how it works and why it behaves the way it does, but I want to know if the math is actually accurate. What I'm interested in is the following lines:

```
 // Mass 1 velocity
 mass1VelocityY = mass1VelocityY + mass1AccelerationY * timeStep;
 mass1VelocityX = mass1VelocityX + mass1AccelerationX * timeStep;

 // Mass 1 position
 mass1PositionY = mass1PositionY + mass1VelocityY * timeStep;
 mass1PositionX = mass1PositionX + mass1VelocityX * timeStep;

```

So we first calculate the velocity, adding a fraction of the calculated acceleration to it, and then we calculate the position, adding a fraction of the calculated velocity to it. So we are building the final position at time `T` by summing `T/timestep` intermediate positions.

Given the formula for displacement `s=ut+0.5at^2` where:

s = displacement u = initial velocity a = acceleration t = time

If I plug in the values: s = 0, u = 0, a = 1, t = 2, I will get `s = 2`. That means that if I start at position zero and I build up the velocity with an acceleration of 1m/s/s I will end up at position 2, with a velocity of 2m/s.

Now if I try to follow the same logic but break that result into 20 steps`(2/0.1 - t = 2 timeStep = 0.1)`, and sum the results of all these intermediate steps as is being done in that code, I will get a different result: `s=0.55 at t=1` and `s=2.1 at t=2`.

My initial intuition is that because in the code we end up multiplying timeStep by acceleration twice, it becomes exponentiation and so the progession isn't linear anymore and so smaller steps will get smaller values in the beginning. So I have 3 questions:

1) Did I understand what the code is doing correctly?

2) Is what the code is doing the most correct/accurate way to calculate displacement?

3) I really want to grasp these concepts so if you have any other advice or know of something that would be helpful for me to learn, please point me to it.

# Answer
This is the “explicit” or “forward” Euler method for numerically integrating your differential equation that models a spring.

https://en.wikipedia.org/wiki/Euler\_method

It is unconditionally unstable, meaning that no matter what time step you use, the error with respect to the true solution to the equations can compound without bound as time goes on.

The smaller the time step, however, the slower the error accumulates. That’s what you’re seeing here.

Another approach is the “implicit” or “backward” Euler method, which is unconditionally stable. This computes a solution whose error does not compound with abandon like that of the forward approach, even if the time steps are large.

https://en.m.wikipedia.org/wiki/Backward\_Euler\_method

This is a deep topic of interest to all sorts of people, especially those with practical interest in fast and correct solutions to various differential equations. Those people have built up a lot of theory about it over the years.
> 1 votes

# Answer
No, that's because of the nature of mathematical integration and floating point precision. If you break it into more steps you will get more accurate results because of the better integration, but if you make too much steps, you will actually start to get more errors because of the insufficient floating point precision.

```
#include <cmath>
#include <cstdio>

//uncomment to test double precision
//#define DOUBLE_PRECISION

#ifdef DOUBLE_PRECISION
typedef double fp_type;
#else
typedef float fp_type;
#endif

void run_test(int steps, fp_type u, fp_type a, fp_type t)
{
    fp_type timestep = t / steps;
    fp_type mass1Velocity = 0.0f;
    fp_type s = 0.0f;
    for(int i = 0; i < steps; i++)
    {
        mass1Velocity += a * timestep;
        s += mass1Velocity * timestep;
    }
    printf("s(%i steps): %f\n", steps, s);
}

int main()
{
    //initial velocity
    fp_type u = 0.0f;
    //acceleration
    fp_type a = 1.0f;
    //time
    fp_type t = 2.0f;
    //displacement
    fp_type s = u*t+0.5f*a*pow(t, 2.0f);
    printf("s(exact solution): %f\n", s);

    //test 2e(i) steps
    for(int i = 0; i < 7; i++)
        run_test(2*pow(10, i), u, a, t);

    return 0;
}

```

Output (single precision):

```
s(exact solution): 2.000000
s(2 steps): 3.000000
s(20 steps): 2.100000
s(200 steps): 2.009999
s(2000 steps): 2.001011
s(20000 steps): 2.000240
s(200000 steps): 2.002040
s(2000000 steps): 1.987711

```

Output (double precision):

```
s(exact solution): 2.000000
s(2 steps): 3.000000
s(20 steps): 2.100000
s(200 steps): 2.010000
s(2000 steps): 2.001000
s(20000 steps): 2.000100
s(200000 steps): 2.000010
s(2000000 steps): 2.000001

```
> 1 votes

---
Tags: 2d, physics, mathematics, displacement-mapping
---


# Question
Title: How can I use Cross Platform Input in Unity 2019?
I am trying to use CrossPlatformInput in Unity 2019 to follow this tutorial to use it on iOS:

https://www.youtube.com/watch?v=Auj1mrsfXDE

However, I have no item in the top bar for "Mobile View" like in the tutorial, and I do not know how to enable it. I have Standard Assets imported already. Is there an example project I can download with CrossPlatformInoput that works with iOS or a way for CrossPlatfromInput to work in modern versions of Unity?

# Answer
I had the same problem and fixed it by adding this code to my project, hopefully, it'll fix yours too.
> -1 votes

---
Tags: unity, ios, input, cross-platform
---


title: Understanding Tetris speed curve

text:
# Question
Title: Understanding Tetris speed curve
I'm attempting to make a Tetris clone and want to be as accurate to the games as I can. I found a chart that explains the speed curve that's supposedly used in games that follow the official Tetris guideline: https://harddrop.com/wiki/Tetris\_Worlds

**1G = 1 cell per frame**

* **Level 1:** 0.01667G
* **Level 2:** 0.021017G
* **Level 3:** 0.026977G
* **Level 4:** 0.035256G
* **Level 5:** 0.04693G
* **Level 6:** 0.06361G
* **Level 7:** 0.0879G
* **Level 8:** 0.1236G
* **Level 9:** 0.1775G
* **Level 10:** 0.2598G
* **Level 11:** 0.388G
* **Level 12:** 0.59G
* **Level 13:** 0.92G
* **Level 14:** 1.46G
* **Level 15:** 2.36G

Another thing that might be worth noting is, like most Tetris games, my loop is updating at 60fps.

So given all this, there are two things that I'm having problems understanding.

**1: The speed curve doesn't always translate to whole numbers.**

For example, at level 2: `1 / 0.021017 = 47.5805300471`. So every 47.5805300471 frames the game is supposed to drop the piece one row. Am I supposed to round these numbers? I can't process a partial frame so I don't understand why the speed curve comes out as a decimal.

**2: Level 14 and 15 drop the piece more than one row per frame**

Because it's dropping more than one row per frame, this would make some moves impossible in the game. For example, if I wanted to move a piece horizontally into a one cell space and the game is dropping the piece more than one row at a time, it will skip the row entirely and make the move impossible. Is this correct or am I missing something?

# Answer
A good approach is to have two time-based counters.

* How long does the tetromino exist
* How long have you simulated its physics

When you spawn a new tetromino, start both at 0.

In the beginning of your update-loop, add the time since the last execution of the update-loop to the existence time. I personally prefer to keep all times in seconds so you can easily experiment with your updates-per-second rate without having to modify too much code. But if you are completely sure you are never going to try anything else but 60 updates per second, you can of course use frames instead of seconds as your unit of time.

Next, check the difference between existence time and simulated time. While the existence time is larger than the physics time:

1. Move the tetromino down one row
2. Add the "time per drop" to the simulated time

Or in pseudocode:

```
time_exists += time_since_last_update // or +1 if you are using a fixed framerate
while (time_exists > time_simulated)
    tetromino.y -= 1
    time_simulated += 1 / cells_per_time_unit

```

That means if you have a falling speed of 2.5 cells per frame, then the above code will alternate between moving it 2 cells and 3 cells.

This, by the way, means that starting from level 14 it will be *physically impossible* for the player to make certain moves because the line on which they need to make that move gets skipped. So if you expect your players to become so good at tetris that this starts to matter, then you should use a higher logical update-rate than 60 FPS, even if your actual graphics render rate is capped.
> 1 votes

# Answer
"For example, at level 2: 1 / 0.021017 = 47.5805300471. So every 47.5805300471 frames the game is supposed to drop the piece one row."

I think it works more like the following (every frame):

1. increase timer by gravity (0.021017)
2. go to step 4
3. move the tetrimino down and decrease timer by 1
4. if timer is equal to or larger than 1, go to step 3, otherwise finish

As for the impossible placement, it is indeed impossible.
> 1 votes

# Answer
In addition to Philipps answer:

Most programming Environments offer really precise timers. If you save the exact moment of a keypress you can still handle actions made in between frames as if you where handling them real time.

Suppose your tetromino moved 2 Blocks per second and you had a framerate of 1fps. If the input occured until 500ms after the last frame you will make the calculations as if the tetromino hadn't moved. Anything after 500ms you will handle it as if it had already moved 1 block. Using timers you cane have high precision input even on low framerates.

This might require a bit of fiddling for it to behave the way you feel like it should.
> 0 votes

---
Tags: tetris
---


# Question
Title: Can HTTPS webserver host an HTML page that uses JS to connect with secured web socket protocol multiplayer game just like node js?
Can HTTPS webserver host an HTML page that uses JS to connect with secured web socket protocol multiplayer game just like node js? If so point me in the correct direction to read more.

# Answer
> 1 votes
You can create a client websocket in browser-based JavaScript like this. Note the protocol `wss://` before the URL of the server. `wss` is to `ws` like `https` is to `http` \- it's websocket via TLS.

```
var socket = new WebSocket("wss://example.com/yourgameserver");
socket.onerror = errorHandler;
socket.onopen = openHandler;
socket.onmessage = messageHandler;

function errorHandler(error) {
     // your code to handle connection errors
}

function openHandler(event) {
     // your code to handle a successful connection.
     // event.data might already contain the first data from the server
}

function messageHandler(event) {
     // your code to handle messages received from the server.
     // event.data will contain the message payload
}

```

After the connection is established, you can send data to the server with:

```
socket.send(data);

```

where `data` can be a String, ArrayBuffer, ArrayBufferView or Blob.

Check the documentation of the WebSocket API for further details.

But keep in mind that the websocket protocol won't allow you to connect to *any* multiplayer game. The WebSocket protocol isn't raw TCP/IP. The data is wrapped in a framing protocol. In order to allow a websocket connection, the server needs to understand that protocol.

Further, many websocket-based servers check the `Origin` header of incomming websocket requests to avoid connections from JS applications hosted on unauthorized websites. This header contains the URL of the website on which the script is running. So if you are trying to create an own client for a websocket server controlled by someone else, that server can easily refuse the connection.

---
Tags: client-server, server, node.js, websocket
---


title: Optimum Path Finding in Varied Terrain

text:
# Question
Title: Optimum Path Finding in Varied Terrain
I'm building a sort of city building sim and would like the ability for people to automatically place roads (or rail) based on a start and end point and for the sim to calculate the optimal route. I thought this would be relatively easy to do with normal path finding but I'm finding it challenging to deal with impassable obstacles and areas where you really wouldn't want a road/rail unless there was no other option!

See an example below - the difficult terrain might be a swamp or a park which we'd like to preserve if possible and the impassable might be really bad terrain, or something protected - for example a National Park.

I thought about using Dijkstra's algorithm but there is no real set of routes/nodes - as you can see the possible routes are quite open, same with A\*. The areas covered would also be quite large so I'm trying to avoid a grid based system - I'm wondering if there is a vector based path finding algorithm? I found this https://faculty.nps.edu/ncrowe/opmpaper2.htm which creates a grid of vectors which looks halfway to what I want, but again could be quite expensive on a large area.

Any suggestions would be appreciated!

Thanks,

# Answer
> 2 votes
A\* and Dijkstra work based on a graph of nodes. They don't need to be grid based.

So you can create a node for each section and then generate next options based on that.

Given a node you have a position and a direction (and a curve if you want to generate smooth curves), From that you can create several candidates by adjusting the length and new curve. Each of those candidates would have a cost based on the terrain the section goes through.

The A\* heuristic can be a simple distance from endpoint to the goal.

The trick bit would be limiting the candidate generation Which you can do by keeping the distance per segment large in a first generation per node then allow shorter segments to be generated.

---
Tags: 2d, path-finding
---