# Question
Title: How to calculate corner positions/marks of a rotated/tilted rectangle?
I've got two elements, a 2D point and a rectangular area. The point represents the middle of that area. I also know the width and height of that area. And the area is tilted by 40° relative to the grid.

Now I'd like to calculate the absolute positions of each corner mark of that tilted area only using this data. Is that possible?

# Answer
```
X = x*cos(θ) - y*sin(θ)
Y = x*sin(θ) + y*cos(θ)

```

This will give you the location of a point rotated θ degrees around the origin. Since the corners of the square are rotated around the center of the square and not the origin, a couple of steps need to be added to be able to use this formula. First you need to set the point relative to the origin. Then you can use the rotation formula. After the rotation you need to move it back relative to the center of the square.

```
// cx, cy - center of square coordinates
// x, y - coordinates of a corner point of the square
// theta is the angle of rotation

// translate point to origin
float tempX = x - cx;
float tempY = y - cy;

// now apply rotation
float rotatedX = tempX*cos(theta) - tempY*sin(theta);
float rotatedY = tempX*sin(theta) + tempY*cos(theta);

// translate back
x = rotatedX + cx;
y = rotatedY + cy;

```

Apply this to all 4 corners and you are done!
> 39 votes

# Answer
It is a common technique to rotate a point about a pivot by translating to a coordinate system where the pivot is the origin, then rotating about this origin, then translating back to world coordinates. (A very good explanation of this approach is available at Khan Academy)

However you are not storing your rectangle corners in world coordinates so we can tailor an approach to suit the data you have available.

```
Cx, Cy // the coordinates of your center point in world coordinates
W      // the width of your rectangle
H      // the height of your rectangle
θ      // the angle you wish to rotate

//The offset of a corner in local coordinates (i.e. relative to the pivot point)
//(which corner will depend on the coordinate reference system used in your environment)
Ox = W / 2
Oy = H / 2

//The rotated position of this corner in world coordinates
Rx = Cx + (Ox  * cos(θ)) - (Oy * sin(θ))
Ry = Cy + (Ox  * sin(θ)) + (Oy * cos(θ))

```

This approach can then be easily applied to the other three corners.
> 4 votes

# Answer
Based on the other answers, and to complement them, I managed to create an example with P5 here.

Here is the code, in case you want to access it directly:

```
function setup() {
createCanvas(400, 400);
}

var count = 0;

function draw() {
  background(250);
  rectMode(CENTER);
  stroke(0,0,255);
  fill(0,0,255);
  count += 1;

  var box1X = 100;
  var box1Y = 100;
  var box2X = 160;
  var box2Y = 100;
  var box1R = count;
  var box2R = -60-count;
  var box1W = 50;
  var box1H = 50;
  var box2W = 50;
  var box2H = 50;

  translate(box1X, box1Y);
  rotate(radians(box1R));
  rect(0, 0, box1W, box1H);
  rotate(radians(-box1R));
  translate(-box1X, -box1Y);

  translate(box2X, box2Y);
  rotate(radians(box2R));
  rect(0, 0, box2W, box2H);
  rotate(radians(-box2R));
  translate(-box2X, -box2Y);

  stroke(255,0,0);
  fill(255,0,0);

  var pointRotated = [];
  pointRotated.push(GetPointRotated(box1X, box1Y, box1R, -box1W/2, box1H/2));  // Dot1
  pointRotated.push(GetPointRotated(box1X, box1Y, box1R, box1W/2, box1H/2));   // Dot2
  pointRotated.push(GetPointRotated(box1X, box1Y, box1R, -box1W/2, -box1H/2)); // Dot3
  pointRotated.push(GetPointRotated(box1X, box1Y, box1R, box1W/2, -box1H/2));  // Dot4
  pointRotated.push(createVector(box1X, box1Y)); // Dot5

  for (var i=0;i<pointRotated.length;i++){
ellipse(pointRotated[i].x,pointRotated[i].y,3,3);
  }
}

function GetPointRotated(X, Y, R, Xos, Yos){
// Xos, Yos // the coordinates of your center point of rect
// R      // the angle you wish to rotate

//The rotated position of this corner in world coordinates
var rotatedX = X + (Xos  * cos(radians(R))) - (Yos * sin(radians(R)))
var rotatedY = Y + (Xos  * sin(radians(R))) + (Yos * cos(radians(R)))

return createVector(rotatedX, rotatedY)
}
```

```
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.3.3/p5.min.js"></script>
```
> 2 votes

# Answer
Possibly, there is some optimizations available by dividing the problem into two:

* compute the center of the top and the bottom side i. e., center + the rotated height/2.
* compute the corners relative to these center points using the rotated width/2
* Compute the actual sine and cosine once and for all.

Code below, here the rectangle is called ruler. ruler.x, ruler,y is the rectangle center.

```
/** Middle point on rulers's top side. */
function getRulerTopMiddle(cos, sin) {
    return {
        x : ruler.x + sin * ruler.height/2,
        y : ruler.y - cos * ruler.height/2
    }
 }

/** Middle point on rulers's bottom side. */
function getRulerBottomMiddle(cos, sin) {
    return {
        x : ruler.x - sin * ruler.height/2,
        y : ruler.y + cos * ruler.height/2
    }
 }

/** Update ruler's four corner coordinates. */
function getRulerCorners() {
    const sin = Math.sin(ruler.angle);
    const cos = Math.cos(ruler.angle);
    const topMiddle = getRulerTopMiddle(cos, sin);
    const bottomMiddle = getRulerBottomMiddle(cos, sin);

    ruler.nw = {
        x: topMiddle.x - (cos * ruler.width/2),
        y: topMiddle.y - (sin * ruler.width/2)
    }
    ruler.ne = {
        x: topMiddle.x + (cos * ruler.width/2),
        y: topMiddle.y + (sin * ruler.width/2)
    }
    ruler.sw = {
        x: bottomMiddle.x - (cos * ruler.width/2),
        y: bottomMiddle.y - (sin * ruler.width/2)
    }
    ruler.se = {
        x: bottomMiddle.x + (cos * ruler.width/2),
        y: bottomMiddle.y + (sin * ruler.width/2)
    }
}

```
> 1 votes

# Answer
Refactoring the code above gives a cleaned up form which also highlights the simple fact that each corner is basically `center + height/2 + width/2`, with signs as appropriate for each corner. This also holds if you treat `height/2` and `width/2` as rotated vectors.

Trusting the interpreter to inline the helpers, this should be pretty effective, should we try to benchmark this.

```
function addPoints(p1, p2) {
    return { x: p1.x + p2.x, y: p1.y + p2.y }
}

function subPoints(p1, p2 ) {
    return { x: p1.x - p2.x, y: p1.y - p2.y }
}

function multPoints(p1, p2 ) {
    return { x: p1.x * p2.x, y: p1.y * p2.y }
}

function getRulerCorners() {
    const sin = Math.sin(ruler.angle);
    const cos = Math.cos(ruler.angle);
    const height = { x: sin * ruler.height/2, y: cos * ruler.height/2 };
    const heightUp = addPoints(ruler, multPoints({x: 1, y :-1}, height));
    const heightDown = addPoints(ruler, multPoints({x: -1, y: 1}, height));
    const width = { x: cos * ruler.width/2, y: sin * ruler.width/2 };
    ruler.nw = subPoints(heightUp, width);
    ruler.ne = addPoints(heightUp, width );
    ruler.sw = subPoints(heightDown, width);
    ruler.se = addPoints(heightDown, width);
}

```
> 1 votes

# Answer
See the Wikipedia article on rotation. The essence is this:

(1) If *c* is the center point, then the corners are *c* \+ (*L*/2,*W*/2), +/- etc., where *L* and *W* are the length & width of the rectangle.

(2) Translate the rectangle so that center *c* is at the origin, by subtracting *c* from all four corners.

(3) Rotate the rectangle by 40 deg via the trig formulas cited.

(4) Translate back by adding *c* to each coordinate.
> 0 votes

# Answer
A little late, but here's a compact function I've used. It calculates the top and left points, then just flips them for the opposite corners.

```
rotatedRect(float x, float y, float halfWidth, float halfHeight, float angle)
{
    float c = cos(angle);
    float s = sin(angle);
    float r1x = -halfWidth * c - halfHeight * s;
    float r1y = -halfWidth * s + halfHeight * c;
    float r2x =  halfWidth * c - halfHeight * s;
    float r2y =  halfWidth * s + halfHeight * c;

    // Returns four points in clockwise order starting from the top left.
    return
        (x + r1x, y + r1y),
        (x + r2x, y + r2y),
        (x - r1x, y - r1y),
        (x - r2x, y - r2y);
}

```
> 0 votes

# Answer
Old post, but here is another way to do it:

```
public static Point[] GetRotatedCorners(Rectangle rectangleToRotate, float angle)
{

    // Calculate the center of rectangle.
    Point center = new Point(rectangleToRotate.Left + (rectangleToRotate.Left + rectangleToRotate.Right) / 2, rectangleToRotate.Top + (rectangleToRotate.Top + rectangleToRotate.Bottom) / 2);

    Matrix m = new Matrix();
    // Rotate the center.
    m.RotateAt(360.0f - angle, center);

    // Create an array with rectangle's corners, starting with top-left corner and going clock-wise.
    Point[] corners = new Point[]
        {
            new Point(rectangleToRotate.Left, rectangleToRotate.Top), // Top-left corner.
            new Point(rectangleToRotate.Right, rectangleToRotate.Top),    // Top-right corner.
            new Point(rectangleToRotate.Right, rectangleToRotate.Bottom), // Bottom-right corner.
            new Point(rectangleToRotate.Left, rectangleToRotate.Bottom),  // Botton-left corner
        };

    // Now apply the matrix to every corner of the rectangle.
    m.TransformPoints(corners);

    // Return the corners of rectangle rotated by the provided angle.
    return corners;
}

```

Hope it helps!
> 0 votes

---
Tags: 2d, rotation, grid, computational-geometry
---


# Question
Title: Why doesn't my pygame window close on MacOS?
I am trying to create a window and then close the window. Everything runs smoothly until I click the red X. When I click it, the window doesn't close and all that happens is that the colourful red beach ball thing shows up whenever I hover my mouse over the Pygame window and the window just does not respond.

It seems like the `pygame.quit()` or `pygame.display.quit()` functions do not work for some reason.

```
import pygame
pygame.init()
Window=pygame.display.set_mode((250, 250))
run=True
while run:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False
pygame.quit()
pygame.display.quit()

```

