title: Creating a hexagonal wraparound map

text:
# Question
Title: Creating a hexagonal wraparound map
I'm trying to create a wraparound map for a hexagonal map, so when you exit a tile on one side of the big hexagon-shaped map, you enter a tile on the other side.

Example image from Red Blob Games article on Hexagonal Grids.

In the image, the pale tan hexagonal chunk in the center is our map. The greenish/reddish chunks around it are shifted copies of the same map. If we stand on the blue tile under the cursor and walk off the main map into the green copy to the right, that's the same as wrapping around our map to the corresponding point on the other side: here, walking from the blue tile in the lower-right-hand red copy into the bottom-right corner of the center map.

I used an approach with a lookup table first. But as soon as those maps get too big, the lookup tables get even bigger. I'm searching for a solution which works without a lookup table.

# Answer
Here's a simple method which does not become more complex as the map grows in radius:

1. Keep a list of the center coordinates of your main map (0, 0, 0), and its 6 shifted copies.
2. After a move that might take you off the edge of the map, calculate the distance to your destination tile from each of these center points.
3. Stop when you find a center point whose distance away is less than or equal to your map radius.
4. Subtract this center point from your destination point. Now your destination is correctly expressed as an offset from the center of your original map (0, 0, 0).

Implemented directly, this is at most 7 distance checks, no matter how big your map gets.

But, if your distance from the original center is less than your map radius, you can skip the other checks entirely, since you haven't crossed an edge.
> 4 votes

# Answer
Here's a demo of a wraparound hexagonal map. Use the QWEASD keys to move around:

```
const size = 20;
const dx   = size * 3 / 2;
const dy   = size * Math.sqrt(3);

const radius   = 3;
const diameter = 2 * radius;

const canvas  = document.createElement("canvas");
const width   = canvas.width  = diameter * dx;
const height  = canvas.height = diameter * dy;
const context = canvas.getContext("2d");

const y_axis  = 3 * radius - 2;
const length  = radius ** 3 - (radius - 1) ** 3;
const coords  = Array.from({ length }, coordOf);

const colors  = ["#E6A86E", "#FFCD9E", "#CF8846"];

var player = 0;

document.body.appendChild(canvas);

document.body.addEventListener("keypress", keypress);

draw(player);

function coordOf(_, i) {
    const [x, y, z] = toCoords(i);
    return [ width / 2 + (x - y) * dx
           , height / 2 + (z - (x + y) / 2) * dy];
}

function toCoords(i) {
    const coords = getCoords(i, 0, 0);
    return Math.max.apply(Math, coords) < radius ?
        coords : getCoords(i - length, 0, 0);
}

function getCoords(x, y, z) {
    return x < 0 ? getCoords(x + y_axis + 1, y, z + 1) :
        x < radius ? [x, y, z] : getCoords(x - y_axis, y + 1, z);
}

function keypress(event) {
    const y = y_axis, z = y + 1;

    switch (event.key) {
    case "q": player += y; break;
    case "w": player += z; break;
    case "e": player += 1; break;
    case "a": player -= 1; break;
    case "s": player -= z; break;
    case "d": player -= y; break;
    }

    if (player < 0) player += length;
    else player %= length;
    draw(player);
}

function draw(player) {
    const [x, y] = coords[player];
    context.clearRect(0, 0, width, height);
    field(width / 2, dy);
    hexagon(x, y, size / 2, "#000000");
}

function field(cx, cy) {
    for (let i = 1 - radius; i < radius; i++) {
        const j = Math.abs(i);
        const x = cx + i * dx;
        const y = cy + j * dy / 2;
        const k = diameter - j - 1;

        for (let i = 0; i < k; i++) {
            hexagon(x, y + i * dy, size, colors[(2 * i + j) % 3]);
        }
    }
}

function hexagon(x, y, size, color) {
    context.beginPath();
    context.moveTo(x + size, y);

    for (let i = 1; i < 6; i++) {
        const angle = i * Math.PI / 3;
        context.lineTo( x + Math.cos(angle) * size
                      , y + Math.sin(angle) * size );
    }

    context.closePath();
    context.fillStyle = color;
    context.fill();
}
```

Oftentimes in programming, choosing a suitable data structure can drastically simplify the algorithm for solving a particular problem. Your problem can be elegantly solved by vectorizing the hexagonal map as follows:

```
        16
    15      09
14      08      02
    07      01
06      00      13
    18      12
17      11      05
    10      04
        03

```

Vectorization means converting the two-dimensional hexagonal map into a one-dimensional array. The numbers in the above diagram represent the indices (of the corresponding hexagonal map cells) in the one-dimensional array. For example, the center cell of the hexagonal map is stored at index 0 in the one-dimensional array.

This representation of a hexagonal map has an important advantage. For any given cell, its six neighbors (including wraparound neighbors) are always a fixed distance away (modulo the total number of cells in the hexagonal map):

```
    +8
+7      +1

-1      -7
    -8

```

For example, the six neighbors of 0 (going counter-clockwise) are:

* 1 ≡ 0 + 1 (mod 19)
* 8 ≡ 0 + 8 (mod 19)
* 7 ≡ 0 + 7 (mod 19)
* 18 ≡ 0 - 1 (mod 19)
* 11 ≡ 0 - 8 (mod 19)
* 12 ≡ 0 - 7 (mod 19)

Note that vectorization works for hexagonal maps of any size. The above example is a hexagonal map of side length 3. It has 19 cells and its neighbors on the y-axis are 7 indices apart. These values can be obtained using the following equations:

The neighbors on the x-axis are always 1 index apart and therefore the neighbors on the z-axis are always (y-axis(n) + 1) indices apart. Here are the axes for reference:

```
    -z
+y      +x

-x      -y
    +z

```

Hope that helps.
> 4 votes

# Answer
You can actually do a rectangular projection without wasted space in the array. This enables yo has the added benefit, that the character visually goes upwards instead of in an angle.

You can get the center of a hex with the following formula (width and height is the hexagon width and height, x and y are the current position):

```
centerX = x * width + (y % 2 + 1) * width / 2
centerY = y * height + height / 2

```

If you have a map with the width `n` and height `m`, then every hexagon on the left side will have the x coordinate 0, on the right side the x coordinate `n`, in the top row they'll have a y coordinate 0 and and on the bottom a y coordinate `m`.

This also means the four corners are `(0; 0)`, `(0; m)`, `(n, 0)`, `(n, m)`.

So, to achieve a wrapping effect, you need to check if the x coordinate of the player is bigger than `n`, and if it is, then set it to 0, if it's smaller than 0, then set it to`n`, if the y coordinate is smaller than 0, then set it to `m` and if it's bigger than `m`, than set it to 0.

In code:

```
if (x < 0) x = n;
if (x >= n) x = 0;
if (y < 0) y = m;
if (y >= m) y = 0;

```
> 1 votes

---
Tags: hexagonal-grid
---


# Question
Title: How to know the point of collision with another object in Unity5
I have a small problem and it would be very helpful, which could guide me. What happens is the following, I have an enemy (evil usb) in my scene, to the collisionar this enemy with my main player threw the enemy always right falling down the map. All right up here, what I need now is to know that exact point I'm colliding my enemy to know if I should throw it to the right or left depending on the point of collision which can be at the Centre to the right or to the left of my enemy like this imagen:

I read something about contact point, but can not understand how it works and really serves me, here is the code that I have to collision and throw it to the right:

```
void OnCollisionEnter(Collision other){

    if (other.gameObject.CompareTag ("Inacapin")) {
       enemyrigid.AddForce (-transform.right * 500, ForceMode.Acceleration); // work fine

      /*if(point of collision right){ // I need something like that

            enemyrigid.AddForce(-transform.right * 500, ForceMode.Acceleration);

         }else if(point of collision left){
            enemyrigid.AddForce(-transform.left* 500, ForceMode.Acceleration);
            }else{
             enemyrigid.AddForce(transform.forward* 500, ForceMode.Acceleration);
          }

     }

  }

```

hope they can help me, thank you... ;)

# Answer
You should use the member contacts from the Collision object `other`.

This is the example in the API docs:

```
void OnCollisionStay(Collision collision) {
    foreach (ContactPoint contact in collision.contacts) {
        print(contact.thisCollider.name + " hit " + contact.otherCollider.name);
        Debug.DrawRay(contact.point, contact.normal, Color.white);
     }
}

```

Hope it helps.
> 0 votes

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


# Question
Title: Character appearance synchronization in open world multiplayer game
I am working on a multiplayer open world game where you can equip handhelds and armor pieces. In my architecture, there are clients and an authoritative server. Every equipable item is crafted by a user. They can be different in shape, so it's important that I synchronize shape information. This is expensive data to send (basically an outline plus some more info). Together with this, I also want to synchronize any equipment event that occurs, so when a user meets another user, they can see each other's gear.

The easiest solution I've found is to force-send gear on equipment, but it will use bandwidth even when two players are far away.

This feels like a problem that has been solved a thousand times, so I don't want to reinvent the wheel. Do you know of any best practice/known strategy that suits my situation?

# Answer
> 1 votes
One way you can handle this is to hash or digest your gear data, and first send the digest to as "have you seen a gear item with this description recently?"

If the party on the other side says no, you reply with the full data.

They associate that gear data with the digest in a cache, so if the player with this gear swaps it in & out frequently or leaves & comes back, you don't need to re-transmit the full data every time.

If you keep the maximum lifetime of an item in the cache low relative to the size of your digest, then your chances of having a collision from two different gear items producing the same digest can be made quite small - the two items would need to be seen within a short time of one another.

You can further reduce the risk of collision by doing a higher-detail check when I'm in direct interaction with someone - if they're one of the 3 players closest to me or we're using game abilities on one another, we can ask for a different/larger digest to verify that we're showing the correct equipment.

This can be combined with a level of detail system. If a player enters the area a kilometer away, the server can send me the lowest-detail version of the gear, maybe just its base colour value.

As the player comes closer, the server can ask me "Have you seen gear item A8675E875EC24A245D0 at medium detail?" and I say "no," so it sends me a medium-detail version of it suitable for display at that distance.

If we enter within a few meters of each other, the server can ask "Have you seen gear item A8675E875EC24A245D0 at high detail?" and I say "no," so it sends the full data. This way we only send as much information as is needed to adequately display the content.

# Answer
> 0 votes
**NOTE**: I'm missing some info:

1. What's the number of simultaneous players
2. How's that crafting system? I understood that a player can craft a piece of armor with whatever shape they want, is this it? Or are there presets and player can simply increase a little the X side up to twice the original size and choose among 10 textures?
3. Platform?
4. Powerful server or not? Is the game already runnable and can the server be benchmarked?

You said you have an authoritative server. If that's the case, why would you have to send anything between clients?

You could send everything once to the server, and it would be the one handling distances and sending the appropiate data to the clients who need it.

Example: If you have a brand new armor piece just crafted, you send whatever info (outline, texture, etc.) to the server, which should keep it in a DB. The server will be updating players' positions and will receive a message if you change your gear, but it won't receive this gear's info anymore (just use ID as mentioned in Gregory's answer). Then, IF players can configure their LOD distance, I see two options:

1. The player sends a request to the server asking for another player's info when he detects a different player entered their LOD distance (bad idea in my opinion, every client always knowing where all other players are? Security threat on sight).
2. The server holds the distances of LODs for every connected player. As I said, this should be carefully studied since it's obviously not the same to hold this data for 10 players than for 10k. In any case, it would be just an extra integer for each player and it could be inside the Player entity itself in RAM (to avoid performance problems looking up a hash table/vector/map or whatever). If 1 distance parameter is enough for each player and you had 10k simultaneous players, it would take 10000 * 4B = 40kB in the server's RAM, I think it's not that much to the big troubles you're avoiding.

Obviously there are drawbacks as in any solution. If you add the extra info I mentioned, I could allow me to make my answer more accurate and try to help you better.

Regards.

---
Tags: networking, multiplayer, client-server, mmo, synchronization
---


# Question
Title: How can I display a loading state until a song loaded with www.GetAudioClip() is ready to play?
I use `www.GetAudioClip()` to get a song and play it when my Android mobile game starts.

My issue is that it takes a 3-second delay to play the song.

My idea is to add some loading screen before starting the game, and the game starts after `www.GetAudioClip()` finishes getting the song and I begin to play it. But I don't know how to control the loading screen so it disappears after the right delay.

# Answer
> 2 votes
This can be done with a coroutine you start by calling `StartCoroutine(LoadSongWithLoadingScreen(songURL));`

```
IEnumerator LoadSongWithLoadingScreen(string url) {

    // Show your loading screen.
    loadingVisuals.SetActive(true);

    // Start the download.
    var request = new WWW(url);

    // Wait for the download to finish,
    // letting the game continue running
    // and animating in the meantime.
    yield return request;

    // TODO: check for & handle network errors.

    // Hide loading screen.
    loadingVisuals.SetActive(false);

    // Use your song.
    song = www.GetAudioClip();
    PlaySong(song);
}

```

---
Tags: unity, c#, sound, loading
---


# Question
Title: Draw a sphere with a custom material from script
How can I spawn or draw a sphere with a custom material with a script?

So far I've tried using Gizmos.DrawSphere, but I can't find a way to control the material used to draw it.

I would like to draw it with a material with some specularity, around 0.5.

# Answer
You can spawn a new spherical GameObject and set its material like so:

```
var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);

var renderer = sphere.GetComponent<Renderer>();

renderer.sharedMaterial = myMaterial;

```

Or if you just want the sphere to be drawn, without having a GameObject for it in your scene, you can use Graphics.DrawMesh / Graphics.DrawMeshNow / Graphics.DrawMeshInstanced, passing a spherical mesh and the material you want to use (or setting the material with Material.SetPass before using the "now" version)
> 1 votes

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


# Question
Title: Transforming 2D viewport coordinates after scaling the viewport (zoom in/out)
I've been getting started with personal experimentation and have been working on a project for a few days now using SDL2. It is a 2D game, and at this stage I have it rendering game objects in a fixed-size viewport that can navigate around the 'game world'.

I'm not terribly well-versed in linear algebra yet, so it's possible that the answer to this question is somewhere in that curriculum that I have yet to tackle.