# Answer
> -1 votes
This is the correct code:

```
from pygame.locals import *

import sys,pygame

screen=pygame.display.set_mode((200, 100))

pygame.display.set_caption("hello")

while(True):

   for event in pygame.event.get():

        if event.type==QUIT:

            pygame.quit()

            sys.exit()

```

# Answer
> -2 votes
Well instead of declaring run as variable you can just do it like this:

```
from pygame.locals import *
import sys

```

`enter code here`

```
while 1:
 for event in pygame.event.get()
  if event.type == QUIT:
   pygame.quit();sys.exit()

```

---
Tags: python, pygame, macos
---


title: How to detect a pinch in Unity?

text:
# Question
Title: How to detect a pinch in Unity?
How do I detect a pinch motion on Unity for an android or Iphone? I need to also know whether the player pinches a certain character or not. How do i do that?

# Answer
in videogames most of the time you have to look for some math models for events or interactions you see.

pinch: only 2 active touch on the screen with distance more than a threshold if their distance is less than a threshold in any amount of time, a pinch has happened.

there are lots of plugins for gesture detection in asset store. just look them or implement it on your own of you like the problem. this a sample code for touch states on screen.

```
void Update ()
{
    int activeTouches = Input.touchCount;

    if (activeTouches > 0) {
        print (activeTouches + " touch(es) detected");

        for (int i = 0; i < activeTouches; i++) {
            Touch touch = Input.GetTouch (i);

            print ("Touch index " + touch.fingerId + " detected at position " + touch.position);

            switch (touch.phase) {
            case TouchPhase.Began:
                print ("User did touch the screen");
                break;
            case TouchPhase.Moved:
                print ("User dragging or moving his finger");
                break;
            case TouchPhase.Ended:
                print ("User did lift up his finger");
                break;
            }
        }
    }
}

```
> 2 votes

---
Tags: unity, iphone
---


# Question
Title: How to store ever-expanding maps with top-bottom, left-right hierarchy?
I'm writing a game that will largely take place on only a screen-worth of hexagons, but which will require map to expand in every direction. Also the way I want to display those hexagons requires that I have to be able to iterate over them in order from top to bottom, left to right.

I have already written coordinate system, which can represent coords as 2d (axial) or 3d (cube). The system regards (0, 0) as the center hex, so it means I need to store negative coords as well.

What I don't have is data structure that fufills my needs.

I'm thinking about writing a data structure myself, which will consist of 4 two-dimensional vectors (each for one quadrant of the map in regards to positive/negative) that would be able to get hexes in order I want, but this solution (using 4 vectors) seems unintuitive and long to write.

So is there a simpler, possibly already implemented, way?

# Answer
There are several options. For example:

* An `std::map` which maps coordinate pairs to tiles
* An adjacency graph (each tile has pointers to its neighbors - pretty useful for pathfinding or other applications where you need to navigate from tile to tile)
* A two-dimensional tree (allows you to quickly obtain a rectangular area of your map - useful for rendering or obtaining the local surrounding of an entity)

But all these methods have a drawback: While they grow, they allocate memory for new tiles as they need. That means that your tile data will be spread wildly across your RAM. This is bad for CPU caching, which might result in bad performance. (not as bad, though as using growing `std::vector`s, which will from time to time copy the whole content to a different memory location when they grow)

When your game world is very large, then it might be useful to divide it into fixed-size chunks. Fixed size means that each chunk can be easily represented as a fixed length array, which is great for memory locality. The chunks can then be connected through one of the options above.

Another option could be to allocate tile data in bulk and then put that data into the data structures described above as needed.
> 1 votes

# Answer
Start with a 2d array of tile. If they are all displayed on screen, there should not be too many tiles.

Each of your tile hold lot of data? Split data by concern and create one 2d array per concern. For example with a sim city like game path finding array will hold data about terrain surface, electricity availability could be another array... It all depends on how your algorithm access the data. If you just need one kind of data for one process, then give it his own view. This will even allow for efficient multithreading.

You have a hell lot of data? Split in squares. Maybe octree could help.

Need to apply same function on each tile? Just process as a 1d array.

But clearly if your tiles are on screen you should not have more than thousand, then any data design will work.
> 0 votes

---
Tags: c++
---


title: Accessing strings based on score

text:
# Question
Title: Accessing strings based on score
I have strings named like this:

```
list_1 = {"a", "b", "c"};
list_2 = {"v", "t", "d"};
list_3 = {"e", "a", "b"};
..
list_100 = {"g", "q", "z"};

```

and I have a variable:

```
int counter;

```

and I have `string[] myList;` which I define as below:

```
if (counter==1){
   myList = list_1;
}
else if (counter==2){
   myList = list_2;
}
else if (counter==3){
   myList = list_3;
}
...

else {
    myList = list_100;
}

```

Is there a way to shorten this code, so that `if score == i`, then I can assign `myList = list_i`?

ty so much!

# Answer
This looks like you want an array of arrays, also called a jagged array (since each row could have its own length):

```
string[][] allLists = new string[][]{
   new string[]{"a", "b", "c"},
   new string[]{"d", "e", "f"},
   ...
};

string[] myList = allLists[counter - 1];

```

Or you could do it with a two-dimensional array,

```
string[,] table = new string[,]{
  {"a", "b", "c"},
  {"d", "e", "f"},
  ...
}

```

And then replace any access of `myList[i]` with `table[counter - 1, i]` to index both your desired row and column.

This is very beginner C#, so you might want to work through some more introductory tutorials for the language to get familiar with these fundamentals.
> 2 votes