The game space has its own coordinates, organized in the same way that they are on an `SDL_Window`. The "viewport" then has its own coordinates (indicated by it's top left corner) in the game space. Game objects are then given transformed coordinates in the viewport's own coordinate space, which corresponds to the `SDL_Window`'s coordinate space i.e. they start at `(0, 0)` at the upper left, which is essentially an offset given the viewport's coordinates, e.g.:

Entity x's gamespace coordinates are `(100, 200)` and the viewport's gamespace coordinates are `(20, 20)`, the entity's "viewport" coordinates would be `(100 - 20, 200 - 20)` or `(80, 180)`.

I've started to think about implementing 'zoom' functionality. At the moment, all that means is that the viewport is scaled up or down (to certain size limits), and the game entity's dimensions are scaled up or down correspondingly. What isn't transformed are the coordinates.

Visually, this is the basic problem:

At maximum size, where the viewport's dimensions are the same as the game space's dimensions (they have the same aspect ratio), the positions of all objects in the viewport space would be the same as they are in the game space, but they would have to be positioned using completely different coordinates in the viewport space.

What are the mathematical techniques/principles I should be studying to figure this one out? Thank you!

# Answer
This is all covered by *Translation*, *Rotation* (not mentioned by you) and *Scaling*. You can write separate functions for each transformation but usually it is done using **homogeneous coordinates** and **Matrices**. By this you can define arbitrary sequence of operations and perform them on any point.

Here are the three Matrices:

**Translation** (Translate a point by (X,Y)):

```
[ 1  0  X  ]
[ 0  1  Y  ]
[ 0  0  1  ]

```

**Rotation** (rotate a point by a):

```
[ cos(a) -sin(a)  0  ]
[ sin(a)  cos(a)  0  ]
[    0      0     1  ]

```

**Scaling** (scale a point Sx,Sy):

```
[ Sx   0    0  ]
[  0   Sy   0  ]
[  0   0    1  ]

```

To transform a point by any matrix you need to add a 3rd coordinate to your points which is basically just "1":

```
[x y 1]

```

Now you can multiply any of the above mentioned matrices with your vector and transform it:

Example Scaling:

```
  [x]   [ Sx   0    0  ]     [ x * Sx  ]
  [y] . [  0   Sy   0  ]  =  [ y * Sy  ]
  [1]   [  0   0    1  ] =   [    1    ]

```

If you want to combine operations you can multiply your matrices and then multiply each point with the result. So you can calculate a **transformation matrix** based on your viewport once and transform all points before drawing them.

See this question for more detailed information about homogeneous coordinates
> 1 votes

---
Tags: 2d, camera, sdl2, scale, viewport
---


title: How can I avoid jittery motion in SDL2?

text:
# Question
Title: How can I avoid jittery motion in SDL2?
I am experiencing stutter when I am moving faster than 0.1 units in my program.

When doing exactly 0.1 units I get:

For test purposes I've made the bot always heading southeast.

```
int main()
{

// Intialize SDL2

SDL_Init(SDL_INIT_EVERYTHING);

  // Defining world & window dimensions and camera position
  const int SCREEN_WIDTH{ 800 };
  const int SCREEN_HEIGHT{ 480 };
  const int WORLD_WIDTH{ 1000 };
  const int WORLD_HEIGHT{ 1000 };
  int view_x{ 0 };
  int view_y{ 0 };

  // Create window and default rendering context
  SdlCreateWindowAndRendererWrapped wr{ SCREEN_WIDTH, SCREEN_HEIGHT };
  SDL_Renderer * const ren{ &wr.get_resource_renderer() };

  Object ground(ren, "assets/ground.png", 0, 0, 95);
  ground.set_size(600);
  ground.set_pos(200, 200);

  Object bot(ren, "assets/bot.png", 40, 46, 32);
  bot.set_size(200);

  // Game loop
  bool is_running{ true };
  SDL_Event event{};
  SDL_SetRenderDrawColor(ren, 0, 0, 0, 0);
  while (is_running) {
    Uint64 start = SDL_GetPerformanceCounter();
    /*--------------Event loop--------------*/
    while (SDL_PollEvent(&event))
    {
      if (event.type == SDL_QUIT)
      {
        is_running = false;
      }
    } // end of the event loop

    /*--------------Physics loop--------------*/
    static Clock clock;
    clock.tick();
    Vec2f v{ 0.3f, 0.3f };
    bot.move(v, clock.delta);

    // Screen coordinate translations
    bot.set_pos(bot.get_pos().x - view_x, bot.get_pos().y - view_y);
    ground.set_pos(ground.get_pos().x - view_x, ground.get_pos().y - view_y);
    ground.update();
    bot.update();

    // Check camera bounds
    if (view_x < 0)
    {
      view_x = 0;
    }
    if (view_y < 0)
    {
      view_y = 0;
    }
    if (view_x > WORLD_WIDTH - SCREEN_WIDTH)
    {
      view_x = WORLD_WIDTH - SCREEN_WIDTH;
    }
    if (view_y > WORLD_HEIGHT - SCREEN_HEIGHT)
    {
      view_y = WORLD_HEIGHT - SCREEN_HEIGHT;
    }

    // Make the camera follow the bot
    view_x = bot.get_pos().x - SCREEN_WIDTH / 2;
    view_y = bot.get_pos().y - SCREEN_HEIGHT / 2;

    /*--------------Rendering loop--------------*/
    SDL_RenderClear(ren);
    ground.draw(ren);
    bot.draw(ren);
    SDL_RenderPresent(ren);

    /*--------------Todo: Animation loop--------------*/

    // Cap to 60 FPS (approx. 16.666 ms per frame -- the cycle time)
    Uint64 end = SDL_GetPerformanceCounter();
    float elapsed_ms{ (end - start) / static_cast<float>(SDL_GetPerformanceFrequency()) * 1000.0f };
    if (std::isless(elapsed_ms, 16.666f))
    {
      SDL_Delay(static_cast<int>(floorf(16.666f - elapsed_ms)));
    }
  }

  // Clean up used resources
  SDL_Quit();
  return 0;
}

```

I took inspiration for designing my game loop from

https://thenumbat.github.io/cpp-course/sdl2/08/08.html

The Clock class/struct was implemented exactly as Salajouni's one:

How to calculate delta time with SDL?

The camera was implemented via this method:

https://wiki.allegro.cc/index.php?title=How\_to\_implement\_a\_camera

This is how my Object struct/class looks like:

```
class Object
{
public:
    explicit Object(SDL_Renderer * t_renderer, const std::string & t_s, const int t_x, const int t_y, const int t_sz)
    {
        sprite = new Sprite;
        sprite->set_texture(t_renderer, t_s);
        sprite->set_src_rect(t_x, t_y, t_sz, t_sz);
        sprite->set_dest_rect(0, 0, t_sz, t_sz);
        size = t_sz;
    }
    ~Object()
    {
        delete sprite;
        sprite = nullptr;
    }
    int get_size() const
    {
        return size;
    }
    void set_size(const int t_sz)
    {
        size = t_sz;
    }
    const Vec2i & get_pos() const
    {
        return pos;
    }
    void set_pos(const int t_x, const int t_y)
    {
        pos.x = t_x;
        pos.y = t_y;
    }
    void move(const Vec2f & t_v, const Uint32 t_delta)
    {
        pos.x += static_cast<int>(t_v.x * t_delta);
        pos.y += static_cast<int>(t_v.y * t_delta);
    }
    // Todo:
    void animate()
    {
    }
    void update()
    {
        sprite->set_dest_rect(pos.x, pos.y, size, size);
    }
    void draw(SDL_Renderer * ren)
    {
        SDL_RenderCopy(ren, &sprite->get_texture(), &sprite->get_src_rect(), &sprite->get_dest_rect());
    }
private:
    Sprite * sprite{};
    Vec2i pos{};
    int size{};
};

```

The part that supposedly needs the most attention is the **physics loop**. This is the part where all the motion and motion updates happen. In there I define a velocity vector and set both of its components too 0.3. After that the stutter/jitter happens. However, when I do 0.1, then it runs smoothly as shown in the pictures above. I created the window via SDL\_CreateWindowAndRenderer(). So accelerated rendering should be active. I am not sure whether or not VSYNC gets activated as well when doing SDL\_CreateWindowAndRenderer().

So what could possibly be the cause? Is it due to cascading rounding errors? Is it due to the active VSYNC and the manual framerate cap at the end of the loop? What is it exactly that is causing the stutter?

PS: And for the possibility that my Vector2 template class needs attention as well, there you go:

```
/* 2D math classes */
namespace oki2d::math2d
{
    // Vector2 class definition
    template <typename T>
    struct Vector2
    {
    public:
        T x{};
        T y{};
        explicit Vector2() : x{}, y{}
        { }
        explicit Vector2(T t_value) : x{ t_value }, y{ t_value }
        { }
        explicit Vector2(const T t_x, const T t_y) : x{ t_x }, y{ t_y }
        { }
        explicit Vector2(const Vector2 & t_v) : x{ t_v.x }, y{ t_v.y }
        { }
        Vector2 & operator=(const Vector2 & t_rhs)
        {
            if (&t_rhs == this)
            {
                return *this;
            }
            x{ t_rhs.x };
            y{ t_rhs.y };
            return *this;
        }
        Vector2 operator-() const
        {
            return Vector2{ -x, -y };
        }
        bool operator==(const Vector2 & t_rhs) const
        {
            // Perform single-precision floating-point comparison (float)
            if (std::is_floating_point<T>::value)
            {
                return (std::fabsf(static_cast<float>((*this).x - t_rhs.x)) < std::numeric_limits<float>::epsilon())
                    && (std::fabsf(static_cast<float>((*this).y - t_rhs.y)) < std::numeric_limits<float>::epsilon());
            }

            assert(std::is_floating_point<T>::value == false);

            // Perform integer comparison otherwise
            return x == t_rhs.x && y == t_rhs.y;
        }
        bool operator!=(const Vector2 & t_rhs) const
        {
            return !((*this) == t_rhs);
        }
        const Vector2 & operator+=(const Vector2 & t_rhs)
        {
            if (&t_rhs == this)
            {
                return *this;
            }
            x += t_rhs.x;
            y += t_rhs.y;
            return *this;
        }
        Vector2 & operator-=(const Vector2 & t_rhs) const
        {
            if (&t_rhs == this)
            {
                return *this;
            }
            x -= t_rhs.x;
            y -= t_rhs.y;
            return *this;
        }
        Vector2 operator+(const Vector2 & t_rhs) const
        {
            return Vector2{ x + t_rhs.x, y + t_rhs.y };
        }
        Vector2 operator-(const Vector2 & t_rhs) const
        {
            return Vector2{ x - t_rhs.x, y - t_rhs.y };
        }
        Vector2 operator*(const T t_rhs) const
        {
            return Vector2{ x * t_rhs, y * t_rhs };
        }
        Vector2 operator/(const T t_rhs) const
        {
            return Vector2{ x / t_rhs, y / t_rhs };
        }
        static T double_length(const Vector2 & t_v)
        {
            return t_v.x * t_v.x + t_v.y * t_v.y;
        }
        static T length(const Vector2 & t_v)
        {
            return std::sqrt(t_v.x * t_v.x + t_v.y * t_v.y);
        }
        static Vector2 normalize(const Vector2 & t_v)
        {
            const T len{ length(t_v) };
            return Vector2{ t_v.x / len, t_v.y / len };
        }
        static T dot_product(const Vector2 & t_lhs, const Vector2 & t_rhs)
        {
            return t_lhs.x * t_rhs.x + t_lhs.y * t_rhs.y;
        }
        friend std::ostream & operator<<(std::ostream & t_os, const Vector2 & t_v)
        {
            t_os << "(" << t_v.x << ", " << t_v.y << ")";
            return t_os;
        }
    }; // Vector2

    // Using declarations
    using Vec2i = Vector2<int>;
    using Vec2f = Vector2<float>;
} // oki2d::math2d

```

It is just a simple templated 2D vector math class. Nothing scary.

# Answer
> 7 votes
As Alexandre Vaillancourt in the comments suggested:

* it is caused by the conversion from float to int (rounding errors).
* It might also be caused by the fact that I used SDL\_Delay() earlier to cap the framerate.
* It is apparently unreliable since it doesn't wait the specified amount of time in an accurate fashion.

So the two issues that needed attention were:

**1. The conversions from float to int
2. And possibly: Using SDL\_Delay() to achieve the framerate cap\****

Many tutorials on the web seem to achieve the framerate cap via a combination of SDL\_Delay() and SDL\_GetTicks().

I will do it differently, since this is what helped me to get a steady and fluid motion. So here it goes:

* What to do you do instead? Well, you want 1 frame to be 16 ms long (that is, if you are aiming to realize the frequency of 60 Hz -- 60 FPS).
* Thus, you need to wait until the 16 ms is up and only then execute your routines be it rendering, physics or animation.
* IOW: execute the routines iff the 16 ms have passed.

I used an if block to make the execution depending on the minimum cycle time of 16 ms.

For the time measurement I made a small utility class/struct inspired by Salajouni:

```
struct Timer
{
    Uint64 previous_ticks{};
    float elapsed_seconds{};

    void tick()
    {
        const Uint64 current_ticks{ SDL_GetPerformanceCounter() };
        const Uint64 delta{ current_ticks - previous_ticks };
        previous_ticks = current_ticks;
        static const Uint64 TICKS_PER_SECOND{ SDL_GetPerformanceFrequency() };
        elapsed_seconds = delta / static_cast<float>(TICKS_PER_SECOND);
    }
};

```

You need to collect/accumulate the seconds in each iteration. The steps that you need to take then are: accumulating the seconds of each iteration (hence the variable name accumulator), then make a float comparison either with an epsilon comparison (float\_val1 - float\_val2 \< epsilon, epsilon = 0.00001f) or just use std::isgreater() or std::isless() for that.

Then, accumulating the seconds until you reach the cycle time you need e.g. 16 ms. (And again: do not forget to reset the accumulator inside the if block. It needs to recount to the 16 ms every time. I reset it with -CYCLE\_TIME)

```
int main()
{
    /*--------------Game loop--------------*/
    // Timing constants
    const int UPDATE_FREQUENCY{ 60 };
    const float CYCLE_TIME{ 1.0f / UPDATE_FREQUENCY };
    // System timing
    static Timer system_timer;
    float accumulated_seconds{ 0.0f };
    while (is_running)
    {
        // Update clock
        system_timer.tick();
        accumulated_seconds += system_timer.elapsed_seconds;

        /*--------------Event loop--------------*/
        /* ... */

        // Cap the framerate
        if (std::isgreater(accumulated_seconds, CYCLE_TIME))
        {
            // Reset the accumulator
            accumulated_seconds = -CYCLE_TIME;

            /*--------------Physics loop--------------*/
            static Timer physics_timer;
            physics_timer.tick();

            bot.position.x += bot.direction.x * bot.speed * physics_timer.elapsed_seconds;
            bot.position.y += bot.direction.y * bot.speed * physics_timer.elapsed_seconds;

            // Screen coordinate translations
            /* ... */

            ground.update();
            bot.update();

            // Camera
            /* ... */

            /*--------------Rendering loop--------------*/
            SDL_RenderClear(ren);
            ground.draw(ren);
            bot.draw(ren);
            SDL_RenderPresent(ren);

            /*--------------Todo: Animation loop--------------*/
            static Timer animation_timer;
            animation_timer.tick();

            /* ... */
        }
    }

    // Clean up used resources
    /* ... */
    SDL_Quit();
    return 0;
}

```

Note that I left out some code parts to make it easier to follow.

Hope it helps! :)

**Tl;tr: <br>* Accumulate floats instead of using SDL\_Delay() and do not attempt to convert floats to integers carelessly.
* Avoid conversions by constructing a timer class that is based on float.
* Then do a float comparison via an epsilon comparison or via std::isgreater()/std::isless().**

---
Tags: c++, sdl2
---


# Question
Title: Importing audiofile into Unity3d gets shown after ending playmode
I am working on a game where the user has the possibility to import custom audio tracks that can be listened to during the game.

For this I am making use of System.IO.File.Copy method. This works, there are no issues or flaws here. When I inspect the target and destination folder the file(s) get copied properly and show up in the folder.

The issue however is that the Unity Editor doesn't show the file despite it actually being there. During play mode in the Unity editor the new file isn't shown in the resources folder (which I use as destination for now). When I use windows file explorer I can clearly see the file in the corresponding folder. Using debugs (in Unity) also state that the folder is empty, however when I use debugs outside of Unity it shows that the folder contains the copied item. Keep in mind that these both debugs are called roughly at the same time. I have tested this in many ways to be 100% certain that Unity doesn't see the file, while it is there.

So once I stop playmode it starts loading/importing/processing the new file and then it shows up in the folder in unity as well. When I launch playmode after this the file is indeed loaded and included in the game as well.

I however need this to happen without having to stop playmode. So there is probably some type of processing that I haven't called for Unity to process the addition of the new file and for it to be visible.

So in a nutshell basically copying a file from folder to folder isn't enough for Unity to directly utilized in the same play session (and all after). How can I make the audio-file directly showable and accessable?

There aren't any errors or warnings. The file plays correctly after it has been processed. I am at a loss with this issue/bug.

# Answer
The comment from DMGregory made me realize that it was the compiler that was processing the new added file. This however only happens outside of playmode and only in the editor. With this came the other knowledge of the Resources folder not being editable in a build. And for me this would be a huge issue since players need to be able to add their own custom soundtracks.

So I actually had 2 issues ongoing without being aware of the second one.

The solution to this was fairly simple, but I wasn't aware of its existence; StreamingAssets. The StreamingAssets folder stays intact and remains editable. This is in a build and in the editor. After making a build you can see the StreamingAssets folder in the *\[gamename\]\_Data* folder. Using a www form in a coroutine I managed to get the newly added soundtrack to the library of soundtracks and made it directly usable for the player. Mainly this website gave me a lot information about how to utilize StreamingAssets.

I hope this will help future programmers that are going through the pain of making an option for the player to add custom audioclips.
> 1 votes

---
Tags: unity, loading, file, processing
---


# Question
Title: How can I speed up the shapes drawing on high-density devices?
I have a game that should draw many shapes on the canvas and in every frame these shapes position will change, the game is running smooth but after adding more shapes some jerk arise and it drops some of frames. And this is just happening in high-density devices (more than 320 dpi).

```
public void run() {
    while (mRunning) {
        if (mSurfaceHolder.getSurface().isValid()) {

            synchronized (mSurfaceHolder){
                canvas = mSurfaceHolder.lockCanvas();

                canvas.drawColor(Color.BLACK);
                drawOnCanvas(canvas);

                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

```

draw function

```
public void drawOnCanvas(Canvas canvas) {
    new Thread(changeGamePosRunnable).start();

    for (int i = 0; i < obstacles.size(); i++) {
        Obstacle obstacle = obstacles.get(i);
        x= obstacle.getX();
        y=obstacle.getY();

        canvas.drawLine(0, 0, x, y, linePaint);
        canvas.drawBitmap(bitmap,x,y,null);
    }
}

```

I have created bitmaps in the constructor, initializing all variables out of the game loop, using `SurfaceView` and implements `Runnable`, added `Thread.sleep(5);` to `while` loop, tried to decrease bitmap size to about 240 bytes, tried to draw circle instead of bitmap again no change.

It's so strange that the drawing function is so slow in high-density devices, I tried to use some bitmaps as buffer and use them in 3 threads but the game sometimes draw on the wrong location. also I think drawing on another bitmap is not a right solution.

How can I speed things up? The quality does not matter, I just need some more speed.

# Answer
You are drawing using the cpu to write pixel per pixel. Instead go hardware accelerated by using opengl or vulkan.

That will allow you to use the gpu which is optimized for drawing stuff that ends up on screen.
> 1 votes

---
Tags: java, android, game-loop
---


# Question
Title: Migrating 2D game from immediate mode to VBOs
I am in the process of migrating away from legacy OpenGL calls in my 2D LWJGL game. Previously I would render each sprite using immediate mode, which was dead easy - bind the texture, add the vertices, and it's done.

Now I want to use vertex arrays. Ideally I would put the vertices for ALL my entities in one big array and render it in a single draw call. The problem? Each entity type uses a different texture, and `glDrawArrays` uses just one texure at a time.

Here are some possible solutions I came up with:

# 1) Create a separate vertex array for each entity

This is by far the easiest solution, but it somehow seems wrong to me, because it's so similar to using immediate mode. Doesn't this defeat the benefit of using vertex arrays?

# 2) Create a separate vertex array for each entity *type*

In other words, all entities that have the same texture will be rendered together. This isn't ideal as it would involve a good chunk of extra work and some extra effort on the CPU to separate the entities by type, and more importantly, would affect the z-ordering of the entities.

For example, it would be impossible to have a Tree that appears in front of one Squirrel but behind another Squirrel.

That is, unless I introduced a depth buffer, but I was trying to avoid this as it adds another level of complexity and, as I understand it, more work on the GPU (although that probably doesn't matter too much).

# 3) Combine all textures using a texture atlas

If I was able to use a single texture for all entities, I could use a single vertex array. However, there are 2 problems with this:

1. I have not been able to find a good library for creating a texture atlas at runtime, and writing this code myself would be non-trivial.
2. I am worried that some GPUs may have a prohibitively small texture size limit.

# Summary

* Would the first solution be viable / advisable?
* Am I being foolish for trying to avoid using the depth buffer?
* Am I missing something here? Is there a better solution?

# Answer
> 1 votes
Having spent a not-insignificant amount of time rewriting my rendering code, here is what I would like to tell my past self...

# Immediate Mode vs. "Modern" OpenGL

* Immediate mode is terrible practice; migrating away from that cannot be a bad thing.
* If you are migrating in order to support MacOS, don't bother; they have stopped supporting OpenGL altogether.
* OpenGL is still a valid choice.

# VAO Strategy

* There is no "right" solution; some may be more efficient than others, but for a simple 2D game, they are probably all viable; graphics processing is not going to be a huge strain on the GPU, even with a sub-optimal approach.
* Switching textures is expensive! Consider rendering by texture.
* Fewer VAOs is always better.
* Start simple, and optimise later if required.

# Depth Buffer

---
Tags: opengl, textures, rendering, lwjgl, vbo
---


# Question
Title: How can I efficiently change the color of a BufferedImage?
I am trying to change the color of a white `BufferedImage` image.

I do know that you can use `.setRGB(x,y,rgb)` and simply run some nested `for` loops and make changes to one pixel at a time. However, the problem arises when it comes to gradually changing the color instead of instantly doing so. This means I would have to run thousands of loops every runtime, completely ruining the frame rate.

My question is, is there a way to just change the color of an image right away?

# Answer
> 0 votes
It depends a bit on what you're specifically trying to do.

If you want to change all of the pixels to a single new color, then most likely the fastest & easiest way is something like this:

```
int width = 512;
int height = 512;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2d = image.createGraphics();
Color darkOliveGreen = new Color(85, 107, 47);
g2d.setColor(darkOliveGreen);
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());

```

Note, the above code can also be modified to deal with rectangular subsections of the image.

On the other hand, if you need to quickly evaluate & process the pixels individually for some reason (i.e. change the reds to greens, the greens to blues & the blues to reds), then you'll need to manually access the data buffer that backs the image:

```
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

```

From there you can manipulate the pixels quickly without the overhead of issuing a method call for each read & write. The downsides to this approach are:

# Answer
> 2 votes
I think one solution is to use `Graphics2D#setXORMode(Color)` but I do not know if it will increase performance, since it requires you to create a new `BufferedImage`. Probably worth a shot, though:

```
public BufferedImage tintImage(BufferedImage image, Color color) {
    BufferedImage tintedImage = new BufferedImage(
                                    image.getWidth(),
                                    image.getHeight(),
                                    BufferedImage.TYPE_INT_ARGB);

    Graphics graphics = tintedImage.createGraphics();
    graphics.setXORMode(color);
    graphics.drawImage(image, 0, 0, null); // NOT 'tintedImage'
    graphics.dispose();
    return tintedImage; // Image will be tinted
}

```

This is all from memory & javadoc so if that code does not work try to change these things:

* Set `color` alpha to 0 (`color = new Color(color.getRed(), color.getGreen(), color.getBlue(), 0)`).
* Change `BufferedImage.TYPE_INT_ARGB` to `BufferedImage.TRANSLUCENT`.

---
Tags: java, color
---


# Question
Title: Does a successful attempt count as an attempt?
I'm writing a video game and I'd like to know if I should include the "successful" attempt in the count of "total attempts".

For instance, in a clay shooting game, if the player needs four shots before they hit the target:

bullet one = miss
bullet two = miss
bullet three = miss
bullet four = hit

Does it equate to three attempts, or four attempts? What text do I need to write at the end of the round?

> You needed *three* attempts to hit the target!

or

> You needed *four* attempts to hit the target!

# Answer
> 3 votes
According to dictionary.com:

> **attempt**
> noun, an effort made to accomplish something

So based on this, something like

> You needed 4 attempts to hit the target!

would make more sense because the player had to make an effort four times in total.

---

Now, that might not be the most question to ask. We need to take into consideration the context in which this will be used.

If the fact that they failed many times before succeeding is important in your context, for instance if the "ratio" of "hit" vs "miss" is important because you're keeping stats, you may want to present it with the failed attempts too:

> You had 3 failed attempts before hitting. Your score is 25%.

or we could get rid of the concept of "attempts":

> You missed 3 times before hitting. Your score is 25%.

Highlighting the fact that they missed 3 times before hitting might help the players see what you want them to see.

In any case, whatever you choose, you should have your game tested by multiple people and see if they understand clearly the information you try to transmit; adapt your user interface as required.

---
Tags: gui
---


# Question
Title: How can I reduce a bezier curve using a slider till all points converge to it's original midpoint
I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet).

I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves. I would like achieve this using a `float` slider (with values from 0 to 1) in editor mode.

# Answer
> 4 votes
Assuming you have a cubic Bezier curve type with control points `a`, `b`, `c`, `d`, and methods to evaluate, given a parameter `0 <= t <= 1`, both:

* a position on the curve at `t`

ie. \\$\vec p = (1-t)^3 \vec a + 3 t (1-t)^2 \vec b + 3 t^2(1-t) \vec c + t^3 \vec d\\$
* the first derivative of that position with respect to the parameter `t`

ie. \\$\frac {\delta \vec p} {\delta t} = 3 (1-t)^2 (\vec b - \vec a) + 6 t (1-t) (\vec c - \vec b) + 3 t^2 (\vec d - \vec c)\\$

Then we can choose new control points for an arbitrary interval `start <= t <= end` on this curve like so:

```
static CubicBezier IntervalFromTo(CubicBezier curve, float start, float end) {

    float scale = (end - start)/3f;

    var a = curve.PositionAt(start);

    var b = a + curve.DerivativeAt(start) * scale;

    var d = curve.PositionAt(end);

    var c = d - curve.DerivativeAt(end) * scale;

    return new CubicBezier(a, b, c, d);
}

```

If you have a `size` parameter that runs between `0` (just the midpoint) and `1` (the whole original curve), then you can compute your symmetrical subset as a special case:

```
subsetCurve = IntervalFromTo(originalCurve, 0.5f - 0.5f * size, 0.5f + 0.5f * size);

```

I recommend that you keep your `originalCurve` unchanged throughout this manipulation, and make a fresh `subsetCurve` from the original each time something changes, rather than overwriting your original with each change. Keeping this separation will ensure you don't get unwanted vibrations or degradation due to accumulating rounding errors.

---
Tags: unity
---


# Question
Title: Rain Effect generation in a Unity VR project
I´m developing a VR project in Unity Engine and I need to implement a Rain Effect. I have considered the following:

* A VR game must run at least 90 frames per second.
* The Rain must be detailed.
* The Rain Drops interact with other objects.

These are the approaches I have considered:

* Particles Systems: I think it is expensive since there are two cameras rendering the scene and checking collision per particle could be expensive.
* Image Effect on the canvas: I think the result would be unreal, and there would not be interaction with other objects.

I have seen examples of rain effect like in Resident Evil 4, Halo Reach, Crysis, FarCry, Project Cars 2 VR and Batman Arkham Knight.

A last approach I haven´t considered yet is by shading, maybe shading would work for the rain drops in the cameras´ lens.

I would like to know optimal approaches to emulate rain effects without making too much computations.

Thanks for your attention.

# Answer
# Particle collisions are super fast

That was one of the requirements Unity had when they added them in 4.0.0