# Answer
You could use a List\<T\> for that (not sure about the exact syntax in c#):

```
List<string[]> lists = new List<string[]>();
lists.Add( new string[]{"a", "b", "c"});
lists.Add( new string[]{"v", "t", "d"} );
lists.Add( new string[]{"e", "a", "b"} );
..
lists.Add( new string[]{"g", "q", "z"} );

```

then

```
string[] myList;
if ( counter >= 1 && counter <= lists.Count )
    myList = lists[counter - 1];
else
    myList = lists[lists.Count - 1]

```

---

You could also achieve this with a Dictionary\<TKey,TValue\> (again, not sure about the exact syntax in c#):

```
Dictionary<int, string[]> scoresTexts = new Dictionary<int, string[]>();

scoresTexts.Add( 1, new string[]{"a", "b", "c"});
scoresTexts.Add( 2, new string[]{"v", "t", "d"} );
scoresTexts.Add( 3, new string[]{"e", "a", "b"} );
..
scoresTexts.Add( 100, new string[]{"g", "q", "z"} );

```

then:

```
string[] myList;
if (!scoresTexts.TryGetValue(score, out myList))
    myList = scoresTexts[100];

```

---

In any case, I think DMGregory's answer suggests approaches that are more efficient than those proposed here.
> 0 votes

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


# Question
Title: Could use some help figuring out bouncy physics material in this PhotonEngine game
So I'm trying to prototype a primitive 1v1 fighting game where the goal is to push the opponent off of the platform rather than actually fight. This is working great in a local multiplayer setup using a physics material on the "belly" of the Rigidbody2d players (the circle collider gameobject nested inside of the square gameobject has the bouncy material).

But I'm toying with the idea of making it a network game and it seems the physics material doesn't get communicated too well over the Photon Realtime connections?

Here is a video showing how it seems like sometimes the position is updated but sometimes a player runs into another player and its like a brick wall:

https://i.stack.imgur.com/cXYrN.jpg

Any ideas of what to try or if this is even possible?

A bit about how things are currently setup: Each player object has the nested collider with a high bounciness material on it. Each player moves via the Rigidbody2D component via

```
.AddForce(direction * Speed);

```

I have a `Photon View` component on the player prefab and a `Photon Rigibody 2D View` component that is checked to Synchronize Velocity and Angular Velocity, as well as a `Photon Transform View` component synchronizing Position. Both the transform view and Rigidbody2dView are Observed Components in the Photon View.

I also found a script someone posted where they were manually sending the position/velocity data via `OnPhotonSerializeView()` I've tried adding that script and making that observable as well, but no luck, but it looks something like this:

```
 public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
        {
            if (stream.IsWriting)
            {
                //We own this player: send the others our data
                stream.SendNext(transform.position);
                stream.SendNext(transform.rotation);
                stream.SendNext(r.velocity);
                stream.SendNext(r.angularVelocity);
            }
            else
            {
                //Network player, receive data
                latestPos = (Vector3)stream.ReceiveNext();
                latestRot = (Quaternion)stream.ReceiveNext();
                velocity = (Vector2)stream.ReceiveNext();
                angularVelocity = (float)stream.ReceiveNext();

                valuesReceived = true;
            }
        }

        // Update is called once per frame
        void Update()
        {
            if (!photonView.IsMine && valuesReceived)
            {
                //Update Object position and Rigidbody parameters
                transform.position = Vector3.Lerp(transform.position, latestPos, Time.deltaTime * 5);
                transform.rotation = Quaternion.Lerp(transform.rotation, latestRot, Time.deltaTime * 5);
                r.velocity = velocity;
                r.angularVelocity = angularVelocity;
            }
        }

```

# Answer
> 1 votes
I would try to assume that the reason for this is that the new coordinates of the second player's movement are transferred from the master to the client a little bit later than the player on the client actually collides master's player on his side. The possible solution to the problem depends on many factors and may be different. In my case, I divided the objects into 2 parts: the Visual part and the Collider. The Collider of the players on the master is always a little ahead of its Visible part to make a collision and send new coordinates to the client as soon as possible (but it shouldn't be too large to be noticeable to the player eyes). It will take some work to adjust it properly: to split objects into 2 parts (I did it programmatically) and work with it in your custom `OnPhotonSerializeView` where you should move your Colliders faster than your Visual part (which should be moved smoothly).

---
Tags: unity, 2d, physics, photon
---


# Question
Title: How to encode a save game / game state as a string?
I'm building an HTML game. For this game I want to implement a save-feature that should work like in some already existing games:

The user can chose `export`, this will create a string, representing the game state (I guess). This string can be pasted into an `import` input and will load the save game.

I thought about storing the state in a JSON, minifying it, stringifying and encoding it in Base64. But I don't think this is a good idea, users could easily cheat in this game by decoding the string, changing whatever they want, encoding it again and loading this string.

I already tried generating save files in games with this feature and decoding them in Base64 which didn't work, so I assume they use a different encoding.

How can I encode the JSON like this?

# Answer
> 1 votes
**If you want to be sure they won't misuse save data don't give it to them in any form :)**

You may give them some key to save stored on for example firebase or playfab that they can recover by entering it or just create authentication mechanism that will connect them to all their data saved in cloud.

**If you don't really care just give them that JSON.**

If someone will want to decode it he will just find your part of code that decodes it on frontend. You may want to make it a little bit harder for them by hiding decoding mechanism on server but that just turns it into more fun for hacking.

---
Tags: javascript, savegame, json
---


# Question
Title: GLSL shader algorithm to render a sprite map with a single draw call (on a single sprite mesh)
I'm trying to render a tile map world on a single sprite mesh (instead of one sprite per tile.) This significantly reduces the array vertex bus labor for extremely large worlds:

In order to do this, you **pass two textures to the shader**: the sprite sheet itself, and a texture containing tile IDs.

Sprite map (I know some tiles repeat but ignore that, this could be any spritesheet):

**Below:** Entire tile world represented by a 128 x 128 texture map, where each RGB value holds actual Tile ID for that location on the map. There are more efficient ways to represent the actual tile ID. Here, for the sake of simplicity, it is stored in the R component.

Putting it all together:

The right-most square is the screen output. On the image I just repeat texture... but what should actually happen is a tile world rendered from tiles on the sprite sheet.

I wrote the shader that is supposed to do this, but I'm stuck. I can render the sprite sheet itself, and even scale it on the sprite mesh, but I can't seem to get the tile IDs render at the proper location, matching the tile world data.

I do think I am really close and there are just a couple of modification needed to the shader -- so what am I doing wrong?

The following shader is what I have so far:

**tilemap.vs**

```
#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 color;
layout (location = 2) in vec2 texCoord;

out vec2 TexCoord;

uniform sampler2D ourTexture;
uniform sampler2D ourTilemapDataTexture;

uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;

void main()
{
    gl_Position = Projection * View * Model * vec4(position, 1.0);

    TexCoord = texCoord;
}

```

**tilemap.frag**

```
#version 330 core

in vec2 TexCoord;

uniform sampler2D ourTexture;
uniform sampler2D ourTilemapDataTexture;

void main() {

    // size of the tile world (128 by 128 tiles on one sprite)
    float cols = 128.0f;
    float rows = 128.0f;

    float tilesPerSide = 8.0f;

    // figure out which tile we´re in from the 3D coordinates
    vec2 tile = vec2(floor(TexCoord.x)/cols, floor(TexCoord.y)/rows);

    // get tile´s texture ID from tile ID texture map
    float tex = texture2D(ourTilemapDataTexture, tile).r;

    vec2 UV = vec2(tex + fract(TexCoord.x), fract(TexCoord.y));

    color = texture2D(ourTexture, UV);

    if (color.a == 0) // remove transparent areas
        discard;
}

```

PS: I looked at every tutorial I could find on Google, and tried to re-implement it in my shader to no effect. This is as far as I got so far.

Can anyone point out what I'm doing wrong?

**Update #1** -- I was able to get position sampling to work.

I painted a bit on the world map:

It's not perfect but definitely a step forward:

Adjustments made to the fragment shader:

```
float cols = 128.0f;
float rows = 128.0f;

float tex = texture2D(ourTilemapDataTexture, TexCoord).r;
float tey = texture2D(ourTilemapDataTexture, TexCoord).g;

vec2 UV = vec2( (TexCoord.x * (cols) / (tex * 32.0f)),
                (TexCoord.y * (rows) / (tey * 32.0f)) );

color = texture2D(ourTexture, UV);

```

Sure it's not 100% correct but at least map indexing works now :)

# Answer
There is no need to have a secondary texture.

Instead, give your quad different texture coordinates.

For the sake of simplicity look at the following image:

Now, we know that our "atlas" texture has 2x2 tiles. So, we give our quad texture coordinates (0,0) to (0.5,0.5), which is, each coordinate axis is 1/number of tiles per direction.

Now when we want to draw a red tile, we send two uniforms (1,1) to the gpu program: The index of the vertical, and horizontal tile. This becomes our offset, and is computed in the vertex shader (normal vertex shader code omitted for brevity):

```
uniform vec2 offset;

void main()
{
    out.uv = uv += uv * offset; (member by member multiplication and addition)
}

```

Thus the uv minimum becomes (0.5,0.5) to (1, 1).

in the same way, to draw a yellow tile, your offset uniform would be (0,0), green would be (1,0), and black would be (0,1).

Because you are doing it in the vertex shader, the coordinates can be interpolated for each fragment using hardware, and the texture prefetch optimised for the fragment stage as normal.
> 2 votes

---
Tags: opengl, glsl
---


# Question
Title: How to move player along navmesh link's curve?
> NavMesh Link creates a navigable link between two locations that use NavMeshes.
>
> This link can be from point to point or it can span a gap, in which case the Agent uses the nearest location along the entry edge to cross the link.

I don't know why when I use navmesh link player move along horizontal plane (that I demonstrate it by red line) between gaps in navmesh link Is there a option that player jump along curve (that I demonstrate it green curve)? should I use force?

you can see player move horizontally! that isn't interesting. Offmesh Links - Unity Official Tutorials

# Answer
The navmesh links are curved only for visual fidelity.
In reality, they only store a start and end point (and some metadata).

If you want your agent to jump when encountering a link, you would need to do that yourself.
One way to do that is described in this forum post.

```
using UnityEngine;
using System.Collections;

public enum OffMeshLinkMoveMethod {
   Teleport,
   NormalSpeed,
   Parabola,
   Curve
}

[RequireComponent (typeof (NavMeshAgent))]
public class AgentLinkMover : MonoBehaviour {
   public OffMeshLinkMoveMethod method = OffMeshLinkMoveMethod.Parabola;
   public AnimationCurve curve = new AnimationCurve ();
   IEnumerator Start () {
     NavMeshAgent agent = GetComponent<NavMeshAgent> ();
     agent.autoTraverseOffMeshLink = false;
     while (true) {
       if (agent.isOnOffMeshLink) {
         if (method == OffMeshLinkMoveMethod.NormalSpeed)
           yield return StartCoroutine (NormalSpeed (agent));
         else if (method == OffMeshLinkMoveMethod.Parabola)
           yield return StartCoroutine (Parabola (agent, 2.0f, 0.5f));
         else if (method == OffMeshLinkMoveMethod.Curve)
           yield return StartCoroutine (Curve (agent, 0.5f));
         agent.CompleteOffMeshLink ();
       }
       yield return null;
     }
   }
   IEnumerator NormalSpeed (NavMeshAgent agent) {
     OffMeshLinkData data = agent.currentOffMeshLinkData;
     Vector3 endPos = data.endPos + Vector3.up*agent.baseOffset;
     while (agent.transform.position != endPos) {
       agent.transform.position = Vector3.MoveTowards (agent.transform.position, endPos, agent.speed*Time.deltaTime);
       yield return null;
     }
   }
   IEnumerator Parabola (NavMeshAgent agent, float height, float duration) {
     OffMeshLinkData data = agent.currentOffMeshLinkData;
     Vector3 startPos = agent.transform.position;
     Vector3 endPos = data.endPos + Vector3.up*agent.baseOffset;
     float normalizedTime = 0.0f;
     while (normalizedTime < 1.0f) {
       float yOffset = height * 4.0f*(normalizedTime - normalizedTime*normalizedTime);
       agent.transform.position = Vector3.Lerp (startPos, endPos, normalizedTime) + yOffset * Vector3.up;
       normalizedTime += Time.deltaTime / duration;
       yield return null;
     }
   }
   IEnumerator Curve (NavMeshAgent agent, float duration) {
     OffMeshLinkData data = agent.currentOffMeshLinkData;
     Vector3 startPos = agent.transform.position;
     Vector3 endPos = data.endPos + Vector3.up*agent.baseOffset;
     float normalizedTime = 0.0f;
     while (normalizedTime < 1.0f) {
       float yOffset = curve.Evaluate (normalizedTime);
       agent.transform.position = Vector3.Lerp (startPos, endPos, normalizedTime) + yOffset * Vector3.up;
       normalizedTime += Time.deltaTime / duration;
       yield return null;
     }
   }
}

```
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: How can I install SharpDX for my project?
Unfortunately, as an experienced developer, I can not find the download link for SharpDX's binary files on SharpDX's download page here

https://www.nuget.org/packages/SharpDX/4.2.0

I am very surprised about the high download numbers.

How do I actually download/install this?

# Answer
On the right hand side of the page is a list of actions.
On the bottom, it says "Download Package".
It prompts a download of the nuget package, which I believe is what you want.

This is the link:
https://www.nuget.org/api/v2/package/SharpDX/4.2.0

**About Nuget:**
To use a nuget package, you need a nuget package manager.
Alternatively, you can open them with a compression software (WinRar, WinZip, 7Zip, etc) and extract the files manually.

Nuget is a standard for library distribution.
The nuget package managers does the heavy lifting for you when you want to add or update external libraries.
This removes the need for manual management of those libraries, which could be quite a pain for some more complex setups.

It's integrated in the last few Visual Studio versions, otherwise you can download the manager here.
I don't have much experience with other IDE's and nuget.
> 2 votes

# Answer
I found a solution is to unzip this nuget package by simply renaming it to a zip file.
> 0 votes

---
Tags: sharpdx
---


title: Unity Component Hierarchy

text:
# Question
Title: Unity Component Hierarchy
I'm currently working on a 3D RPG game and I'm adding Interactions with objects. I have a lot of objects to interact with and I've placed them in an folder/empty object "Interactables".

Now, I want all my objects to have a SpriteRenderer Component. I'm currently adding this Component on each Interactable Object, one by one.

Is there a cleaner way of doing that, for example adding the Component to the Interactables parent empty object and cloning it to all the children ?

Thank you!

# Answer
The new Unity prefab workflow has a new feature called "prefab variants", which you can use to create prefab inheritance chains. You can create one prefab "Interactable Template", and then create multiple Interactable prefabs which are variants of that template prefab.

Each prefab variants can then:

* Override certain properties of individual components (like the Sprite used by their SpriteRenderer)
* Have additional components (like scripts which implement what happens when the player interacts with them)
* Or even have additional child game-objects.

When you change the base prefab, those changes will be automatically applied to all the prefab variants, unless they have overridden that specific property. So if you add a SpriteRenderer component to the template then all the variants will also have a SpriteRenderer.

Unfortunately it is difficult to change to this architecture retroactively when you already created a bunch of similar but technically independent prefabs. So if you want to convert all the prefabs you already made to make use this new technique, you might have a bit of work ahead of you. But if you expect to make more changes to all your interactables in the future, then this might be a worthy investment of your time.
> 1 votes

# Answer
Unity allows you to add components to multiple objects at the same time with multiple selection. If they are in the scene and all of them are under the same empty parent object, you need to click parent and the last child object of the parent object while holding down the Shift to select all of the interactable game objects. While all of them are selected, you can add any component to them with the help of Inspector.
> 0 votes

---
Tags: unity
---


# Question
Title: How to update the value of all owners of shared_ptr?
I’m writing a render, there is a class that shaders should store, something like a shader manager. These shaders are stored as

```
std :: map <std :: string, std :: shared_ptr <BaseShader>> cache;

```

BaseShader is an abstract class (there are virtual methods).

Other classes want to own shaders, and request them accordingly by name. That is, they each have a copy of the smart pointer. After the change, the shaders need to be rebooted from the disk. Accordingly, new is done and written by name in the cache, the problem is that clients do not see this change. How to make sure that the reset for the smart pointer is not made, and the updated object was copied to the same address that it stores?

# Answer
Update Object in place.

```
*cache["foo"] = Object(stuff);

```

Or add a method that will reload the entire object.

```
cache["foo"]->reload(stuff);

```
> 2 votes

# Answer
> How to make sure that the reset for the smart pointer is not made, and the updated object was copied to the same address that it stores?

I have not done this before, but you could allocate a chunk of memory yourself with `malloc`, and call the constructor yourself with an address that you now own (in the chunk allocated with malloc).

That could work if your object is a pod an never change in size. It can get very messy and complicated if your object has references to other objects (string, vector, etc.).

I would suggest you explore other strategies:

One option is that your cache returns `weak_ptr`s instead of `shared_ptr`s. Once the object is reloaded, the weak\_ptr will be 'invalidated'. When this happens, when you `weak_ptr.lock()` and the returned shared\_ptr is null, you know you need to re-fetch the object from the cache.

Another option is to make an event system where the owners of the objects reference are notified that the model has been reloaded in the cache and they should request a new version of it.

You could also simply request the cache via a handle every time you need the model, so you always have the most up-to-date version. (You use a string for now, you could hash that and turn it into an int to make it faster.)
> 0 votes

---
Tags: c++, oop, resource-management, asset-management
---


# Question
Title: Collision library for bullet hell in Python
I am making a bullet hell game in Python and am looking for a suitable collision library, taking the following into consideration:

* The library should do 2D polygon collision.
* It should be very fast. As a bullet hell game, I expect to do collision checks between hundreds, likely thousands of objects every frame at a consistent 60fps.
* Good documentation
* Permissive license (like MIT, not GPL)

I am also considering writing my own library in C/C++ and wrapping with python ctypes in the event that no such library exists, though I do not have experience with collision detection algorithms, so I am not sure if this would be more trouble than it's worth.

Could someone provide some guidance on this matter?

# Answer
> 1 votes
Given the simplicity of typical projectiles in "Bullet Hell"-type games, it'd be pretty simple to roll your own collision detection code.

Collision detection would be a simple line segment to polygon intersection (basic linear algebra). Iterate through all your projectiles and game entities, and you're done.

If after that point, performance needs to be increased, then check AABB collision prior to each polygon intersection.

If after that, performance still needs a boost, then construct a quad-tree out of your entities and projectiles to do "macro"-AABB checks prior to the checks above.

Also, if your implementation/hardware is good, I wouldn't be surprised if doing it in Python turns out fast enough to achieve your needs.

# Answer
> 1 votes
If you are willing to work exclusively with circles. bullets = circles ships collision detection boundary = circles

Tip: Your art can look a little different than the collision boundary.

Then I suspect a basic radius test would be simple and have exceptional performance.

```
A²+B²=C²
A²=(ship.x-bullet.x)²
B²=(ship.y-bullet.y)²
C²=distance

```

if distance is less than ship.radius, then collision is true.

Performance tip: do the math in a way that avoids square root.

Note: this is sudo code.

```
deltaX = ship.x - bullet.x
deltaY = ship.y - bullet.y
isHit = ship.radiusSquared <= (deltaX*deltaX)+(deltaY*deltaY)

```

with a little extra effort you can also test collision with an outer rectangle, (edge of screen, or walls of a billiards table)

Caution: this does not detect "tunneling" which occurs when fast moving objects move through objects due to their speed being greater than the area they would have collided with. This is something Box2D handles with bullet=true, but tunneling detection can be performance heavy. I think the ninja game "N" documented some performance tips for tunneling detection, if you roll your own basic physics engine those are worth looking into.

Box2d is my favorite **shape based** physics engine.

For those making something more like Worms with destructible terrain, you may find it easier to work with a **pixel based** physics engine instead.

# Answer
> 0 votes
I love box2D as much as the next indie developer, but in this case its way overkill.

Try rabbyt its not maintained much anymore but its still pretty sweet. Its super fast also, it is however an entire 2D engine but can be used in pygame and pyglet. It takes advantage of hardware acceleration, and can do some pretty intense collision checks.

Pygame has a decent collision library, however having used pygame in the past and recently discovering much better 2D libraries, I've grown to hate it. As for pyglet, its pretty cool but its not a game engine just media engine sort of like SDL(but not SDL based).

I'd say check rabbyt out, theres a google group for support.

EDIT: Rabbyt IS indeed MIT licensed.

---
Tags: collision-detection, python
---


# Question
Title: How to add a flash light to a particle explosion
I've an explosion effect using particle system.

Explosion occur on air, so I want to add a "flash" light effect when explosion occur (that light sky and terrain ).

Can you suggest me best way to obtain ?

Thanks

# Answer
I've just added a point light with a script that increase (then decrease) :

* intensity
* range

in a fixed span time .

This is my script:

```
public class gsFlashLightExplosion : MonoBehaviour

```

{ \[SerializeField\] int LightStartRange;

```
[SerializeField] int LightEndRange;

[SerializeField] float LightStartIntensity;

[SerializeField] float LightEndIntensity;

[SerializeField] float Speed;

private bool blnRun=true;

private Light light;

// Start is called before the first frame update
void Start()
{
    light=GetComponent<Light>();
    light.range = LightStartRange;
    light.intensity = LightStartIntensity;
}

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

    if(LightEndRange>light.range)
        light.range = (int)(light.range + (light.range * Speed / 100));
    else
        light.range = (int)(light.range - (light.range * Speed / 100));

    if (LightEndIntensity > light.intensity)
        light.intensity = light.intensity + (light.intensity * Speed / 100);
    else
        light.intensity = light.intensity - (light.intensity * Speed / 100);

}

```

}
> 0 votes

---
Tags: unity, lighting, particles
---


# Question
Title: How do I prevent players from flying too low in an infinite sky?
Let's say I have a game that allows the player completely free, open world flight, and the world itself is a bunch of floating islands. This creates some problems with flying too low, such as reaching the fake cloud "floor", being stuck without being able to get back up, and so on. How can I prevent this without introducing some jarring invisible "floor" that repels the player if he slams into it?

I thought about having some sort of in-universe wind near the "bottom" that might decelerate the player and then push him/her back up, but I'd like to hear some more ideas that might be less artificial.

# Answer
> 3 votes
The wind that pushes the player back into the navigation volume is a very good solution. Bespoke games like Sky and Journey by Thatgamecompany are examples where it is used nicely. Alternatively to that, you could have the player being *caught* by some flying something (like an eagle) to be taken back on track or you could have a lightning suddenly strike and teleport the player. Depending on your game’s context it might even make sense to have an entity pop out of the clouds and smack the player with an uppercut on the snout with a strong kick back. In most game styles I would prefer the wind but the context is what opens up possibilities.

# Answer
> 1 votes
You could take the Super Mario 64 aproach where if the player hasn’t collected enough stars he can ascend a stairway forever without making progress. In your case the player could fly down for as long as he wants and still remain at the same height so when he finally decides to fly up it is a short way to the island’s height.

# Answer
> 0 votes
In Star Fox 64 your ship would just stop moving on the Y axis when it was at the top or bottom of the playable space. I know you said this would appear to be "jarring", but there is a way to hide it.

When your player is approaching the boundary, the skybox or whatever backdrop that lies beyond is probably significantly far away (or static) that you no longer have a reference point in view to see if you're still moving on the Y axis. As long as there are no nearby objects from the level in sight, you can maintain the illusion that the player is still flying up or down. (Make sure that cloud floor appears far away from the boundary!) You can also reduce the FOV so that you can't see as many objects beside your character. Pull the camera back and reduce FOV (zoom in) and you will find that this trick is easier to pull off while the player is climbing or diving (looking straight up or down).

Also, if your game involves airplanes, you can constrain the min and max pitch of the plane based on the absolute Y position so that it is always flying level at the min and max Y values. Basically start lerping the (min or max) pitch between the player's input and 0° while in some region close to the Y boundary. That way there is a gradual "swoop" to level out the character before they go out of bounds, which won't appear jarring when combined with a hard limit on the Y position.

---
Tags: movement, game-mechanics
---


# Question
Title: Efficiently pathfinding many flocking enemies around obstacles
I'm working on trying to improve the pathfinding for my game's enemies. Right now, they basically just constantly move towards the player's exact position by calculating the angle between themselves and the players and moving in that direction. I also have a flocking algorithm which prevents the enemies from stacking on top of each other, so they will form up into groups rather than clip through each other.

However, now that I've added a tile-based map, I need the enemies to also be able to path around obstacles and walls for example. I initially tried adding a separation value to "non-walkable" tiles so that the flocking algorithm would consider the walls and obstacles as objects to move away from. I have yet to work out whether or not this is feasible because my initial test showed the enemies hitting an invisible "wall" where there are no non-walkable tiles, yet for some reason, they hit it and start spazzing out.

I was wondering if it might be too performance heavy to calculate a path to the player using A\* and then use the flocking algorithm to prevent clumping. Originally my game was going to be a wave-based shooter, but I've decided instead to make it level-based in the vein of Hotline Miami, so it's likely I'll have fewer enemies, with the occasional horde, and just make them stronger.

Is this a viable solution? I'm using Java with Slick2D as my game engine. Or is there a better solution / algorithm that tackles both these problems?

# Answer
This sounds like a use case for Flow Fields.

In this technique, you do a single pathfinding query outward from your player object(s), marking each cell you encounter with the cell you reached it from.

If all your tiles/edges have equal traversal cost, then you can use a simple breadth-first search for this. Otherwise, Dijkstra's algorithm (like A\* with no goal/heuristic) works.

This creates a flow field: a lookup table that associates each cell with the next step toward the closest player object from that position.

Now your enemies can each look up their current position in the flow field to find the next step in their shortest obstacle-avoiding path to the closest player object, without each doing their own pathfinding query.

This scales better and better the more enemies you have in your flock. For a single enemy, it's more expensive than A\* because it searches the whole map (though you can early-out once you've reached all pathfinding agents). But as you add more enemies, they get to share more and more of the pathfinding cost by computing shared path segments once rather than over and over. You also gain an edge from the fact that BFS/Dijkdtra's are simpler than A\*, and typically cheaper to evaluate per cell inspected.

Exactly where the break-even point hits, from individual A\* being cheaper, to A\* with memoization being cheaper (where you re-use some of the results for a past pathfinding query to speed up the next one), to flow fields being cheaper, will depend on your implementation, the number of agents, and the size of your map. But if you ever plan a big swarm of enemies approaching from multiple directions in a confined area, one flow field will almost certainly be cheaper than iterated A\*.

As an extreme example, you can see a video here with 20 000 agents all simultaneously pathfinding on a reasonably small grid.
> 50 votes

# Answer
A\* is not performance heavy. I would approach this situation by varying the algorithms. Do A\* from time to time and in between check whether the next step is free to step onto or you need evasion.

For example, track the players distance from the A\* target location, if it's above a threshold recalculate a\* and then just do update movements. Most games use a combination of way points, e.g. a simplified grid for path finding and a logic that handles the movement between waypoints with evasion steering algorithms using raycasts. The agents try to run to a distant waypoint by maneuvering around obstacles in their proximity is the best approach in my opinion.

It's best to work with finite state machines here and read the book "Programming Game AI By Example" by Mat Buckland. The book offers proven techniques for your problem and details the math required. Source code from the book is available on the web; the book is in C++ but some translations (including Java) are available.
> 8 votes

# Answer
Not only is it feasible, I believe it was done in a commercial game in the 90s - BattleZone (1998).

That game had 3D units with free non-tile-based movement, and tile-based base construction.

This is how it seemed to work:

First, A\* or something similar (likely a variation of A\* with strict limits on how long a path it can find, so it never takes too many resources to run but doesn't always find a path all the way to the destination) would be used to find a path for a hovertank to get to its destination without getting stuck in tile-based obstacles.

Then the tank would fly around untiled space as if it was attracted to the centre of a nearby tile in its path, and repulsed by obstacles, other nearby tanks, etc.
> 4 votes

---
Tags: java, algorithm, ai, path-finding
---


title: How can I control ads frequency?

text:
# Question
Title: How can I control ads frequency?
This question was already asked a while ago, and I wanted to check the present situation:

* Can I control ads frequency from the **dashboard**? (e.g. frequency capping in Admob)
* Can I control ads frequency through **Unity IAP API**?
* If not, does that mean that I need to implement all that **"frequency control"** functionality manually?

# Answer
yes. admob and unity and other qd services have builtin ad frequency control for any user but they only return no add error when there is no ad. but you have to control them in client side or maybe you can have mid server that manages connection of your clients with adverisement server if you are afraid oc heating or ad overuse
> 0 votes

---
Tags: unity, unity-ads
---


# Question
Title: Additional Entity ID for networking instead of general EID?
http://t-machine.org/index.php/2015/06/09/entity-ids-how-big-using-uuids-or-not-why-etc/

I see this one article that proposes specific IDs just for the networking side of the game. If you are already employing IDs for your entities, is there any benefit on adding IDs just for client-server communication instead of reusing the original local ID (one that you know is not subject to collisions)?

# Answer
An UUID takes up 128 bits.

Your own ID can be as small as `ceil(log_2(n))` bits; where n is the number of entities you want to distinguish between.

Getting the entity from the UUID requires a hashmap. A cleverly constructed ID system will let you simply index into an array instead, which is slightly faster.

You can also embed some type information in the ID usually by assigning ranges to each type. This lets you avoid a downcast/typecheck in the network code because you can have separate containers for each type.
> 1 votes

---
Tags: networking, entity-component
---


# Question
Title: Center Perspective Camera on Coordinates
I've got a `PerspectiveCamera` and set of coordinates (x,y,z).

How could I pan the camera to make these coordinates at the center of the screen?

# Answer
> 1 votes
The idea is to project the target point onto the plane passing through the camera spanned by the camera's up and right vector, and translate the camera to this point.

You can do this in one line with fairly simple math. Pseudocode:

```
cameraPosition = targetPosition + cameraForward*dot(cameraPosition - targetPosition, cameraForward)

```

where `cameraForward` is the normalized camera's direction, `targetPosition` is the point you want to be at the center of view and `cameraPosition` is the camera's position. All are in the same coordinate space.

# Answer
> 0 votes
You can just use `camera.lookAt(Vector3)`:

```
perspectiveCamera.lookAt(coordinates);

```

# Answer
> 0 votes
Here is how I would solve this problem.

**Step explanation:**

1. Calculate nearest point on camera forward ray for target position
*You want the nearest point, because this point lies on the flat movement plane.<br>As long as you move along this movement plane, your vertical distance won't change.*
2. Find distance vector (nearest point - camera position)
*The distance vector points from the camera to the nearest point.*
3. Place camera at (target position - distance vector)
*You need to mirror the distance vector, as you want the camera position relative to the target.*

**Nearest point:**

For the nearest point to the ray, you can use the Ray class and the closestPointToPoint method.
Just create a ray going from the camera position allong the camera forward vector.

Sorry, no code, I don't write three.js.
But I think it isn't to hard to code it yourself.

---
Tags: three.js
---


title: What to do with collision detection?

text:
# Question
Title: What to do with collision detection?
I am able to get collision detection (CD) into my game but... what do I do with it? Do I push the player back to the last location? Something else?

I am programming the game in C++ using the Irrlicht 3D rendering engine, everything is blocks, because the game is a voxel game so there is no need to throw different techiniques of doing CD. All I can find are different methods of doing CD but nothing about what to actually do when I detect collision. The code I use is the following:

```
// ^^^ all character movement is redundant for this post but is is above this comment
std::vector<scene::ISceneNode *> objects; // A vector containing all of the different blocks

objects.push_back(block); // I add the objects in an array, for later access and easability

// after all character movement, check if player rect intersects with any block
    for(int i = 0; i < objects.size(); i++) { // go through all the block objects
        if(player->getTransformedBoundingBox().intersectsWithBox(objects[i]->getTransformedBoundingBox())) { // if they intersect, do the following
            falling = false;
            can_jump = true;
            walk = false;
            player->setPosition(last_pos); // makes the character stuck, since it always collides with floor
            break;
        } else {
            falling = true;
            can_jump = false;
            walk = true;
        }
    }

```

I have tried to create a variable BEFORE ALL MOVEMENT in a frame called `last_pos = player->getPosition();` and then if there is a collision then I do `player->setPosition(last_pos);` but the issue is that I constantly collide with the floor, therefore I never move since I always go back to last position because of the collision. So what should I do?

Edit: the way I understand it: one way to do collision detection is to get the coordinate of EVERY corner of every voxel block I have in the world and check if that corner is in between any one of the corners of my character? Is that waaaayy off or does someone has an actual tutorial / concrete code that actually deals with 3D collision and not just tutorials and theory?

Edit 2: Each block the player can collide with is exactly 10 units long. I crafted up this piece of code to check if ANY corder of ANY block is colliding with my character who is 10x20x10 (x, y, z) where y is heigh.

```
bool axisCollision(vector3df object1, vector3df object2, int axis) {

int pos1_x = object1.X;
int pos1_y = object1.Y;
int pos1_z = object1.Z;

int pos2_x = object2.X;
int pos2_y = object2.Y;
int pos2_z = object2.Z;

// x, y, z
if(pos2_x < pos1_x + 10 && pos2_x > pos1_x &&
   pos2_y < pos1_y + 20 && pos2_y > pos1_y &&
   pos2_z < pos1_z + 10 && pos2_z > pos1_z) {
    std::cout << "collision!\n";
    return false;
}

// x, y, z + 10
if(pos2_x < pos1_x + 10 && pos2_x > pos1_x &&
   pos2_y < pos1_y + 20 && pos2_y > pos1_y &&
   pos2_z + 10 < pos1_z + 10 && pos2_z + 10 > pos1_z) {
   std::cout << "collision!\n";
   return false;
}

// x, y + 10, z + 10
if(pos2_x < pos1_x + 10 && pos2_x > pos1_x &&
   pos2_y + 10 < pos1_y + 20 && pos2_y + 10 > pos1_y &&
   pos2_z + 10 < pos1_z + 10 && pos2_z + 10 > pos1_z) {
   std::cout << "collision!\n";
   return false;
}

// x, y + 10, z
if(pos2_x < pos1_x + 10 && pos2_x > pos1_x &&
   pos2_y + 10 < pos1_y + 20 && pos2_y > pos1_y &&
   pos2_z < pos1_z + 10 && pos2_z > pos1_z) {
   std::cout << "collision!\n";
   return false;
}

// x + 10, y, z
if(pos2_x + 10 < pos1_x + 10 && pos2_x + 10 > pos1_x &&
   pos2_y < pos1_y + 20 && pos2_y > pos1_y &&
   pos2_z < pos1_z + 10 && pos2_z > pos1_z) {
   std::cout << "collision!\n";
   return false;
}

// x + 10, y, z + 10
if(pos2_x + 10 < pos1_x + 10 && pos2_x + 10 > pos1_x &&
   pos2_y < pos1_y + 20 && pos2_y > pos1_y &&
   pos2_z + 10 < pos1_z + 10 && pos2_z + 10 > pos1_z) {
   std::cout << "collision!\n";
   return false;
}

// x + 10, y + 10, z
if(pos2_x + 10 < pos1_x + 10 && pos2_x + 10 > pos1_x &&
   pos2_y + 10 < pos1_y + 20 && pos2_y + 10 > pos1_y &&
   pos2_z < pos1_z + 10 && pos2_z > pos1_z) {
   std::cout << "collision!\n";
   return false;
}

// x + 10, y + 10, z + 10
if(pos2_x + 10 < pos1_x + 10 && pos2_x + 10 > pos1_x &&
   pos2_y + 10 < pos1_y + 20 && pos2_y + 10 > pos1_y &&
   pos2_z + 10 < pos1_z + 10 && pos2_z + 10 > pos1_z) {
   std::cout << "collision!\n";
   return false;

}

return true;

}

```

The function takes in the players coordination and every single coordination for each block in the world. It then checks if ANY corner of ANY block is inside the character, then it will return false, which results in the player not executing the movement. My issue with this code snippet is that... well... it never returns false! It never detects wall collision, whether I walk inside a wall or on a floor does not matter. Any ideas why?

# Answer
This problem of "I found a collision/overlap, now what do I do about it?" is called .

There are lots of different ways that games handle this, roughly in order of increasing complexity:

1. **Undo** (as you described)
Store the position before this movement integration step. If an overlap occurs, revert to this previous-good position.

This is very simple to implement, very efficient, but often feels rough in gameplay - once you get close to an obstacle, you'll tend to get stuck a small distance away, rather than moving all the way up to the surface or sliding along it. This is because a full move would overlap, so we cancel the whole thing. Worse, the exact distance at which this happens can change depending on your movement angle and where the obstacle lands in the rhythmic phase of your movement strides, creating visible inconsistencies in your gameplay.

This also gets more complicated when you have multiple moving objects that all need to avoid overlaps with each other - one could safely move into the empty space another left, detecting no overlap, but then the previous occupant could hit an overlap and get undone, creating a new overlap that wasn't present on your first collision detection pass, forcing you to re-evaluate at least some collision checks a second time.

2. **Sub-Stepping**
Instead of taking your full move all at once, divide it into steps, collision checking at each step. Move to the last non-overlapping spot. This is how Mario 64 handled Mario's movement, splitting the move into 4 so you can move 0, 25, 50, 75, or 100% of your expected movement, cutting the maximum position error proportionately.

This mitigates the more egregious problems with rewinding, but it's strictly only reducing them in degree. And it multiplies your collision-checking cost, so you might want to apply this only to the most visible objects like the player character, or collisions against static walls.

3. **Resolve Penetration / Separation**
Given a pair of overlapping colliders, compute the smallest position change that gets them to no longer overlap. This is called the minimum separation vector / minimum separation distance. It's usually easy to compute for pairs of primitives like boxes/circles/spheres/capsules... but gets more complicated with polygons/meshes, especially if they can be concave...

Once you have this vector, you can use it to resolve the overlap in two ways:

* Shift the two colliders along this vector, one positively, one negatively. You can move each away by 1/2 the distance, or move one by the full vector and the other not at all (eg. if one is static/kinematic or vastly greater in mass) or any weighting you want in between.

    The advantage of this is that you can fully resolve simple collisions in a single step. And unlike the first two approaches, it doesn't stop objects before the collision, leaving a ghost buffer between the objects - you can run right up into kissing contact with a wall, from any distance. The disadvantage is that, like with undoing, resolving one pair of overlaps could cause or worsen another pair. Some multi-way collisions aren't fully resolvable in one step this way, and can lead to unexpected jumps or jittering .
    * Apply an impulse to the bodies along this vector, so that their next movement step will move them apart. This roughly simulates elastic rebounding, and you can scale the magnitude of the impulse up or down to represent bouncier or squishier materials.

    The disadvantage of relying on impulses over shifts is that you might observe the penetration persisting for a frame or two before the objects manage to jostle their way apart. Or objects can accumulate so much velocity from these impulses that they're catapulted out of overlap at a silly-looking speed. But the advantage is that it's tolerant to complex multi-collisions that might not be fully resolvable in a single step, using only local pairwise interactions rather than needing a more complex global constraint solver tackling multi-way collisions.

Many game physics engines use these two strategies in tandem, both applying a position correction to resolve the simple collisions immediately, and impulses to create rebounds and iteratively solve more complex pile-ups over multiple frames.

One hazard to these approaches is that they don't take into account where the objects came from / how they got into this mess. If an object is moving at such great speed that in one step it passes 60% of the way through an obstacle, then the minimal vector that resolves the collision might be one that continues pushing it through the far side, contributing to "tunneling" bugs where objects seem to pass clear through solid walls. This also rears its head when walking along a flat ground made of multiple tiles with their own colliders, when you just straddle the corner of a new tile: the smallest vector to correct the overlap might be to push the player backward instead of up, making it feel like you're snagged on the corner where it should be seamless.
4. **Time of Impact**
An improvement to the method above is to take the velocities of the two bodies into account, and compute the moment within the timestep where these two objects first touched. Then we rewind them to that moment, apply any rebound impulses using the actual points/manifold of contact, and then allow them to continue from there.

This solves many cases of tunneling (as long as the object doesn't hop fully past the obstacle in one step - we have to detect an overlap in order to run this routine), stopping/rebounding an object from the same side of the obstacle it came from. And it can give more physically accurate / plausible results.

But again, this does get more complicated as you add ingredients, like rotation or more complex collider shapes. Then the math to compute this moment of contact might get much more costly or require iterative approximation. And again, when you get three bodies or more colliding, resolving them all accurately can become intractable.

Some physics engines will also let you enable continuous collision detection for select objects, where instead of jumping all objects forward and checking for overlaps at the final position, you can sweep the objects through their whole travel - like a raycast/boxcast/spherecast - and find this moment of contact as part of the collision detection phase. This can completely solve tunnelling, but it is often *much* more expensive to compute.

This is by no means an exhaustive listing - games will use strategies beyond these, or mix elements of several strategies. But this covers some of the common themes you'll see in many games, and hopefully equip you with some conceptual frameworks and search terms you can use to find deeper documentation/Q&A/tutorials to build a solution that works for you.
> 3 votes

---
Tags: c++, collision-detection, 3d, collision-resolution, irrlicht
---


# Question
Title: How to find all possible destinations, within a certain walking distance of a unit?
I have a standard 2D grid that i use for pathfinding. I already use A\* to find the path of my units when I want to move them around.

What I need to implement now is a preview of all possible destinations of the unit when it is selected.

Here is what I want to achieve.  The yellow/orange cells represent the possible destinations.

I want to make this as optimized as possible, because it can be executed on very big maps and for multiple units.

I have something in mind but I wonder if there is better approach for this.

Here is my idea:

1. Get a list of all cells that are walkable in a square around my unit. The square will be from `Unit.X - Unit.Speed` to `Unit.X + Unit.Speed` for X axis and `Unit.Y - Unit.Speed` to `Unit.Y + Unit.Speed` for Y axis.
2. For each element in this list, execute A\* search to see if it is possible to find a path.

By doing the search for only the cells that are within my unit range I should be able to do this on big maps.

Basically this is the same feature that we have in games like Heroes 3 and many other turn based games.

Screenshot:

I was also wondering when it is a good idea to execute this pathfinding logic. When you select a unit (might result a spike) or when something moves on the map to update the list of all possible destinations of all units on the map.

# Answer
You're over-thinking this. There are well-known optimal algorithms to solve it without running A\* over and over.

If the edges of your graph can have different traversal costs, then you want to run Dijkstra's algorithm (like A\* with no heuristic), ignoring neighbours beyond your total cost limit. All the nodes it visits and adds to the closed set are within your movement range.

If the edges of your graph all have the same traversal cost, then breadth-first search suffices, with a maximum hop count. Again, ignore neighbours that would take you beyond your hop count budget, and all the nodes you visited and added to the closed set are within your movement range.

Both algorithms give you the whole reachable set in a single invocation from your starting point, without needing to pick out candidate reachable tiles in advance.
> 1 votes

# Answer
In the end, a simple BFS as DMGregory recommended really did the work.

This particulate implementation uses C#, but it can be easily recreated in other language.

```
public List<Node> GetPossibleDestinations(Graph graph, Node start, int distanceLimit)
{
    var frontier = new Queue<Node>();
    frontier.Enqueue(start);
    var visited = new List<Node>();
    visited.Add(start);

    while (frontier.Count > 0)
    {
        var currentNode = frontier.Dequeue();

        if (currentNode.distance >= distanceLimit)
        {
            continue;
        }

        var neighbors = graph.GetNeighbours(currentNode);
        foreach (var neighbor in neighbors)
        {
            if (neighbor.nodeType == NodeType.Open && !visited.Contains(neighbor))
            {
                frontier.Enqueue(neighbor);
                visited.Add(neighbor);
                neighbor.distance = 1 + currentNode.distance;
            }
        }
    }

    return visited;
}

public List<Node> GetNeighbours(Node node)
{
    List<Node> neighbours = new List<Node>();

    for (int x = -1; x <= 1; x++)
    {
        for (int y = -1; y <= 1; y++)
        {
            if (x == 0 && y == 0)
                continue;

            int checkX = node.gridX + x;
            int checkY = node.gridY + y;

            if (checkX >= 0 && checkX < graphSizeX && checkY >= 0 && checkY < graphSizeY)
            {
                neighbours.Add(nodes[checkX, checkY]);
            }
        }
    }

    return neighbours;
}

```
> 1 votes

---
Tags: algorithm, turn-based
---


# Question
Title: How do I keep UI texts in their relative positions at all screen resolutions?
I need to position several UI texts on the screen.

I do this using a Canvas with Screen Space Overlay.

Also, these UI texts need to stay at their relative positions at different screen sizes.

Here is a screenshot in which the texts are highlighted in green:

One can see that they don't follow a grid-like pattern.

How could I keep them at their relative position at different screen resolutions?

Thank you.

# Answer
Place a Canvas on your scene. Add a Canvas Scaler to it and set "Scale With Screen Size". Add the UI texts to the canvas.

Make sure that the Anchors are set to "Center". (I had them set to "Top Left". That wrecked up the positioning at different screen sizes).
> 0 votes

---
Tags: unity
---


# Question
Title: Dragging a Rigidbody2D without passing through obstacles
I have this body of code written for an object that needs to be an obstacle and another object that is draggable. I have colliders on both and a kinematic rigidbody on the draggable object, but the obstacle is still allowing the dragged object to be dragged through it. This is all 2d. I'm not sure what I'm doing wrong.

The part that I'm confused on is this - when you just add a collider to the obstacle sprite and a collider and rigidbody (all 2d) to the draggable sprite, if I don't add the script above, then the draggable sprite falls due to gravity on top of the obstacle and stop there, it doesn't fall through the obstacle sprite. **However** when I add the above script which has the `OnMouseDrag` function, and I move the draggable sprite around because now I can, it falls through the sprite.

With no script the obstacle acts like an obstacle. With this script the it does not.

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

public class Block : MonoBehaviour
{
    public GameObject Four_Object1;
    //public GameObject clone_Four_Object1;
    //private Vector3 screenPoint;
    //private Vector3 offset;
    private Rigidbody2D rb2d;
    private Vector3 screenPoint;
    private Vector3 offset;
    private Vector3 cursorPosition;

    public void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        GetComponent<Rigidbody2D>().isKinematic = true;
    }

    public void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(Four_Object1.transform.position);

        offset = Four_Object1.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    public void OnMouseDrag()
    {

        Vector3 cursorScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        cursorPosition = Camera.main.ScreenToWorldPoint(cursorScreenPoint) + offset;
        transform.position = cursorPosition;
    }

    public void FixedUpdate()
    {
        rb2d.MovePosition(cursorPosition);
        Debug.Log("Update!");
    }

}

```

# Answer
Your issue here is the same as the one described in this answer: when you position an object with `transform.position`, you're telling the engine "I don't care about collisions, I figured out exactly where I want this thing to be, so just put it here."

The engine does the predictable thing, doing exactly what you told it to, even if it wedges two colliders clear through each other, or teleports one to the far side of the other without colliding in-between.

The next time the physics engine steps, it will find the resulting trainwreck and do its best to clean up the mess and push the colliders apart by the shortest route it can, but if you're still dragging the object that frame, then you'll just wedge them back together, or keep pulling it through the far side.

If you don't want it to move through collisions, then you need to say so:

* You can use `Rigidbody2D.MovePosition` to ask the physics engine to move the object in a collision-aware fashion, or assign the body a `velocity` computed to bring it toward the target position, letting the physics engine integrate that motion and stop it at collision boundaries.

These methods can still cause the object to penetrate a small amount when you try to cross a large distance in one frame, or even tunnel through if your delta is big enough to completely skip over the object in one step. But for low-speed movements they'll do a good job of keeping the colliders from overlapping.

The `Rigidbody2D` must be dynamic (not kinematic) for these techniques to work. With a kinematic body, again, you're telling the engine "trust me, I know where I want this - put it exactly there and don't let collisions nudge it out of place."
* You can take responsibility yourself for avoiding collisions, by using raycasts/shape casts/overlap queries to identify a safe location to place the object and then place it there directly.

This method very thoroughly avoids tunneling/penetration. It can cause the object to seem to "stick" to a surface when your cursor tries to drag it along-and-slightly-into the obstacle: as long as the ray/shape cast hits the obstacle it'll put on the brakes, so you have to steer it away, or cast a second ray/shape query to slide along the first obstacle to the next-closest non-intersecting point you can find.

Here's a script that will let you play around with the various different methods of positioning an object to see how they compare. Just select from the drop-down either

* `TransformPoint` which always passes through colliders.
* `MovePosition`/`Velocity` which avoid overlaps at low speeds but can show some temporary penetration or tunneling at high speeds/offsets.
* `BoxCast` which always stops at the first collision on the way toward the cursor.

Try it out!

```
using System.Collections;
using UnityEngine;

public class DragTest : MonoBehaviour
{
    public enum DragMode {
        TransformPosition,
        MovePosition,
        Velocity,
        BoxCast
    }

    [Tooltip("Choose how to move the object to the cursor")]
    public DragMode mode;
    [Tooltip("Optional limit on how fast the object can follow")]
    public float maxSpeed = float.PositiveInfinity;
    [Tooltip("Select which layers should block the boxcast drag mode")]
    public LayerMask obstacleLayers;

    Rigidbody2D _body;
    BoxCollider2D _collider;

    delegate YieldInstruction dragMethod(Vector2 destination);

    // Start a drag using the selected method when clicked.
    void OnMouseDown() {
        dragMethod method = null;
        switch (mode) {
            case DragMode.TransformPosition:
                method = TransformPosition;
                break;
            case DragMode.MovePosition:
                method = MovePosition;
                break;
            case DragMode.Velocity:
                method = Velocity;
                break;
            case DragMode.BoxCast:
                method = BoxCast;
                break;
        }
        // Start a function that will run each frame/physics step
        // to update our dragged position until the button is released.
        StartCoroutine(Drag(method));
    }

    // Update the dragged position as long as the mouse button is held.
    IEnumerator Drag(dragMethod dragTo) {
        // Turn off our gravity while we're being dragged.
        float cachedGravityScale = _body.gravityScale;
        _body.gravityScale = 0f;

        // Stash our current offset from the cursor,
        // so we can preserve it through the move.
        var offset = transform.InverseTransformPoint(ComputeCursorPosition());

        while (Input.GetMouseButton(0)) {
            // Keep the object from accumulating velocity while dragging.
            _body.velocity = Vector2.zero;
            _body.angularVelocity = 0f;

            // Calculate desired drag position.
            var cursor = ComputeCursorPosition();
            var destination = cursor - transform.TransformVector(offset);

            var travel = Vector2.ClampMagnitude(
                destination - transform.position,
                maxSpeed * Time.deltaTime);

            // Let our chosen drag method choose how to get us there.
            yield return dragTo(_body.position + travel);
        }

        // Re-enable gravity as before.
        _body.gravityScale = cachedGravityScale;
    }

    // Using this method, the object will teleport through obstacles.
    YieldInstruction TransformPosition(Vector2 destination) {
        transform.position = destination;
        return null;
    }

    // Using this method, the object will stop at obstacles,
    // though it may penetrate for a frame before rebounding.
    YieldInstruction MovePosition(Vector2 destination) {
        _body.MovePosition(destination);
        return null;
    }

    // Effectively the same results as MovePosition.
    YieldInstruction Velocity(Vector2 destination) {
        var velocity = (destination - _body.position) / Time.deltaTime;
        _body.velocity = velocity;
        return new WaitForFixedUpdate();
    }

    // Using this method, the object will stop at the border of the obstacle.
    // It can "stick" to surfaces when dragged into them, because it keeps colliding.
    // Pull the cursor parallel or away from the surface to unstick it.
    YieldInstruction BoxCast(Vector2 destination) {
        // Compute the direction & distance to scan ahead.
        var travel = destination - _body.position;
        var distance = travel.magnitude;

        // Skip the query if we're not going anywhere.
        if (Mathf.Approximately(distance, 0f))
            return null;

        // Find the center of our box.
        Vector2 origin = transform.TransformPoint(_collider.offset);

        // Check for any obstacles that our collider would clip on the way.
        var hit = Physics2D.BoxCast(
            origin,
            _collider.size,
            _body.rotation,
            travel,
            distance,
            obstacleLayers);

        // If we hit something, stop just a hair before the collision.
        if (hit.collider) {
            var direction = travel/distance;
            distance = hit.distance - Physics2D.defaultContactOffset * 2f;
            destination = _body.position + direction * distance;
        }

        // Now it's safe to use any of our other methods without penetrating/tunneling,
        // since we took responsibility for avoiding collisions ourselves.
        transform.position = destination;
        return null;
    }

    // Initialize component dependencies.
    void Start() {
        _body = GetComponent<Rigidbody2D>();
        _collider = GetComponent<BoxCollider2D>();
    }

    // Utility functions to compute dragged position.
    float GetDepthOffset(Transform relativeTo) {
        Vector3 offset = transform.position - relativeTo.position;
        return Vector3.Dot(offset, relativeTo.forward);
    }

    Vector3 ComputeCursorPosition() {
        var camera = Camera.main;
        var screenPosition = Input.mousePosition;
        screenPosition.z = GetDepthOffset(camera.transform);
        var worldPosition = camera.ScreenToWorldPoint(screenPosition);
        return worldPosition;
    }
}

```
> 1 votes

# Answer
if you want to be a little deep, in any any computer software and specially games, there are only calculations. unity and other tools only wrap detailed and low level calculations to let the developer concentrate on development.

when you have an active rigidBody on your object, you just tell the physics engine to controll the object. so when you want to make other element like animation or translation move it, it can cause problems.

if you want to drag this object, you have to make it kinematic. when the player left the dragging, you can turn off the kinematic again.

another approach can be velocity property of rigidbody. just turn the gravity off and make the object velocity to move toward mouse **RayCast**.

another guessing approach can be using **joints** with very short length that is attached to the **GameObjec**t. you can control the joint with mouse or touch dragging and ball should move with it, but it needs testing and work to make it behave properly
> 0 votes

---
Tags: unity, c#, collision-detection, collision-resolution, rigidbody
---


title: Seamless 2D wrap-around effect

text:
# Question
Title: Seamless 2D wrap-around effect
I am trying to show multiple images on a grid system which are randomly generated and the grid is moving from right to left.

What my client wants is when a part of a picture goes off the left edge of the viewport, it should start to peek in from the right, similar to the image shown below:

You can see the red and blue images each represent the same object. When they go off the left edge of the screen, they appear the right edge. It should happen seamlessly, without a sudden "pop" appearing out of nowhere.

I think it can be done via a shader, but I'm not a shader programmer. How can I achieve this effect?

# Answer
You can do this with magic (shader)!

# Secret: Cutting Assistant In Half

> Of course, we know she is never actually cut in half. So, there has to be some logical explanation for it all. Well, he certainly relies on the help of an assistant alright. But it’s not one – he has two of them!
>
> https://www.editorchoice.com/magic-tricks-revealed/

as you see in the below picture we need two persons or objects to achieve this effect.

you can achieve this effect easily by using world space shader that I explained before I did this with childing twin but you can use code to teleport.

```
Shader "Smkgames/worldSpaceFade" {
    Properties {
         _Size("Size",Vector) = (2,0,2,0)
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
         _BumpMap ("Bumpmap", 2D) = "bump" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
 Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
     Pass {
        ZWrite On
        ColorMask 0
    }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows alpha:fade

        #pragma target 3.0

        sampler2D _MainTex,_BumpMap;

        struct Input {
            float2 uv_MainTex;
            float2 uv_BumpMap;
            float3 worldPos: TEXCOORD2;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        float4 _Size;

        void vert (inout appdata_full v, out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.worldPos = mul(unity_ObjectToWorld, v.vertex);
        }

        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            float4 equation = (IN.worldPos.x/_Size.x)*(IN.worldPos.x/_Size.x);
            float4 InvertEquation = (IN.worldPos.z/_Size.z)*(IN.worldPos.z/_Size.z);
            float4 finalEquiation = max(equation,InvertEquation);
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = step(finalEquiation,0.5);
             o.Normal = UnpackNormal (tex2D (_BumpMap, IN.uv_BumpMap));
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

# Object Pooling Concept

another concept that you should know is Object Pooling. when one person or object arrived to the destination then move it back to the first position and her twin will appears.

# Dynamic Teleport

better way is Teleporting by code:

```
using UnityEngine;

public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
private void OnTriggerEnter(Collider other) {
    var pos = other.transform.position;
    pos.x = teleportTarget.position.x;
    other.transform.position = pos;
}
}

```
> 6 votes

# Answer
Myself, I wouldn't do this with a shader, but with a second camera.

The idea is we'll take our original/main/central camera, and make a copy that butts-up perfectly against its left side. As an object exits the left side of our main camera's view, it will enter the right side of this camera's view. If we draw both cameras to the same output buffer (the player's screen/window), then we'll see two images of the object: one exiting to the left, and one entering from the right.

All it takes is a little coordination to make sure the alignment is perfect.

To keep things simple, I'm going to make some assumptions:

* Your central camera is...
    + orthographic
    + located at world x = 0
    + in default orientation (looking along the z+ axis, with y+ up)
    + unchanging over time (you're not modifying its location or parameters)
* Your game window doesn't change size / mobile orientation during play
* Your display objects move from right to left only, never left to right

(If you need to break these rules, there are solutions available, they're just more complicated than the simple version I'll show here)

To start, create a copy of your central camera, call it "wraparound"

* Make it a child of the central camera (for ease of positioning)
* Remove its AudioListener (so all audio is heard by just one camera, and we don't get errors)
* Set its Depth to 0 (instead of the default -1, so it renders after the central cam)
* Set is Clear Flags to "Don't Clear" (so it keeps the colour & depth drawn by the central cam)

Attach to it a script something like this:

```
public class WraparoundCamera : MonoBehaviour {
    // Quick & dirty singleton.
    public static WraparoundCamera current;

    Camera central;
    float halfViewWidth;

    void Awake() {
        // Make ourselves easy for other scripts to find.
        WraparoundCamera.current = this;

        // Position this camera to butt up to the central camera's left edge.
        central = transform.parent.GetComponent<Camera>();
        halfViewWidth = central.aspect * central.orthographicSize;
        transform.localPosition = Vector3.left * halfViewWidth * 2f;
    }

    // Objects will call this to wrap themselves around to the other side of the view.
    public bool WrapMeIfNeeded(Renderer renderer) {
        // If the object is still in range to be seen by the central camera, don't move it.
        if(renderer.bounds.max.x >= -halfViewWidth)
            return false;

        // Once it's passed the left edge of the central camera,
        // teleport it over on full view width, so it's at the right edge.
        renderer.transform.position += Vector3.right * halfViewWidth * 2f;
        return true;
    }
}

```

Then your moving objects can use a script a bit like this:

```
void Update() {
    transform.position += velocity * Time.deltaTime;
    WraparoundCamera.current.WrapMeIfNeeded(renderer);
}

```
> 3 votes

---
Tags: unity, c#, shaders, graphic-effects
---


# Question
Title: Unity ads displaying only unity products
i just implemented unity ads on my project and now its only showing a single unity product each times. Can anyone suggest why? Thanks..

Here is some screenshot of the ad 1: (https://i.stack.imgur.com/oG9vm.jpg) 2: (https://i.stack.imgur.com/ZrS7x.jpg)

Can anyone tell me if this is even a real ad or just for testing?

# Answer
> 0 votes
you have to go to your unity panel and make a **campaign** or change any unwanted **region** limitation or **age** limitations. if you only receive one advertisement, it means there is only that ad that satisfies your limitations.

im not sure that unity **caches** ads but check for internet connection. maybe it loads old ads of there is timeouts or...

---
Tags: unity, unity-ads
---


title: Strange GLSL performance problems

text:
# Question
Title: Strange GLSL performance problems
I'm having weird performance problems with a GLSL shader I'm working on. This small example fragment shader:

```
#version 450
out vec4 fragColor;

struct ST { float a; float b; float c; float d; float e; };

void main() {
    ST s = ST (0.0,0.0,0.0,0.0,0.0);
    ST[1] stack;
    int ptr = 0;
    for (int i = 0; i < 32; i++) {
        if (i > -1) // Always true
            stack[ptr++] = s;
        s = stack[--ptr];
    }

    fragColor = vec4(1.0);
}

```

has horrible performance, but the same shader with almost anything taken out, for example, removing `e` from the struct, performs fine. I'm just using these on a fullscreen triangle.

I can't figure out what's going on, and how I could fix this problem in my actual shader. Any ideas?

# Answer
> 1 votes
Loops and flow control statements in shaders aren't great. Avoid when possible. At best, they will be slow, and at works, they won't work at all (loops).

GPU cores are optimized for mathematical calculations, not logical flow control of programs (loop exit conditions, if statements etc). When you use such constructs in shaders, it really hurts performance and here is why:

Let's look at a trivial hypothetical situation. Imagine you write a fragment shader with a single if statement in the code. That if statement controls whether or not a calculation is performed. The calculation will be carried out 10% of the time.

What happens when you execute a shader pipeline, is that at the driver/hardware level, a "warp" is executed. Warps are a collection of shader kernels (an instance of a shader/gpgpu program) each of which will run on a single core. After these kernels have executed, the memory they operate opon (in this case, a target buffer texture), will have to be memory fenced and synchronized, and wait until all kernels have exited.

90% of the kernels will finish early, having not had to perform our extra calculation, but the remaining 10% will still be working, thus adding a little extra work *some of the time* will actually reduce performance *all the time*.

Then you have code branching. On a cpu, when code branching is executed, difference branches of code are run on different cores, with little to no penalty in performance (compilers sort this out for you), but on gpus this sort of branch prediction is not available, and in most cases will result in performance loss. Loops suffer from this problem, because their exit conditions result in code branching upon compilation.

The solution?

Unroll your loop code, and stick to shaders with a finite predictable scope.

---
Tags: opengl, shaders, glsl, performance
---


# Question
Title: How do i retrieve individual Tile Information from a tilebased procedural World fast?
I am concerned about performance with my current setup; as I want to expand on it i need to figure out if I might need to change it.
**Current Setup:**
The Game/Prototype is similar to Dwarf Fortress or Rimworld. The world i have is tile based and procedural. It is made up of chunks(16x16). All chunks are connected not via coordinates but via pointers (chunk on the east, chunk in the north, chunk in the south and so on). Each chunk segment (or block/ tile) holds an entity(which can be the player, the human or a plant).
Lets say one Entity (for a example a human) walks towards the edge of the chunk and wants to know what is the tile next to him. Then i will have to look at min 8 tiles next to him. Due to the chunks only being accessible through neighbors, I have to always check wether the position relative to the entity is in a new chunk and how many chunks i have to iterate through to get to the position asked for. It is quiet the hassle and i can imagine it becomes a big performance problem once i want to do pathfinding.
**Now some Questions:**
How do games like Factorio handle this type of data gathering. In an Array i could easily figure out where to look. **How do i retrieve individual Tile Information from a tilebased procedural World fast?** Should i use coordinates or relative Positions(like i do now)?

# Answer
I suggest using a quadtree, which is composed of nodes that contains four pointers to nodes. It's basically a binary tree for 2D, like an octree is for 3D. With it you divide your terrain into squares (chunks) that are grouped up in nodes of four chunks, that are themselves grouped up into nodes, etc. Then you write recursive algorithms to go through your tree. The advantage is whenever you want to add a chunk, you just attach it to the appropriate node, at the appropriate place, and if it doesn't exist, create a bigger node and add it, so on.

More precisely, you can have a node class that is the base type of each pointer. Then you have the "branch" class and "leaf" class that inherit of node. The branch class has four pointer to nodes. The leaf class is just a chunk. It's up to you to design the algorithms, and what a node has in information, but here's pseudocode for one recursive algorithm :

```
Chunk findChunk(x,y) {
   if(x<nodeX) {
    if(y<nodeY) {
      return topRightNode.findChunk(x,y);
    } else {
      return bottomRightNode.findChunk(x,y);
    }
  } else {...}
}

```

Of course, this requires more, such as findChunk function in chunk, that always returns itself, and a null check before calling each findChunk, because if the pointer is null, that means the chunk you are looking for doesn't exist, and must be created.

There is a lot more to know, the best is to Google about it and try it out.
> 1 votes

# Answer
I do not know how games do this, but I think you should abandon that data structure. A coordinate system that gets a pointer to a chunk when given coordinates would be simpler and much faster to get a point from anywhere. This means an array of pointers, and as you said it is easy to find where to look. You could use a dynamic size list with pointers to generate chunks on the go. I think you shouldn't worry too much about performance yet, don't make it too complex or specific, as you might end up having to write something much too complicated for a case you didn't foresee.
> 0 votes

# Answer
Why not use a Dictionary, where the key is a tuple that holds int x and int y values and the other entry is a pointer or reference to your tile?
> 0 votes

---
Tags: performance, path-finding, procedural, tiles
---


title: Networking - assigning IDs to entities

text:
# Question
Title: Networking - assigning IDs to entities
Maybe I'm asking dumb question, but this problems bothers me...

So I have my networked game in Unity (client), and server written in C# (without Unity). I Use ENet library for networking. Most of networked components are written by myself (lobby, components etc.).

Server doesn't know about Unity entities like players, obstacles etc. In most cases I send message ("hide object with id 4") to the server, and server pass that message to other clients where they applied message information.

What my problem is, how to assign proper IDs to networked objects, that will be the same across all players?

What I do is that:

1. On all clients I get all components with specific network component (e.g. NetworkRigidbody)
2. I sort all of objects using special comparer which compares based on component name with all parents appended to it
3. ID is just an index in sorted array

Above algorithm works, but I have a feeling that in normal games that problem is handled in other manner.

I searched over Mirror, MLAPI and other libraries source code and I couldn't find how entity id is generated, especially when server is not Unity application.

# Answer
> 0 votes
A simpler method is to set a free ID on creation and send to other clients "create entity of type foo with ID 4 and parameters x,y,z,bar"

There is a danger of collision when selecting IDs for which you need a mitigation strategy. Either by error message and some kind of recovery or pre-agreeing a pool of IDs for each entity creator which can grow as needed.

Fixing the ID on creation also gives you the guarantee that the ID for a specific entity can remain the same for as long as it is alive.

---
Tags: unity, networking, unity-networking
---