> From the blog
>
> With Unity 4.0 we are adding support for world particle collsion detection. It’s quite awesome and very fast.
>
> We spent a lot of time optimizing world particle collisions and also did more than a few optimizations to Shuriken in general. Especially on mobile devices Shuriken got a very big performance boost.
>
> **Multithreading**
>
> Shuriken is multithreaded and so is collision detection.

So this should be fine, even for VR.
> 1 votes

---
Tags: unity, shaders, particles, virtual-reality, image-effects
---


# Question
Title: Input events slow on unity Update function
I have this running on the Update() on Unity. I am trying to create a page swipe feature on my game, but the problem is there is a half second delay when printing "dragging" to "end drag" when I release the mouse.

Does anyone have a method that will register input events faster?

```
void Update()
{
    if(isDragOn)
    {
        if(Input.GetMouseButton(0))
        {
            print ("dragging");
            //moveContainers((Input.mousePosition.x - mouseLastPosition) * 0.01f);
            mouseLastPosition = Input.mousePosition.x;
        }
        else if(Input.GetMouseButtonUp(0))
        {
            print ("end drag");
            isDragMoved = false;
            isDragOn = false;
            endDrag();
        }
        else if(Input.touchCount > 0)
        {
            if(Input.GetTouch(0).phase == TouchPhase.Moved)
            {
                //moveContainers(Input.GetTouch(0).deltaPosition.x);
            }
            else if(Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                isDragMoved = false;
                isDragOn = false;
                endDrag();
            }
        }
    }
}

```

# Answer
There isn't going to be something "faster" than `Update`(reference), that runs once per frame:

> Update is called every frame, if the MonoBehaviour is enabled.

If your frame rate is half a second per frame, then you'll get a half second delay. You'll need to perform some optimizations if you want faster response. Make sure your MonoBehaviour is enabled, and you're not running `Update` as part of a Coroutine. You can try creating a new project, and just putting your code into a new script on an otherwise empty object.
> 4 votes

# Answer
The mouse input can be theoretically speed up by using a callback-based input API. Because polling-based input API is going to be delayed from the actual input no matter what. Depending on the timing of the hardware, imagine at this moment the `Update` just passed but you are not yet at the rendering routine. If you were using callback-based input you would have 1 frame advantage and able to update the graphic in time. Unity have keep this callback data for the next frame.

Unity's New Input System is callback-based. But currently (9/9/2018) as far as I tried the callback does not occur at an arbitrary time but queued up and batched together and present the callback to you in the loop, before all `Update()`. There might be a way to ask the "queued up" data in the future when the API is being finalized, so I think it worths looking out for.

Because I see some touch code I am assuming you might also want the solution to work with touch input. If you use Native Touch you can receive the native touch callbacks as soon as the touch happen, which could be faster than waiting for `Update`. If you want the same input workflow as native app developement you might want to check it out.
> 0 votes

---
Tags: unity, input, events
---


# Question
Title: Unity: OnTrigger detection issue with Child of Prefab
I'm trying to make a set of tiles on the floor of my 3d world visible only when the Player is nearby them. This will work as single tile prefabs. Just not if I set them within an empty parent gameobject... which is what I really need, ideally, for the sake of game performance.

Once I put them inside the empty parent gameobject, OnTrigger stops working or even registering (debug.log doesn't show anything).

Does anyone know the correct way to access and switch the MeshRenderer on/off via OnTrigger (or OnCollision might be even better... I've tried and same issue) when I have a LevelManager that loads all my game objects at runtime? The Level Manager instantiates a prefab (clone), which has an empty gameobject that's holding the tiles as children?

Code I've tried and that's not working so far:

```
public class CubeVis : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

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

    }

    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("hit");
        if (other.gameObject.CompareTag("Cube"))
        {
            Debug.Log("hittt");
            //other.gameObject.GetComponentInParent<MeshRenderer>().enabled = true;
           // other.gameObject.GetComponentInChildren<MeshRenderer>().enabled = true;
            //other.gameObject.GetComponent<MeshRenderer>().enabled = true;

        }
    }

```

Inspector/Hierarchy info as requested:

# Answer
Based your newest comments, here's another suggestion for a solution to your problem.

The idea is that you use a `OverlapSphere` to find all colliders on a specific **layer** within a certain range. Then you can use the dot product between the direction the player is looking, and the direction towards the collider. Finally you sort these by the distance to the player (may not be necessary, do a test), and enable the mesh renderer.

### TileManager.cs

Attach the script to the player, and assign a tag and layer to your tiles. See the screenshots.

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

public class TileManager : MonoBehaviour
{
    public string tileTag;
    public LayerMask tileLayer;
    public float maxDistance = 50.0f;
    public int maxVisibleTiles = 3;

    private List<MeshRenderer> tileMeshRenderers = new List<MeshRenderer>();

    private void Start()
    {
        // find all game objects with the specified tag,
        // and save their mesh renderer in a list for later
        var tiles = GameObject.FindGameObjectsWithTag(tileTag);
        foreach (var tile in tiles)
        {
            tileMeshRenderers.Add(tile.transform.GetComponent<MeshRenderer>());
        }
    }

    private void Update()
    {
        // disable all mesh renderers
        foreach (var meshRenderer in tileMeshRenderers)
        {
            meshRenderer.enabled = false;
        }

        // find tiles within range
        var hits = Physics.OverlapSphere(transform.position, maxDistance, tileLayer);
        var visibleHits = new List<Collider>();

        // filter the hits
        foreach (var collider in hits)
        {
            // use dot product to check if the collider's pivot is within a 180 degree fov
            if (Vector3.Dot(transform.forward, collider.transform.position - transform.position) > 0)
            {
                visibleHits.Add(collider);
            }
        }

        // order the hits by the distance to the camera
        visibleHits = visibleHits.OrderBy(x => (x.transform.position - transform.position).sqrMagnitude).ToList();

        // enable the 3 closests mesh renderers
        var indices = visibleHits.Count > maxVisibleTiles ? maxVisibleTiles : visibleHits.Count;
        for (int i = 0; i < indices; i++)
        {
            visibleHits[i].GetComponent<MeshRenderer>().enabled = true;
        }
    }
}

```
> 0 votes

# Answer
Your description was a little confusing, but I gather that you want to enable one or more MeshRenderer components, when the player enters a trigger.

1. First of all, make sure your player game object has a RigidBody and a Collider. Then assign some tag to your **player** \- in my example I've used the `Player` tag.
2. Then, your trigger object needs a Collider that has `IsTrigger` enabled (which I think you've done). There's no need to set a tag on the trigger box.
3. Assign the sample script `TriggerSample.cs` to your trigger object, not the player. If the player now enters the trigger object, the MeshRenderer on the trigger object is enabled.
4. If you want to enable other game objects in your scene, you can drag them into the array `ObjectToEnableOnTrigger` in the inspector on the trigger object.

I have attached screenshots of the scene hierarchy, the player (the slim cube) and the trigger object (the big cube).

### TriggerSample.cs

```
using UnityEngine;

public class TriggerSample : MonoBehaviour
{
    // array of MeshRenderers - assign them in the inspector
    public MeshRenderer[] ObjectsToEnableOnTrigger;

    // place this on the object you want to enable
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            // enable the MeshRenderer on THIS game object
            // this is the same as transform.GetComponent<>()
            // it is good practice to check for null
            var thisRenderer = GetComponent<MeshRenderer>();
            if (thisRenderer != null)
            {
                thisRenderer.enabled = true;
            }

            // this will enable all the MeshRenderers assigned in the inspector
            foreach (var meshRenderer in ObjectsToEnableOnTrigger)
            {
                meshRenderer.enabled = true;
            }
        }
    }
}

```
> 1 votes

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


title: Animation clip not working

text:
# Question
Title: Animation clip not working
I am working on playing different animation of key press.Below are the animation element attached to my player

Initially run animation is played.I have written code to play "Jump" animation on keypress.

The problem is that when I press the key "Jump" animation will be played,But this animation is played again and again.

I need to play the "Jump" animation only once.Then I need to switch to run animation

Here is the code written

```
public bool run=false;

void Update () {
    if(Input.GetKey(KeyCode.R))
        {
        run = true;

        }
    if (run == true) {

        GetComponent<Animation>().Play("Jump");
        GetComponent<Animation>().wrapMode = WrapMode.Loop;
    }
}

```

# Answer
at the moment the loop that run the Jump animation is infinite because

```
if (run == true) { // this condition is always TRUE once the player press R.

```

we can avoid it by changing that into a diffrent boolean that doesnt effect the running animation itself as I can only guess that when RUN equals TRUE the player is running so the following code should solve this problem.

```
public bool run = false;

void Start () {

}

void Update () {
    if(Input.GetKey(KeyCode.R))
        {
        run = true;
        GetComponent<Animation>().Play("Jump");
        GetComponent<Animation>().wrapMode = WrapMode.Loop;
        }
    }

```
> 0 votes

# Answer
if you want play once Jump animation you can use Input.GetKeyUp for falsing condition.your way isn't correct because you Check condition in Update function.In update function while condition is true do your work. using UnityEngine; using System.Collections;

```
public class AnimationComponent : MonoBehaviour {

        void Start () {
            GetComponent<Animation>().Play ("Walk");
        }

        void Update () {
        if (Input.GetKeyDown (KeyCode.R)) {
            GetComponent<Animation> ().Play ("Run");
            GetComponent<Animation> ().wrapMode = WrapMode.Loop;
            }
        if (Input.GetKeyUp (KeyCode.R)) {
            GetComponent<Animation> ().Play ("Walk");
        }
    }
}

```
> 0 votes

# Answer
There are parts of both Seyed's answer and Daniel's answer that are correct.

However, I would advocate for different code.

For example, Daniel does this:

> ```
> public bool run = false;
>
> void Update () {
>     if(Input.GetKey(KeyCode.R)) {
>         run = true;
>         GetComponent<Animation>().Play("Jump");
>         GetComponent<Animation>().wrapMode = WrapMode.Loop;
>     }
> }
>
> ```

Which doesn't fix the issue that `run` will be true forever (the identified problem). All it does is make the effects of that no longer dependent *on* it.

Instead, I would suggest this:

> ```
> void Update () {
>     bool run = false;
>     if(Input.GetKey(KeyCode.R)) {
>         run = true;
>     }
>     if(run) {
>         GetComponent<Animation>().Play("Jump");
>         GetComponent<Animation>().wrapMode = WrapMode.Loop;
>     }
> }
>
> ```

Which makes the scope of `run` *function scope* rather than *class scope* (which lets it reset) or use an `else` statement that resets it, or remove it entirely (as doing it purely based on the input is fine, just that the field is no longer relevant). What you do depends on whether or not you're accessing that field from outside the class or in another method.

Then, both Daniel and Seyed are still using `Input.GetKey(KeyCode.R)`, which means that the key is not rebindable and if you ever decide that "You know what, I don't want Run to be R, I want it to be Left Shift" you have to change it inside your code *anywhere and everywhere* you're using `KeyCode.R`.

Instead use `Input.GetButton("Run")` and use the input settings (Edit -\> Project Settings -\> Input) menu to configure your keyboard input. Alternatively you can get an asset like Rewired that allows you to do key rebinding *in game* rather than Unity's setup which prompts the user *before the game* and looks wholly unprofessional (and it only works for Windows and Mac builds, webgl and console builds won't show it and your keybinds are again permanent).
> 0 votes

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


# Question
Title: Unity 3d texture animated round circular bar
I'm struggling to create a circular bar with an animated texture and a round cap end. What I would like to create is implemented in the Unity game Subnautica - the bottom left bar. So here is the HUD from the game. The problem is that I don't know how to animate texture with the round end. I can fake it with basic colors but I need it to have animated texture.It is possible to make this using shader because i hadn't tried that. Or are there maybe some assets in the store?

# Answer
> 0 votes
Going to plug my $2 shader asset, its not required to get this to work, but it will look better (this is due to alpha cutoff works).

### Step 1: make your texture.

Your texture will need to have the circular graphic you want to display and then you need to fiddle with the alpha so that it has the curved feature you want. I'm going to spend no more than 10 minutes trying to do this, so results may not be perfect.

You want it so that the low end of your bar is 100% opaque and the high end (the 100% full portion) to be 1% opaque (almost completely invisible). Not fully transparent, as you still want there to be bits available for the portions of the texture you won't be using at all.

Something that looks like this on the alpha:

This wasn't perfect, the first third of the bar is perfectly white (limits of the tool I was using), but it gives you the right idea.

Then the final image will look like this:

The curved portion of the bar as it fills in isn't 100% accurate here either, but I did say no more than 10 minutes.

You will also want a background texture that will display behind (and around) the bar. I'm going to skip that for this example.

### Step 2: set up your material

Create a material, assign your texture, set the shader to Unlit -\> Transparent Cutout, add a quad to your scene with the material applied.

You may also be able to use it as a UI sprite material, I haven't fiddled around with those much because the shaders tend to vomit errors when they don't have some settings that the UI expects. I think I fixed it completely once, here. The six `[HideInInspector]` lines and the `Stencil` block are what need to be added to make a shader work properly on UI components. Should work for any shader, though I've not tested extensively. Unity built-in shaders (e.g. AlphaCutout) can be downloaded in the archive, just change the dropdown from "Downloads" to "Built-in Shaders."

### Step 3: profit

You're done!

My alpha shaders will make those ugly jaggies go away by blurring the edges slightly (configurable, I suggest small values of around 0.02) and then some care regarding the setup of the alpha channel and you can get some pretty good results. Asset is $2 because I can't make it $1, if you know what you're doing you can recreate the shaders in a half hour or so (and if you don't, that's why it's $2 ;). Layer a mask on top (link is for UI sprites) and you can constrain the filled part's edges even better.

It probably won't be 100% to Subnautica's bar, as it has an outline applied that this method can't replicate, but you can get something pretty close for almost no work.

This question inspired me to go back to my shader asset and add two new textures for circular progress bars, including a much refined version of what you're looking for (the leading edge is much more circular). The entire process of creating the correct and accurate alpha composite took about 3 hours. Here's the end result (with blend range of 0.03 so you can see some of the progression). Note that the black border is a second texture giving the bar a background to sit inside.

# Answer
> 0 votes
In the Unity documentation there is an **Image.Type.Filled** component. The description says:

> Displays only a portion of the Image.
>
> A Filled Image will display a section of the Sprite, with the rest of the RectTransform left transparent. The Image.fillAmount determines how much of the Image to show, and Image.fillMethod controls the shape in which the Image will be cut.
>
> This can be used for example to display circular or linear status information such as timers, health bars, and loading bars.
>
> See Also: Image.FillMethod, Image.fillAmount, Image.fillOrigin.

---
Tags: unity, shaders, gui
---


# Question
Title: How can I ensure my Direct3D 11 shader scripts are not visible to the user?
Right now for my engine, I rely on pixel and vertex shader script text files that I load and compile when I need them.

What I am wondering is, how can I store the shader scripts so that they are not visible to the user?

Maybe I could hard code them inside the executable, then dump them to .ps and .vs files, compile them, and then delete those files?

Or I could place them in binary files along, say, level or model data, and then generated/compiled in that same way?

Or would I pack them as text files inside a proprietary compressed file format with all the other resources, that is uncompressed and loaded as needed?

I'd like to avoid storing them in a way that's hackable or easy to reverse engineer.

# Answer
There are multiple ways the shader scripts can be hidden from the user - the graphics api used doesn't matter much.

The shader files could

* be added in some obscure subfolder as plaintext files. Most non-power users won't bother searching around. Most power users won't be stopped by this and most other techniques I'm going to explain.
* just be renamed with another extension so they're not identified as textfiles by the operating system. Anyone could still open them in a text editor though.
* be included in a header/source file as a string/literal/character array. The shader gets compiled into the program and is hidden in the executable file (can still be seen in a hex editor). The shaders would then get loaded from the variable in program memory instead of from a file.
* compressed into an archive file. Some games use compressed files (e.g. \*.zip, or the \*.pak files of doom/quake) to collect multiple resources into one file. The compressed files are opened and uncompressed by the executable and get used as a virtual file system, from which the shaders are loaded.
* added into resource files, e.g. some engines store the shader source as part of the asset metadata.
* transformed into an intermediate format. Many graphics apis provide a way to compile shaders into binary files, e.g. using fxc.exe on directx or SPIR V on opengl/vulkan. Since the binary formats are standardized, reverse engineering is still possible.

Of course, any of the above can be combined with cryptographic methods. A simple scheme like ROT13 or BASE64 can be used to encrypt the shader source, which will make the shaders harder to find and keep out the script kiddies, but won't deter anyone really serious about finding out how the rendering works. Harder encryption schemes would be getting into cryptography.stackexchange.com territory though. Due to the time needed to decrypt the files, this approach isn't used often.

Also something to consider: Making it harder to modify the games asset and shader files also makes it harder to mod the game. Which can be a good or bad thing.

Most rendering techniques are available in research papers and/or other sources one way or another, so many games just throw shaders into an asset file or folder and focus on providing a good gameplay experience.
> 1 votes

---
Tags: shaders, directx11
---


# Question
Title: How to update UI after changing text in a view
After applying a text change to a scrolling view, how do you get the new height of the text, resize other UI elements around the changed text length, etc?

Many have posted this question. Some have noted that the rect size doesn't change or that they have to wait multiple frames to then react to the UI updates.

# Answer
> 3 votes
This is one method of updating a ScrollBar (or anything) after changing the content of ScrollView Text and wanting to react to the new width/height of the text after it is rendered.

Platform: Unity 4.6 / 5 (I'm using Unity 5, but I think I used all 4.6 components), C#

There are a number of videos on how to create scrolling text views for fixed-content:

Unity: https://www.youtube.com/watch?v=tcU8yzv\_xEw

Sloan Kelly's popular: https://www.youtube.com/watch?v=5XJBBWI2F0I

There are a many questions posted of how to resize things / update their UI after changing Text.

How to create scrolling input text field using Unity UI

There are very few answers.

Here is my approach.

Goals:

* Simple to apply to a project.
* Minimize artifacts.
* Minimize impact on performance
* Debug-able for when you get extra fancy

Initially I tried Coroutines and other tricks to try to let the ScrollView update and then capture the new dimensions.

This did not go well.And multi-threading can make testing ugly.

Usage:

Create a root empty GameObject in your scene.I rename it to GlobalTextScript.

Apply the below script to that object.

Create the following GameObject structure in your Hierarchy:

* UI-\>Canvas
    + UI-\>Panel : name "ScrollTextPanel", Anchor: custom(place where you want the scroll view)
        - UI-\>ScrollBar : name "ScrollBarMain", Direction: Bottom to Top(in most cases), Anchor: Alt - Shift Stretch, Right(Rect Transform Width: 20(or to taste)), Value: 1(moves scroll to top)
        - UI-\>Image : name "ScrollBackground", Anchor: Alt - Shift Stretch Stretch(then set Rect Transform Right: \[Match your ScrollBarMain Right Width\])
        - Components: Mask, Scroll Rect(Horizontal: off, Vertical Scrollbar: ScrollBarMain)
        - UI-\>Text: name "ScrollTextMain", Anchor: Alt - Shift Top Left
            * Components: Content Size Filter(Horiz: Unconstrained, Vert: Preferred Size)
            * With this created, go back to ScrollBackground and add ScrollTextMain to the Scroll Rect's Content value

This script at launch:

1. Finds the ScrollTextMain GameObject by name
2. Finds the ScrollBarMain GameObject by name
3. This means you don't have to have them as public variables and drag-and-drop the objects into them in the IDE.
    * I've had the IDE lose those values too many times, I don't trust it and prefer it "documented" in the code what the variable should point to.
    * Grabs the child components it's actually interested in.
4. Since the script immediately will go into an Update cycle, it will wipe your IDE content
    * Start() has some commented out code you can enable to prevent this.

Usage during run time

1. A simplistic Singleton allows access globally through GlobalTextScript.Instance.UpdateText(string).
    * This means if you want multiple text areas managed, you will need to clone this class under a different name
    * Alternately, you can add a bunch of interesting code to hold all the Text and ScrollBar objects and each.UpdateText will need to say what it's target is.
2. That's it.

When.UpdateText(string) is called, it's sets itself up to perform the update over 4 frames.

1st frame: it actually updates the text content of the target.

2nd frame: it waits -- after this frame Unity's UI engine will update the ScrollBar.size value

3rd frame: Your update code goes here as you can now look at ScrollBar.Size and get a valid answer.

3rd frame (b): If you add variables to track the ScrollBackground's Transform, I assume you could look at it's size here too. I haven't tried yet.

4th frame: goes inactive, taking itself out of Unity's Update loop and minimizing impact on perf.

Full GlobalTextScript.cs code:

```
using UnityEngine;
using System.Collections;

public class GlobalTextScript : MonoBehaviour
{
    private GameObject _ScrollTextMain; // if you need to debug in Unity IDE, change this to public
    private UnityEngine.UI.Text _Text;

    private GameObject _ScrollBarMain; // if you need to debug in Unity IDE, change this to public
    private UnityEngine.UI.Scrollbar _ScrollBar;

    private int _FrameCount = 0;
    private string _NewText = string.Empty;

    void Start()
    {
        _ScrollTextMain = GameObject.Find("ScrollTextMain");
        _ScrollBarMain = GameObject.Find("ScrollBarMain");

        _Text = _ScrollTextMain.GetComponent<UnityEngine.UI.Text>();
        _ScrollBar = _ScrollBarMain.GetComponent<UnityEngine.UI.Scrollbar>();

        // On Start, the Update loop is going ot overwrite your scrollview text with _NewText ("").
        // If you have IDE default text you want to preserve, add this line in:
        // gameObject.SetActive(false);
        // or this one:
        // _NewText = _Text.text;
    }

    public void UpdateText(string text)
    {
        // note: an in-progress update will be flat out reset by a new incoming text.
        _NewText = text;
        _FrameCount = 0;
        gameObject.SetActive(true);
    }

    // Once UpdateText is called, over 3 frames, the text scroll view is updated, then the object goes back to sleep so it doesn't need Updates
    void Update()
    {
        switch (++_FrameCount)
        {
            case 1: // update text -- technically can be in the UpdateText function, but this shows the frame flow
                Debug.Log("frame: 1");
                _Text.text = _NewText;
                break;

            case 2: // Unity UI updates _ScrollBar.size AFTER this Update
                Debug.Log("frame: 2, size: " + _ScrollBar.size);
                break;

            case 3: // update ScrollBar
                Debug.Log("frame: 3, size: " + _ScrollBar.size);
                _ScrollBarMain.SetActive(_ScrollBar.size < 0.995);
                break;

            case 4: // go back to sleep
                Debug.Log("frame: 4");
                gameObject.SetActive(false);
                break;
            default:
                Debug.LogError("GlobalTextScript is on frame: " + _FrameCount);
                break;
        }
    }

    #region Simple Singleton
    public static GlobalTextScript Instance;

    void Awake()
    {
        Instance = this;
    }
    #endregion Simple Singleton
}

```

A quick Demo:

Start a new project, and add the GameObjects outlined above, then:

1. Create a new script called TestAction.cs

Put this code in it:

```
public class TestAction : MonoBehaviour
{
    private int _Count = 0;

    public void OnClick()
    {
        _Count = (_Count + 1) % 3;
        Debug.Log("count: " + _Count);
        switch (_Count)
        {
            case 0: GlobalTextScript.Instance.UpdateText("Testing..."); break;
            case 1: GlobalTextScript.Instance.UpdateText("Testing...\n1\n2\n3\n4\n5\n6"); break;
            case 2: GlobalTextScript.Instance.UpdateText("Testing...\n1\n2\n3\n4\n5\n6\n1\n2\n3\n4\n5\n6\n1\n2\n3\n4\n5\n6\n1\n2\n3\n4\n5\n6\n1\n2\n3\n4\n5\n6\n1\n2\n3\n4\n5\n6\nEnd"); break;
            default: GlobalTextScript.Instance.UpdateText(""); break;
        }

    }
}

```
2. Add a UI -\> Button to your Canvas, Name: SendTextButton
3. Attach the TestAction.cs script to it.
4. In the Button's On Click event, add the SendTextButton object, then select the TestAction =\> OnClick function
5. Run your app and click the button.

# Answer
> 0 votes
1. Set Text and mark component as dirty;
2. At the beginning of next Update tick, check if component is dirty;
3. If it is - Do the work...

```
using UnityEngine;
using UnityEngine.UI;

public class LogController : MonoBehaviour
{
     public Text label;
     public ScrollRect scroll;
     bool isDirty;

     public void SetText(string text)
     {
        label.text = text;
        isDirty = true;
     }

     void Update()
     {
        if(isDirty)
        {
            scroll.verticalNormalizedPosition = 0;
            isDirty = false;
        }
     }
}

```

Game Objects Hierarhy is:

* ScrollRect
    + ViewPort
        - Text

---
Tags: unity, text, view, scrolling
---


title: Instantiating problems

text:
# Question
Title: Instantiating problems
I'm beginner here, I'm trying to instantiate a single object every specific duration, either form the left of the screen or from the the right, at the same time I want this object to move to the other side of the screen

So the troubles I'm facing here are:

1. sometimes 2 objects are being instantiated at the same time.
2. the objects move in the direction that are defined in the first if statement (both objects on the left and the right move in one direction)

the part where I instantiate objects is in the script(smallFishes) that's attached to an empty gameobject is :

```
void Start () {
    timer = gameObject.AddComponent<Timer>();
    width = 2f;
    timer.Duration = 3;
    timer.Run();
    left = Resources.Load("Left") as GameObject;
    right = Resources.Load("Right") as GameObject;

}
void Update () {

    if (timer.Finished)
    {
        lr = Random.Range(1, 3);
        if (lr == 1)
        {
            var generetx = -8.8f - width / 2;
            Instantiate(left, new Vector2(generetx, Random.Range(-4.8f,4.8f)), Quaternion.identity);
        }
        else
        {
            var generetx = +8.8f + width / 2;
            Instantiate(right, new Vector2(generetx, Random.Range(-4.8f, 4.8f)), Quaternion.identity);
        }
        timer.Duration = 3;
        timer.Run();
    }

}
public int state
{
    get { return lr; }
}

```

the part where I make the object move from the script that's attached to the object prefab:

```
void Start () {
    small = gameObject.AddComponent<smallFishes>();
    rb2d = gameObject.GetComponent<Rigidbody2D>();
}

void Update()
{
    var fishes = GameObject.FindGameObjectsWithTag("small");
    if (fishes!=null)
    {
        if (small.state == 1)
        {
            moveright = new Vector2(4 * Time.deltaTime, 0);
            rb2d.AddForce(moveright, ForceMode2D.Impulse);
        }
        else
        {
            moveleft = new Vector2(-4 * Time.deltaTime, 0);
            rb2d.AddForce(moveleft, ForceMode2D.Impulse);
        }
    }
}

```

Thanks in advance.

# Answer
It's quite likely that `if (timer.Finished)` is satisfied twice. As `Update` is called once for each frame it seams that `timer.Finished` is `true` for two frames in a raw.

**Possible solutions:**
Falsifying `timer.Finished` as soon as it's `true` value is consumed can be a solution.
Or detecting change of `timer.Finished` from `false` to `true` and executing code on that `event` also can be a solution.

Or just detecting the change not only `true` value:

```
bool timerFinishedPrevious = false;
void Update () {

    var timerFinishedToTrue = timerFinishedPrevious == false && (timerFinishedPrevious != timer.Finished);

    if (timerFinishedToTrue)
    {
        lr = Random.Range(1, 3);
        if (lr == 1)
        {
            var generetx = -8.8f - width / 2;
            Instantiate(left, new Vector2(generetx, Random.Range(-4.8f,4.8f)), Quaternion.identity);
        }
        else
        {
            var generetx = +8.8f + width / 2;
            Instantiate(right, new Vector2(generetx, Random.Range(-4.8f, 4.8f)), Quaternion.identity);
        }
        timer.Duration = 3;
        timer.Run();
    }

    timerFinishedPrevious = timer.Finished;
}

```
> 1 votes

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


# Question
Title: Implementing online connectivity and multiplayer/PVP for a newbie
**Background**

I'm a noob programmer looking to create a simple turn based mobile game as a side project. I've pretty much got the game logic down and am left with implementing the online multiplayer/PVP portion.

More specifically, i'm looking to implementing a system when the player clicks play and will be matched with an opponent in a 1 v 1 format, without any lobbies etc etc.

I'm currently trying to develop my game in android studio(i'm new) but am also open to unity if it makes the development easier.(I have no experience in Unity).

**What i want to know**

From what i understand,i need to create and host my own server for the multiplayer to run(i.e matching of player to opponent). Do i also need the server to run the game itself or am i able to connect the player to the opponent and simply record the result of the game to my server/database?

Also, how would i go about creating and running/hosting the server? I heard nodeJS is a good choice for writing the server.

**End Goal**

I just wanna publish my game onto the app store, IOS store, etc.

# Answer
> 1 votes
> Do I also need the server to run the game itself?

Generally speaking, it's better if the application is running on the server itself as you can never truly trusts the users. Unfortunately for you, Android Studio is not the best tool to create a web server application. Thankfully, you did suggests an acceptable alternative later in your question: Node.js

However, this is a huge shift in development in which you will need to transfer the game logic to the server. The Android Studio application will only be used to handle the user's input and display the game. The server will be in charge of verifying what is being submitted and apply the game logic.

> how would I go about creating and running/hosting the server?

Many options are available to you when it comes to hosting servers. AWS, Azure, Google Cloud platform or even Digital Ocean will do nicely. They also tend to have special promotions in which they give away free credits numbering in the hundreds to new accounts. Alternatively, you can host the server locally, but I do not recommend this options for self-described newbies.

Once you have purchased a server instance, you will need to install Nginx or Apache to handle incoming connections. Additionally, you will need an application that can transfer traffic generated by one user to another which can be done in Node.js as you initially suggested. You will also need to hardened your server against attack as once your game goes live, you will be advertising your server's address for all to see.

Finally, you might want to purchase a domain name and have it hosted on the server you build. Using Let's Encrypt, you can also have your traffic encrypted via SSL. This is not necessary, but it will improve the legitimacy of your game.

> I heard nodeJS is a good choice for writing the server.

Indeed, I have use this solution in many projects in the early phases due to how easy it is to create a quick application that can handle incoming connections and distribute traffic. Initially, you will wish to research web sockets which will allow you to send and receive messages using one constant connection.

Obviously, your questions are very broad and each of the topics discussed above could be it's very own in-depth article. I encourage you to continue digging. It may seem overwhelming, but we were all there once. Good luck!

---
Tags: unity, android, multiplayer, unity-networking
---


# Question
Title: How can I iterate over all entities with a particular component?
I'm currently designing a game engine and want to implement my own ECS implementation, so I decided to look around for ideas.

Unity has recently updated their engine and seems to be pushing towards using ECS, instead of their original components-are-systems design.

I noticed that Unity has a method called "GetEntities", a generic method which can do something like this:

```
public struct SomeComponent : IEntityComponent
{
    public string Message = "Hello, World!";
}

public struct Filter
{
    SomeComponent someComponent;
}

public MovementSystem : EntitySystem
{
    public override Process()
    {
        // How can I accomplish something like this?
        foreach(var entity in GetEntities<Filter>())
        {
            Console.WriteLine(entity.someComponent.Message);
        }
    }
}

```

I like this style of iterating over entities, given a filter for a specific component they need to include. But I'm not sure how to accomplish something like this.

If someone could shed some light on how something like this is even possible in C# that would be great!

# Answer
> 1 votes
I'm a little rusty with C# but something like this might work:

```
public List<FilterType> GetEntities<FilterType>()
{
    // Assume all entities are valid
    List<Entity> entities = new List<Entity>(allEntities);
    var fields = FilterType.GetFields();
    foreach(var field in fields)
    {
        var componentType = field.FieldType;
        foreach(var entity in entities)
        {
            // Remove any invalid entities
            if(!entity.HasComponent(componentType))
                entities.Remove(entity);
        }
    }

    List<FilterType> filters = new List<FilterType>();
    foreach(var entity in entities)
    {
        FilterType filter = (FilterType) Activator.CreateInstance(FilterType);
        foreach(var field in fields)
            field.SetValue(filter, entity.GetComponent(field.FieldType));
        filters.Add(obj);
    }

    return filters;
}

```

This uses reflection to get the type of all (public!) fields in the struct/class `FilterType` and then checks if an entity does not have that component. In that case that entity is invalid and is removed from the final list result.

---
Tags: unity, c#, entity-system
---


# Question
Title: Pathfinding in Procedural cave generation
I'm learning THIS tutorial about procedural cave generation using cellular automata with Unity.

I want to implement pathfinding on some enemies, so I need to make a quantization of the procedurally generated "non-wall" part of the map. Is there a best way to place nodes in this space?

I hope I was clear enough and I'm sorry if not.

# Answer
> 4 votes
That tutorial, just like any grid-based cave generation tutorial, will already generate both open and closed tiles. Thus you will already have a

> quantization of the procedurally generated "non-wall" part of the map

if you follow the tutorial through.

---
Tags: unity, c#, path-finding, procedural-generation
---


# Question
Title: libGDX game crashes on Android without any mention of crash in logs
No mention of any issue in process logs, an application just turns off during loading assets (~3% of all assets loaded). It works fine on desktop.

Only thing that seems related in global logs is this:

```
09-01 15:15:25.261 824-22928/? W/ActivityManager: Force removing ActivityRecord{911979f u0 xxx.xxx.xxx/.AndroidLauncher t664}: app died, no saved state

```

I suspect there might not be enough of memory, but why there is nothing in logs? I tried limiting JVM memory on PC to 512MB and it runs fine. But I am not entirely sure if this limit covers also native memory. Could that be the reason why it runs with limit set and yet crashes on a mobile device with 2GB memory?

# Answer
After splitting textures to multiple atlases and loading them only when needed, application runs fine. So I guess it was caused by lack of memory.
> 1 votes

---
Tags: libgdx, android
---


# Question
Title: Game map for platformer megaman-style game
I want to make platformer game that would be sort of like megaman. I'm using SFML library for it. I have a problem with creating a map. Should I hardcode every single platform, add it colliders and so on? I've heard that 2d array of segments would be better, but I would still have to manually fil an array that's like 1000x1000 segments. Is there an easier way to approach this?

# Answer
> 1 votes
Well it sounds like you should use or make this into a ***Tile-based platformer Engine***. Another really helpful thing to know is if you're using images?

Among a lot of tile-based engines-You should load your images either by making code for your images (listed below) or if you're using image **Files** some how *load* each image into a sort of structure like below: (Here's the important part so listen up)

`/*c/b means color/byte or you could have a number*/
/*Structure started*/ = {
 c/b, c/b, c/b, c/b, //New line
 c/b, c/b, c/b, c/b, //New line
 c/b, c/b, c/b, c/b, //New line
 c/b, c/b, c/b, c/b, //New line
}`

Here we have a grid of what (could be bytes or colors or, well it depends) to represent each image.

# Options

Either what structure you're using (it doesn't matter) **Loading** the images into a special *structure* where it is easier to process *collision*. You could do 2+ things:

```
1. *sew* all the images/image structures together and actually have them connected some how. (Like a segment structure or an adjacency array) Or some structure where everything can easily build itself while connecting it self

```

together; like:

/*iteration 1*/ `*-* * * * *
 * * * * * *
 * * * * *-*`

/*iteration 2*/ `*-* * * * *
 * * *-* * *
 * * * *-*-*`

/*iteration ...*/

Until it is all filled up! (You get the idea) So the it does the work for you. Also while processing collision you could just have everything relate to itself

```
2. The second option: Don't *sew* everything together and have it fill up by using like an array to copy in the structure you used to represent the map in. In this state your colliders create themselves.

```

And of course you could use a similar structure to represent the map as the image. I recommend you branch off of my ideas somehow to suit your needs. While you could use option #1 (preferably).

# Relating the data together

And of course in a more direct state sort of sense. No don't be *hardcoring parameters*.

Make a *structure for your images* to be turned into something to go in like a \[option #2 `gameObject` or as in option #1 just put it directly in your world structure\]! That would be easily processed by **collision handlers**.

Make sure you have multiple layers for your game to work in. **Segment/Array** and under that all *images stitched together into one big image*!

Now with multiple images together (**Unless** you want to directly work with the images) while creating the code for that remember to store the image coordinates in an array (Called `imgStorage`) so you can create the top layer.

# Referencing Objects

You could use that method to also get data from that `imgStorage` array and also to ***add bounding boxes*** (to the world structure) so you could put extra **code** in to help you represent/stitch/reference for your collision.

Now with everything in mind it's time to piece it all together!

* You have your images imported with their data in their structure(s).
* You have your grid/data/array to tell where to put the **images/game objects**.
* Your images have gotten (and put) their parameters in `imgStorage`!
* (Optionally) You made the image layer (piece together the images) backing the level(s)!
* You've built your **World structure** (in part) by using the structure where
* You've set you're **bounding boxes** `imgStorage` in their *(image data/game object place) or structure where it needs to go*
* You've added extra references for **bounding boxes** to tell them they can collide and told them whether they are "static" or "dynamic"

That's it, all you need now is to put in the collision code the operates on the images...

And then you're *done*! I hope this helps!

---
Tags: collision-detection, maps, sfml, platformer
---


# Question
Title: When I have multiple UI elements overlapping, how can I use a raycast to prioritize the one on top?
I have movable objects in a scene. When Raycast hits an object, I have a hovering UI that moves to a retaliative distance from the hit object. When the object is dragged, the UI's position is moved relative to the object. The UI accesses script functions by way of the Button(Script) component. I attached my functions to the buttons in the editor.

My issue is when the hovering UI is overlapping the view of another object, the UI moves to the object under the UI and never performed the function.
I would like for raycast never to hit the underlying object while my hovering UI is up, or at least to not hit the underlying object while the UI is in the way.

Both scripts are attached to the object tiles.

**updatePentagon.cs**

```
using UnityEngine;
using System.Collections;

public class updatePentagon : MonoBehaviour {
    public Transform target;
    public GameObject UI;
    private RaycastHit hit;
    private Plane dragPlane;
    private Vector3 dragPlaneNormal = Vector3.up;
    private float distanceToDragPlane = 0;
    Ray ray;

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit, 100f) ) {
                //if ((hit.collider.tag == "tileUI")  ){
                    //UI.SetActive (true);
                    target = hit.transform;
                    dragPlane = new Plane (dragPlaneNormal, target.position);
                //}
            }
        }
        if (Physics.Raycast (ray, out hit)) {
            if (Input.GetMouseButton (0)) {
                ray = Camera.main.ScreenPointToRay (Input.mousePosition);
                if (target) {
                    if (dragPlane.Raycast (ray, out distanceToDragPlane)) {
                        target.position = ray.GetPoint (distanceToDragPlane);
                    }
                }
            }
        }
    }
}

```

**updateTileUI.cs**

```
using UnityEngine;
using System.Collections;

public class updateTileUI : MonoBehaviour {
    public GameObject tileHandler;
    updatePentagon updatePentagon;
    float UIoffset = .2f;
    Vector3 pos;

    void Start () {
        updatePentagon = GetComponent<updatePentagon> ();
        updatePentagon.target.Rotate(0, 36, 0);
        updatePentagon.target.Rotate(0, -36, 0);
    }
    void Update () {
    }
    void OnMouseDown(){
        updatePentagon = GetComponent<updatePentagon> ();
        pos = updatePentagon.target.position;
        pos.y = updatePentagon.target.position.y + UIoffset;
        tileHandler.SetActive (true);
        tileHandler.transform.position = pos;
        }
    void OnMouseDrag()
    {
        tileHandler.transform.position = updatePentagon.target.position + new Vector3(0, UIoffset, 0);
    }
    public void cancelUI(){
        tileHandler.SetActive (false);
    }
    public void turnRight(){
        updatePentagon.target.Rotate(0, 36, 0);
        }
    public void turnLeft(){
        updatePentagon.target.Rotate(0, -36, 0);
    }
    public void confirm(){
        //activate colliders
        tileHandler.SetActive (false);

    }
}

```

# Answer
> 1 votes
You could have the UI set a flag that it has been click on, and condition the tiles to not respond to an intercepted mouse click. It may be useful in the future when you click units, or other things you might implement that are on top of your tiles. Perhaps all things should be able to intercept clicks and set this flag.

# Answer
> 1 votes
One way you can do it is to get the click ray, do a `Physics.RaycastAll()` and run through each object sequentially. The following is 2 scripts I used.

RayShooter.cs

```
public class RayShooter : MonoBehaviour
{
    public Ray ray;
    public float distance = 10;

    void Start () {
        ray = new Ray(transform.position, transform.forward);
    }

    void Update () {
        Debug.DrawRay(ray.origin, ray.direction * distance ,Color.red);

        RaycastHit[] hits = Physics.RaycastAll(ray, distance);

        foreach (var hit in hits)
        {
            bool blocked = hit.collider.GetComponent<RayIntercepter>().ProcessHit();

            if (blocked)
            {
                Debug.DrawLine(ray.origin, hit.point, Color.green);
                break;
            }
        }
    }
}

```

RayIntercepter.cs

```
public class RayIntercepter : MonoBehaviour
{

    public bool doProcessHit;
    public bool doInterceptHit;

    public bool ProcessHit()
    {
        if (!doProcessHit) { return false; } //This object doesnt want to get hit now

        //When I get hit, I draw line (Change this to whatever you want)
        Debug.DrawLine(transform.position, transform.position+ Vector3.up*2, Color.yellow);

        if (doInterceptHit) return true; //Block the raycast
        return false; //Dont block the raycast
    }
}

```

Here is a test scene

Yellow line = Ray process
Green line = Actual ray hits
Red line = Potential ray hit

From the left, the following is the properties

1. DoProcessHit = false, DoInterceptHit = false;
2. DoProcessHit = true, DoInterceptHit = false;
3. DoProcessHit = true, DoInterceptHit = true;
4. DoProcessHit = true, DoInterceptHit = true;

Describing each object,

* The first object ignores all raycast.
* The second object processes the raycast but doesnt block it
* The third object processes the raycast and blocks it
* The forth object want to process raycast but didnt receive it.

The suggestion for a camera case is to use `Camera.main.ScreenPointToRay()` to get the ray for the ray shooter.

# Answer
> 0 votes
If your hovering panel is a UI object (that is, one that uses the new Unity UI and requires a Canvas to render; I am unable to tell if you are or not) then you can do this at the top of your click-handling function:

```
if(EventSystem.current != null && EventSystem.current.currentSelectedGameObject != null) {
    return;
}

```

In your case, it'd be the section of code with the raycast in it. You can put this above the raycast and the rest of the method will be skipped.

---
Tags: unity, gui, raycasting
---