# Question
Title: How to implement toroidal mapping in SDL?
I am making an Asteroids clone in SDL2. I think the kind of world asteroids takes place in is called toroidal map. I'm refering to the fact that the edges of the world are connected so when you exit from one side, you appear at the opposite.

My first approach was with SDL\_DrawRect(), but I don't know how to "break" the rectangle in order for it to appear in two (or more) sides at once. I faked the effect by creating another rectangle, like a shadow, when the original rectangle was touching an edge. It worked somehow, but I wanted the real deal: render the diferent parts of the rectangle in different edges.

My second approach is creating the rectangle by SDL\_FPoints in a std::vector, like this:

```
struct SpaceObject {
  std::vector<SDL_FPoint> shape_;
  // more members
  void generateSquareShape(const SDL_FPoint& where);
  void move(float delta_time, const SDL_Point& screen_size);
  void render(SDL_Renderer& renderer) const;
  void warpCoordinates(SDL_FPoint& point, const SDL_Point& screen_size);
  // more functions
};

```

The shape is generated once with generateSquareShape(). It just sets the appropiate coordinates to each SDL\_FPoint. The movement function is just applying deltas to each point:

```
void SpaceObject::move(float delta_time, const SDL_Point& screen_size) {
  for (auto& point: shape_) {
    point.x += delta_.x * delta_time;
    point.y += delta_.y * delta_time;
    warpCoordinates(point, screen_size);
  }
}

```

Render is more of the same, another vector travesal:

```
void SpaceObject::render(SDL_Renderer& renderer) const {
  for (const auto& point: shape_) {
    SDL_RenderDrawPointF(&renderer, point.x, point.y);
  }
}

```

The warpCoordinates() is called at every move to check if a point must go to another side:

```
void SpaceObject::warpCoordinates(SDL_FPoint& point, const SDL_Point& screen_size) {
  if (point.x < 0) {
    point.x = screen_size.x + point.x;
  } else if (point.x > screen_size.x - 1u) {
    point.x = point.x - screen_size.x;
  }

  if (point.y < 0) {
    point.y = screen_size.y + point.y;
  } else if (point.y > screen_size.y - 1u) {
    point.y = point.y - screen_size.y;
  }
}

```

All in all it accomplishes with the effect nicely, but I think it performs poorly (at least in my laptop i5 2,6ghz, 6gb RAM, win10) and it hasn't collision detection yet. One optimization I think is moving and rendering on the same function so it only loops through the points vector once, but I think that breaks the one function, one job, doesn't it?

So, is there anything I'm missing to improve performance? A faster algorithm to implement this toroidal world? Maybe a most suitable SDL class to work with? Or some C++ technique I'm not using and I should? Thanks in advance, any help appreciated.

Using win10, SDL2.0.12, and the latest visualC++ compiler.

# Answer
Just use modulo operation on edges. It works in both positive and negative values.

Your `update()` function would call something like:

```
entity->posX = (entity->posX + entity->velocity * dt ) % screen_width
entity->posY = (entity->posY + entity->velocity * dt ) % screen_height

```

Creating a `warp_object()` function like you did, is the path to misery.
> 1 votes

---
Tags: c++, game-design, performance, sdl2
---


# Question
Title: SDL2. Why I'm getting a Segmentation Fault in the free() function? Also, am I doing the rendering stuff right?
So, I'm new at C programming and SDL2 and I'm trying to get something working here to write some games. First, I would like to know if I'm doing the rendering stuff the right way.

I'm kind of confused about the software and hardware rendering. Here I'm using a `SDL_Texture` and `SDL_LockTexture` to write raw pixels into it. I would like to know if I should use `SDL_Surface` instead, and, how can I get the best performance out of the hardware.

I allocate the memory for the pixels in the `SDL_WINDOWEVENT_EXPOSED`, which is called the first time a window appears, and everytime the window is resized, so then I can reallocate a new memory for the new window size.

For that to work, I need to `SDL_DestroyTexture` and `free(pixels)` to allocate newer ones in a new resized `SDL_Texture`, at least I think I need. The problem is... I'm getting a Segmentation Fault right in the `free()` call, according to GDB (GNU Debugger), and I don't know why, it's probably some stupid beginner error.

It is important to mention that, in the first `while(running)` iteration, the function `free()` is not called, so, the SegFault only happens the first time I resize the window. Here is the code:

```
#include <stdio.h> // fprintf, printf

#include <SDL2/SDL.h>

typedef struct
{
  SDL_Texture* texture;
  void* pixels;
  int width;
  int height;
  int pitch;
  int bytes_per_pixel;

} Render_Buffer;

void rendering_testing(Render_Buffer* render_buffer)
{
  if(SDL_LockTexture(render_buffer->texture,
                     NULL,
                     &render_buffer->pixels,
                     &render_buffer->pitch) != 0)
  {
    fprintf(stderr, "Failed to lock SDL texture: %s\n", SDL_GetError());
  }
  else
  {
    uint8* row_first_byte = (uint8*)render_buffer->pixels;

    for(uint16 y = 0; y < render_buffer->height; ++y)
    {
      uint32* pixel = (uint32*)row_first_byte;

      for(uint16 x = 0; x < render_buffer->width; ++x)
      {
        *pixel++ = 0x00ff00ff;
      }

      row_first_byte += render_buffer->pitch;
    }

    SDL_UnlockTexture(render_buffer->texture);
  }
}

int main(int argc, char* argv[])
{
  if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  {
    fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError());
    return -1;
  }

  int window_width = 640;
  int window_height = 480;

  SDL_Window* window = SDL_CreateWindow("Breakout",
                                        SDL_WINDOWPOS_CENTERED,
                                        SDL_WINDOWPOS_CENTERED,
                                        window_width,
                                        window_height,
                                        SDL_WINDOW_RESIZABLE
#ifndef DEBUG
                                        |SDL_WINDOW_FULLSCREEN_DESKTOP
#endif
                                        );
  if(window == NULL)
  {
    fprintf(stderr, "Failed to create SDL window: %s\n", SDL_GetError());
    SDL_Quit();
    return -1;
  }

  SDL_Renderer* renderer = SDL_CreateRenderer(window, -1,
                                              SDL_RENDERER_ACCELERATED|
                                              SDL_RENDERER_PRESENTVSYNC);
  if(renderer == NULL)
  {
    fprintf(stderr, "Failed to create SDL renderer: %s\n", SDL_GetError());
    SDL_DestroyWindow(window);
    SDL_Quit();
    return -1;
  }

  Render_Buffer render_buffer = {0};
  render_buffer.bytes_per_pixel = 4;

  bool8 running = true;
  while(running)
  {
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
      switch(event.type)
      {
        case SDL_QUIT:
        {
          running = false;
        } break;

        case SDL_WINDOWEVENT:
        {
          switch(event.window.event)
          {
            case SDL_WINDOWEVENT_EXPOSED:
            {
              if(render_buffer.texture)
              {
                SDL_DestroyTexture(render_buffer.texture);
              }

              SDL_GetWindowSize(window, &window_width, &window_height);
#ifdef DEBUG
              printf("window width: %d\nwindow height: %d\n", window_width, window_height);
#endif
              render_buffer.width = window_width;
              render_buffer.height = window_height;

              render_buffer.texture = SDL_CreateTexture(renderer,
                                                        SDL_PIXELFORMAT_RGBA8888,
                                                        SDL_TEXTUREACCESS_STREAMING,
                                                        render_buffer.width,
                                                        render_buffer.height);

              if(render_buffer.texture == NULL)
              {
                fprintf(stderr, "Failed to create SDL texture: %s\n", SDL_GetError());
                SDL_DestroyRenderer(renderer);
                SDL_DestroyWindow(window);
                SDL_Quit();
                running = false;
                return -1;
              }

              if(render_buffer.pixels)
              {
                free(render_buffer.pixels); // SEGFAULT HAPPENS HERE!!!
              }

              render_buffer.pixels = malloc(render_buffer.width *
                                            render_buffer.height *
                                            render_buffer.bytes_per_pixel);

              render_buffer.pitch = render_buffer.width * render_buffer.bytes_per_pixel;

            } break;

            default:
            {
              // TODO
            }
          }
        } break;

        default:
        {
          // TODO
        }
      }
    }

    rendering_testing(&render_buffer);

    SDL_RenderCopy(renderer, render_buffer.texture, NULL, NULL);
    SDL_RenderPresent(renderer);
  }

  SDL_DestroyTexture(render_buffer.texture);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}

```

Should I use `malloc()` and `free()` or something else instead?

What can I do to solve this SegFault error? What can I do the get the best performance out of the renderer while writing pixels manually into the memory, and what is the right way to do that? What can I do better that I'm not doing here?

For now, thanks so much for the attention!

# Answer
After the `SDL_UnlockTexture` the pointer to the pixels gets invalidated. From SDL documentation

> As an optimization, the pixels made available for editing don't necessarily contain the old texture data. This is a write-only operation, and if you need to keep a copy of the texture data you should do that at the application level.

Also is explained in LazyFoo's documentation.

> After the texture is unlocked the pixel pointer is invalid so we set it to NULL.
> 1 votes

---
Tags: sdl2, c
---


# Question
Title: How do I detect collision between an ellipse and a rhombus?
I'm building a game in C/C++ (been alternating between the two), but one of the biggest problems I've run into is collision detection. The game is isometric and exists on a 2x1 grid (e.g. the base tile is 32x16px).

Most creatures in the game use ellipses as collision masks (similarly 2x1 sized, default size is 32x16), whereas static objects use rhombuses for masks (again, 2x1, 32x16 default). How do I detect the collision of these two distinct shapes? Also, how do I detect collisions between two ellipses and/or two rombuses?

I've looked at the Separating Axis Theorem, Voronoi diagrams, and all kinds of other things, but I am having trouble understanding them (which is a pretty essential step for C/C++). Can anyone help me to understand these techniques?

# Answer
Exactly because that kind of problems we have two coordinate system, one is the `view coordinate system` (the isometric one) that you uses to draw and the other is the `world coordinate system` where you do the mapping (a regular Cartesian plane).

Collisions should be handled in the world coordinate system. You also need to write 2 functions to translate coordinates in those two spaces: `world2view` and `view2world`.

The exact details of those two functions depend only of your isometric camera angle.
> 1 votes

---
Tags: c++, collision-detection, isometric, c, sdl2
---


title: Turn-based Pencil/paper game; phases

text:
# Question
Title: Turn-based Pencil/paper game; phases
I'm not entirely sure this is the right place since all I see is coding questions, but I'll ask anyway in the hopes that someone can answer or point me in the right direction.

I've been developing a pencil/paper war strategy game for a while now and have run multiple tests with other players, but I've been having one major issue with the action system.

The game is turn-based and phase-based during the turns. Each turn has 7 phases and each unit has anywhere between 1 and 7 phases, depending on the unit itself. The phases are split up for the turn phase, so a unit with a movement phase can only move on the x; |x|2|x|4|x|6|x|.

I have a separation of attack phases and movement phases which can be two different things. For example, a vehicle has a movement rating of 6 but an attack of 4. This means it can move 6 times and attack only 4 times but only on it's designated rating.

Hopefully that's enough explanation... Anyway, I have had an issue when it comes to initiative. If two units have an attack on the exact same part of the phase and both deal enough damage to destroy each other... How could I determine who attacked who first? Should one unit be able to destroy the other, or should both just destroy each other?

The second part of that would be... If both units still have the same attack phase and unit 1 deals enough damage to destroy the other but unit 2 only deals a small amount... Who went first? Should there be a dice roll or coin toss to determine or can someone help think of a way to fix this?

# Answer
I can see three approaches for this. Which one is better, is up to you. Although, what do player say? Player feedback is probably more valuable than, you know, some random person on the Internet feedback.

1. Simultaneous initiative: They both attack, and they both receive damage. That would mean that both players declare the attack, and then you solve the consequences for both attacks. If one unit destroys the other, that does not prevent the attack of the destroyed unit to also deal damage. If they can both destroy each other, they both get destroyed.
2. Ad-Hoc Initiative. Just pick one at random when the situation arrives.
3. Global Initiative. Usually some order of play is picked at the start of the game. *Perhaps by throwing dice and picking in descending order. Or some other randomization strategy.* You don't have that, consider adding it. If you do have it, consider reusing it for deciding who attacks first.

I would prefer the first approach. It keeps the spirit of simultaneous actions, does not require additional mechanical complexity, and can lead to unique outcomes that are impossible (such as mutual destruction) if we decide that one unit goes first.

The second approach has value from the point of view of risk and reward. If the units can destroy each other, the attack is a gamble, and the player should be ready for both winning and losing.

The third approach can have some strategic value. Given that the outcome is known, you can plan ahead for it. However… The first player would not attack a unit knowing the other player can answer back and win. And the second player would not answer the attack known it will be a lose. That means, that this approach should (in perfect play) result in the mutual attack never happening. *On the other there could be strategic value in getting a mutual destruction with the first approach, which I consider more interesting.*

Although, we should also consider what else can the other player do other than response the attack. Given that the game is divided in phases, and some are designated attack phases. The other player cannot move while being attacked. It appears to me the only other option is to attack a third unit. Then again, the same arguments above would unroll. If the player know they are winning or losing despite what they might do, it is not an interesting decision… However, if they had another option aside from attacking, it could be.

---

Being a pencil and paper game, you really have much more freedom. The player can play rock-paper-scissors, or they ask each other trivia questions, or whatever. The answer above applies for video and otherwise games. *Well, I guess you could implement rock-paper-scissors et.al. as a solution in a video game. Let us say, this is not an exhaustive list of possible solutions.*

---

Considering units that can move and attack in the same phase. We can continue to apply the rule of all attacks happening at the same time. However, if we want to simulate the idea that all units begin the phase at the same time, then a unit that did not move would attack before one that did.

We can come up with more complicated rules for the case where both units did attack and move. Namely, that the faster unit (the one able to move more more distance) would attack first.

Similarly, we could solve initiative based on the attacks. That is, adding an initiative stat to either units or attack (or even both, and add them together). Then you compare these values to decide who attacks first.

*This kind of solutions I would avoid in pencil and paper games, just to keep the flow of the game fast, however you see these kind of rules all the time in tabletop RPG games and similar. And of course, for a video game, we can disregard the time this computation would take.*

---

See also En passant chess rule. Where a pawn that moved later can capture a pawn that moved the prior turn "as it was passing". As if, the turns of both player somehow overlapped in time. While not exactly the same thing, it is an interesting precedent that might serve as inspiration.
> 0 votes

---
Tags: turn-based-strategy
---


# Question
Title: My character is not switching right or left like subway surfer in 2D?
I am making a 2D subway surfer type of game right now and I found this code on the internet that switches the lane of the player but the problem is it doesn't switch. When I play the scene it won't move it will just give the of "int" desiredLane. Why is this happening?

---

**CODE**

```
private const float LANE_DISTANCE = 3.0f;

[Header("Movement")]
public float moveSpeed;

public int desiredLane = 1; //0 = Left 1 = Middle 2 = Right

```

---

```
void MobileSwipeControl()
{
    //Movement Input
    if (Input.GetKeyDown(KeyCode.A))
        MoveLane(false);
    if (Input.GetKeyDown(KeyCode.D))
        MoveLane(true);

    //Calculate where we should be in the future
    Vector3 targetPosition = transform.position.y * Vector3.up;

    if (desiredLane == 0)
        targetPosition += Vector3.left * LANE_DISTANCE;
    else if (desiredLane == 2)
        targetPosition += Vector3.right * LANE_DISTANCE;

    //Let's calculate our move delta
    Vector3 moveVector = Vector3.zero;
    moveVector.x = (targetPosition - transform.position).normalized.x * moveSpeed;
    moveVector.y = moveSpeed;

    //Move the player
    myBody.velocity = Vector2.up * moveSpeed;
 }

```

---

```
private void MoveLane(bool goingRight)
{
    desiredLane += (goingRight) ? 1 : -1;
    desiredLane = Mathf.Clamp(desiredLane, 0, 2);
}

```

# Answer
> 1 votes
So I found out the answer thanks to Zibelas! I forgot to apply moveVector to my movement.

---

```
//Move the player
myBody.velocity = moveVector * moveSpeed;

```

---

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


# Question
Title: ScreenToWorldPoint(Input.mousePosition) always returns 0 for X and Y coordinates
I'm trying to convert the mouse position (Input.mousePosition) into world points, but for whatever reason the X and Y coordinates are always, always 0.

Here, I printed mousePosition and ScreenToWorldPoint()'s output:

The -10 in the Z is understandable, but why do I get 0s in X and Y regardless of the actual, varying mouse position?

This is inside a custom display I set inside Game View (1440x3040). I tried Free Aspect, but that didn't change anything.

I tried parenting the script to an empty game object centered on origin just in case, but that didn't do anything either.

The code:

```
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log(mousePos);
Debug.Log(Input.mousePosition);

```

Or, more generally:

```
private bool hitProjectile() {
    bool hit = false;
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    Debug.Log(mousePos);
    Debug.Log(Input.mousePosition);

    if ((mousePos.x >= (pt.position.x - radius) && mousePos.x <= (pt.position.x + radius)) &&
        (mousePos.y >= (pt.position.y - radius) && mousePos.y <= (pt.position.y + radius)))
        hit = true;

    return hit;
}

```

The game is in 2D, the camera is perspective, and I'm using URP. The script is trying to determine if the mouse clicked on a circle (/w a CircleCollider2D).

What the hell is going on? I hope this is not a URP thing. I've had nothing but bad experiences with it.

# Answer
> 3 votes
Whenever you have trouble with an API method, your first step should be to check the documentation on that method:

> # Camera.ScreenToWorldPoint
>
> `public Vector3 ScreenToWorldPoint(Vector3 position);`
> `public Vector3 ScreenToWorldPoint(Vector3 position, Camera.MonoOrStereoscopicEye eye);`
>
> **Parameters**
>
> * **position** A screen space position (often mouse x, y), *plus a z position for depth* (for example, a camera clipping plane).
> * **eye** By default, Camera.MonoOrStereoscopicEye.Mono. Can be set to Camera.MonoOrStereoscopicEye.Left or Camera.MonoOrStereoscopicEye.Right for use in stereoscopic rendering (e.g., for VR).
>
> **Returns**
>
> **Vector3** The worldspace point created by converting the screen space point *at the provided distance z from the camera plane.*

Note the emphasis I've added on the z depth. Your code doesn't tell the camera what depth it wants the world point to be at. It just converts the 2D vector `Input.mousePosition` into a 3D vector implicitly. That implicit version puts a zero in the z coordinate. And of course if you take *any* screen position at zero depth from the camera, you get the camera's location itself. The frustum hasn't had any room to fan out.

Try something more like this:

```
Vector3 screenPosDepth = Input.mousePosition;
// Give it a depth. Maybe a raycast depth, maybe a clipping plane...
screenPosDepth.z = 5.0f;
Vector3 mousePos = Camera.main.ScreenToWorldPoint(screenPosDepth);

```

For example, if you want the projected point to have the same depth from the camera as some other transform `target`, you can write:

```
screenPosDepth.z = Vector3.Dot(
                      camera.transform.forward,
                      target.position - camera.transform.position
                  );

```

# Answer
> 1 votes
Couple of suggestions here...

First off, try setting the mouse position's z to a positive value. As I recall it's to do with the near clipping plane (in the Camera settings). Set it to a value greater than that and it should work.

Secondly, take a look at OnMouseEnter(). It's called on a MonoBehaviour when the mouse cursor enters it. If you cache this value in a variable (and clear it on OnMouseExit()) you can just query the variable when the mouse button is down...

Danny

---
Tags: unity
---


title: Controlling noise density

text:
# Question
Title: Controlling noise density
I'm trying to fake terrain blending by using an opacity mask on my road mesh to reveal the grass underneath. I'm currently multiplying some Perlin noise by a Rectangle node displaying my texture at 80% width which is giving me the following:

Obviously this doesn't look great for reasons that should be apparent. The blotches are unnaturally spaced and they abruptly end with a sharp line at the end of the texture. What I would like to do is generate noise that looks more along the lines of this:

Is there a way to apply some sort of gradient to my noise to achieve this? I know I can just use the texture itself but I would like to be able to adjust properties like the extent of the noise during runtime.

# Answer
> 2 votes
Here's one way to approach this:

The main idea here is that we make a symmetric gradient across our UV space (using the y direction here because that's how my road mesh was set up) by subtracting 0.5 and thaking the absolute value.

Then we apply domain warping within that gradient - shifting the gradient value back & forth using the output of a noise node, with 0.5 subtracted to get the values to be symmetric about 0.

Now we can use this warped sample coordinate to look up into our gradient map, that controls the fall-off from opaque to transparent. You can also use math nodes for this, but you might find the gradient more intuitive to adjust by eye.

---
Tags: unity, shaders, perlin-noise, unity-shader-graph
---


# Question
Title: Bouncing ball loses its forward momentum after the first bounce
I've created a bouncing ball in Unity, and I want to bounce the ball across the field, but the results I get seem very unrealistic.

The ball should bounce in the direction it was launched 2 or 3 more times, but after the first launch the next bounce is bouncing at the same place, going straight into the air. I also didn't see any spin effect on the ball. How can solve this problem?

And here's my physics settings

# Answer
Thank you for your answer. I think i found a solution. The solution is reduce the FixedTimestep into 0.01 instead of 0.02(default). I think this will make the physic much more precise(Since every thing on pitch happen in 8x8 grid).
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Switch statement efficiency in game code
Recently, I was digging into VVVVVVV's source code that was released on GitHub by Terry Cavanagh. I went into the `Game.cpp` file, and found that it contains an absolutely gigantic, 3000+ case long `switch` statement in what is seemingly a function that is called consistently, not just once.

This made me ponder about how efficient `switch` statements are, and I realized I don't know much about their difference to normal `if-else` chains. Are `switch` statements normally used in this manner to implement state handling, and why doesn't something like this lag the game like crazy? (I'm assuming a massive amount of comparisons are being made every time)

# Answer
In this situation, it is trivial and a no-brainer.

I'll be bold and not look at the whole code. I'll assume that the function in which this `switch` statement is (`Game::updatestate()`) is called once per frame.

This switch statement being called *once per frame* is a droplet in the ocean. Typically, graphics rendering, physics and AI take up much more CPU time than this type of decision making, whether it is a switch or a series of if-else-if.

From the couple of videos I've seen on YouTube, the game runs smoothly, without lag.

I assume Terry Cavanagh, like any good dev, profiled the game at some point and fixed/improved/optimized some parts of it *based on the profiler results*; it's safe to assume that the issue was not *that part*.

That's the key part here. The syntax of the `switch` is clean and clear with the minimum of overhead code, going another way would clutter more the code without real technical benefit.

---

To be honest, I would personally be more worried about the use of raw integers instead of constant in the `case` parts, as this makes the code much harder to read. (I'll give the author the benefit of the doubt, as coming up with 300+ GOOD constant names could be a challenge. He used comments in an OK manner, in this case, and using constants like this removes the need to link all the files that share the constant names together.)

---

To answer your questions directly:

> Are switch statements normally used in this manner to implement state handling

There are many games around, and many ways to do this, but yes, using a switch to handle a state (or multiple states) is a perfectly acceptable way of doing this.

> and why doesn't something like this lag the game like crazy?

As it's been pointed out, this switch is called 30, 60, 90 times per seconds, it's trivial for a CPU to handle.

---

Finally, if you're curious to go and see the "under the hood" effects of the code you write, there is an online tool called Compiler explorer that lets you write some chunks of C++ code and see how it is compiled to assembler by the different compilers out there.

Although you can come up with trivial tests for this tool, you'll never know the full effects of actual real code compiled with optimization flags (because you ship your game with optimizations turned on). Compilers are very smart to not do some work.

As a simple, trivial, non-optimized test, I've written two similar chunks, one using `if-else` (Link), and one using a `switch` (Link). You can take a look and see for yourself the different output, and even toy around and add the optimization to see the effects (and see why using simple-trivial test code is often useless for testing real world situations).
> 27 votes

# Answer
In fact, `switch` statements are *more* efficient than `if-else` chains for one simple reason: Switch tables! (Also known as branch tables or jump tables).

The simple explanation is that in a typical `switch` statement, each case ends in a `break` statement, so the compiler can figure out that exactly one path is going to be taken upon entering the `switch`. So then each `case` entry just becomes an entry in a table. Your switch statement becomes:

1. Look up table entry
2. Jump to the appropriate block

This is versus a naive `if-else` chain, where each `if` clause needs to be evaluated one at a time. So if you're looking for case 200, you need to evaluate 199 `false`. Much slower than a lookup.

However, modern compilers are really smart. What you'll probably see if you run with optimizations is that something like this:

```
if (x == 1) {
  ...
} else if (x == 2) {
  ...
} else if (x == 3) {
  ...
}
...

```

can be turned into:

```
switch(x) {
  case 1:
    ...
    break;
  case 2:
    ...
    break;
  case 3:
    ...
    break;
  ...
}

```

So a good compiler will take advantage of switch tables either way, and you probably won't notice any difference between the two.
> 27 votes

# Answer
There is a surprising amount of confusion about how the compiler optimizes `if/else` chains vs `switch` statements. This is probably because there have been many changes over time in how compilers optimize these constructs. And even using the latest compiler versions, the answer depends on:

* what optimization level you are using,
* what values you are checking for,
* the number of values you are checking for,
* what code is being executed inside each case.

Note that if a chain of `if/else` statements is semantically identical to a `switch` statement, the compiler is free to optimize the `if/else` chain in the same way as the `switch` statement. Nothing prevents the compiler from using a jump table in either case.

In an earlier version of Vaillancourt's answer, examples on the Compiler Explorer were given for the `if/else` chain and the `switch` statement. These examples are not representative of real game code, since they did not use any optimization flags, and because every case executes exactly the same statement. The examples do match one aspect though: in VVVVVV's switch statement, there are gaps in the case values tested for.

When a game is released, it is typically compiled with a high optimization level. When adding `-Ofast` to the compiler flags in the examples, and looking at the resulting assembly, the results are quite interesting, showing both that compilers can use jump tables for `if/else` chains, and that there is a huge variation in how compilers optimize code:

* `if/else` statement:
    + GCC 10.1 `-Ofast`: linear sequence of compare and jump instructions
    + Clang 10.0.0 `-Ofast`: jump table
* `switch` statement:
    + GCC 10.1 `-Ofast`: jump table
    + Clang 10.0.0 `-Ofast`: replaces the whole function with `return state * state;`

And it's not even clear which of those results is fastest. The branch predictor might hide a lot of the latency with the linear sequence of jump instructions, so if it hits one of the early cases most of the time, it might even win.
> 8 votes

# Answer
Because `switch` statements work on only a single variable they can be optimized very easily compared to an `if-else` statement. The most naïve way to do so would be to determine the case using a binary tree.

Of course, I doubt this is the reason for using switch in VVVVVVV. The amount of time saved is unlikely to be meaningful especially with branch prediction.
> 3 votes

---
Tags: c++, efficiency
---


# Question
Title: what are texcoord tags in mesh.xml file in Ogrexml format?
I exported a 3d model from blender 2.79 and using ogrexml import/export plugin. but the texture will crash and UV map not working in that format. I made the model by four parts head-body-hands-shoes and they have 4 material and 4 textures, so I made a texture atlas for it and join them in a mesh to More optimization. I think removing other UV maps has a problem because when I check the model.mesh.xml in a note editor and every vertex has 3 texture coordinate tags and I compared it with a normal correct model that looks good in the blender and in ogrexml format, it has one texcoord tag inside of vertex tag. 1-what are texcoord tags? are they using for UV maps in ogrexml format? 2-how can I clear blend files from other unused uvMaps to avoid exporting them with the model?

# Answer
finally, I found the problem.

1-it seems the texcoord tag is using to determine the UV map of texture. 2-an option in the data tab of blender is used to keep and show UV maps, from there I deleted unused uvMap and it works correctly.
> 1 votes

---
Tags: blender, materials, ogre, texture-atlas
---


# Question
Title: How to render a field of view of over 180 degrees?
In most 3D renderings, a view frustum is used.
This has the problem, that things get stretched out towards the edges.
At "normal" fov (field of view) of about 60 degrees, the effect is not very noticeable, unless compared side by side (example) but at a higher fov of something like 120 degrees it's really noticeable by making things near the edge look way larger/closer (example).
A fov of anything near or over 180 degrees breaks the rendering completely.

So far, I couldn't find anything on how to render in such a way that fixes this or even how it's called.

The ultimate goal would be to be able to render up to 360 degrees (ignoring the hardware needed, to display it) without any distortion, relative to other parts of the image.

So, how would I approach rendering that? Is there already some open source software, I can take a look at?

# Answer
There are many ways to project sphere to rectangle, as you can see in this video. Basic idea is simple:

1. Build screen-sized lookup texture that maps screen coordinates to cube map coordinates, according to selected projection function (and it's parameters). Needs to be done once.
2. Render scene to a cube map.
3. Using a fragment shader, combine the two to project a cube map on a screen.

Problem is, this approach is going to cause massive performance toll *and* quality degradation, because pixel density is not going to match 1:1 between projection source and destination. (Unless you are willing to render cube map at higher resolutions to guarantee at least 1:1 density, which will cause even bigger performance impact.)

I don't see a way to do this transform at earlier stages of rendering, because GPU hardware depends on straight lines being straight, but all "interesting" projections break this guarantee. Essentially GPU can't render triangle with bent edges.

If alternate projections seem too fancy and you'd rather stick with perspective, then straight cube map method (as mentioned in other answer) should work, I just wanted to elaborate on it a little: all you need to do is to render scene to cube map (except 1 face that is never visible), then render it as unlit cube around camera. It's still susceptible to quality issues I mentioned earlier.
> 2 votes

# Answer
This is actually a solved problem from shadowmapping point lights; you do multiple renderings instead of just a single rendering. So you can think of a render-to-cubemap as rendering with both horizontal and vertical FOV of 360 degrees, for example.
> 0 votes

---
Tags: rendering, projection
---


# Question
Title: How to make a simple dialog system with yes/no options and pages?
I recently made dialogues. Now I want to add the option to choose yes/no when the dialogue is finished (if it has a choice).

Adding buttons to the dialogue is no problem, the problem I'm having is that I want a "generic" dialogue system. By that I mean, I might have 200 NPCs, and depending on which NPC I am talking to, the yes/no buttons will react differently. This is where I'm stuck. How will the buttons know which methods to call?

Say I have one NPC that offers to sell me an item for 100 gold, and another NPC that offers to show me around the village. How will my system know which functions to call when I press "Yes"?

All I can find on this subject is really complicated using trees and things I don't fully understand yet, and don't really need, since my system is very simple.

# Answer
Here you go:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using UnityEngine.Events;

[RequireComponent (typeof(CanvasGroup))]
public class GenericDialog : MonoBehaviour {

    public Text title;
    public Text message;
    public Text accept, decline;
    public Button acceptButton, declineButton;

    private CanvasGroup cg;

    void Awake(){
        cg = GetComponent<CanvasGroup>();
    }

    public GenericDialog OnAccept(string text, UnityAction action){
        accept.text = text;
        acceptButton.onClick.RemoveAllListeners();
        acceptButton.onClick.AddListener(action);
        return this;
    }

    public GenericDialog OnDecline(string text, UnityAction action){
        decline.text = text;
        declineButton.onClick.RemoveAllListeners();
        declineButton.onClick.AddListener(action);
        return this;
    }

    public GenericDialog Title(string title){
        this.title.text = title;
        return this;
    }

    public GenericDialog Message(string message){
        this.message.text = message;
        return this;
    }

    // show the dialog, set it's canvasGroup.alpha to 1f or tween like here
    public void Show(){
        this.transform.SetAsLastSibling();
        cg.DOKill();
        cg.blocksRaycasts = true;
        cg.interactable = true;
        cg.DOFade(1f, 0.3f);
    }

    public void Hide(){
        cg.DOKill();
        cg.interactable = false;
        cg.DOFade(0f, 0.3f).OnComplete(() => cg.blocksRaycasts = false);
    }

    private static GenericDialog instance;
    public static GenericDialog Instance() {
        if(!instance){
            instance = FindObjectOfType(typeof (GenericDialog)) as GenericDialog;
            if(!instance)
                Debug.Log("There need to be at least one active GenericDialog on the scene");
        }

        return instance;
    }

}

```

Usage:

```
GenericDialog dialog = GenericDialog.Instance();
dialog.SetTitle("Hello player!");
dialog.SetMessage("Do you want to exchange some gems for 100 gold?");
dialog.SetOnAccept("Yes", () => { // define what happens when user clicks Yes:
    if(player.HasGems(10)){
        player.RemoveGems(10);
        player.AddGold(100);
    }
    dialog.Hide();
});

dialog.SetOnDecline("No thanks", () => dialog.Hide());
dialog.Show();

```

You can chain these like:

```
dialog.SetTitle("ABC").SetMessage("DEF").Show(); // cause of a builder pattern

```

Now, create your beautiful dialog on the scene, add `Text` components, `Buttons` and more. Also, add a `CanvasGroup` to fade the dialog in and out.

Add this `GenericDialog` script to the `dialog's gameobject` on the `scene` and drag and drop your components on that script's fields.

You can access the above code from anywhere cause of a singleton pattern.

Feel free to ask any questions!

If you don't use any `Tweening` library like `DOTween`, just change `Show()` method contents to:

```
public void Show(){
    this.transform.SetAsLastSibling();
    cg.interactable = true;
    cg.alpha = 1f;
    cg.blockRaycasts = true;
}

```

and `Hide()` method too.

# Dialog with pages

Ok so, first of all, we create a `Page` script and add this code to it:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent (typeof(CanvasGroup))]
public class Page : MonoBehaviour {

    public Text pageText;
    private CanvasGroup cg;

    void Awake(){
        cg = GetComponent<CanvasGroup>();
    }

    public void Show(){
        this.cg.alpha = 1f;
        this.cg.interactable = true; // in case it's a scrollview or something and you want to scroll - it has to be interactable to allow clicks
        this.cg.blocksRaycasts = true;
    }

    public void Hide(){
        this.cg.alpha = 0f;
        this.cg.interactable = false;
        this.cg.blocksRaycasts = false;
    }
}

```

Then, we create an object like here, add a `Page` component to it and attach the one object - `Text` to the script.

Then, you need to make the page a `PREFAB` \- so just move the page object to the `Assets window` from the scene. When it becomes blue, we're done. You can remove the object from the scene. We'll use the prefab later.

Now we create the PageableDialog class. I've explained how it works inside.

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

[RequireComponent (typeof(CanvasGroup))]
public class PageableDialog : MonoBehaviour {

    // title and subtitle for the entire dialog, like NPC name and quest name or something
    public Text title, subtitle;

    // buttons and their text components (Prev/Next and on the last page - Accept)
    public Text nextText, prevText;
    public Button prevButton, nextButton;

    // accept text when we're on the last page of the dialog
    private string acceptText = "Accept Quest";

    // what happens when user clicks Accept
    private UnityAction onAcceptAction;

    // canvas group for the entire dialog
    private CanvasGroup cg;

    // prefab for the page object (it has just a text component)
    public Page pagePrefab;

    // list of pages (added through AddPage())
    public List<Page> pages = new List<Page>();

    // current page index
    private int _currentPage;

    void Awake(){
        cg = GetComponent<CanvasGroup>();

        _currentPage = 0;

        // prevbutton always shows the previous page so (currentPage - 1)
        prevButton.onClick.AddListener(() => {
            if(_currentPage > 0){ // so we don't exceed the pages list
                ShowPage(_currentPage - 1);
            }
        });

        // nextButton always shows the next page (current + 1)
        nextButton.onClick.AddListener(() => {
            if(_currentPage < pages.Count - 1){ // so we don't exceed the pages list
                ShowPage(_currentPage + 1);
            }
        });
    }

    // you can customize this method and the Page class so it has some scrolls, buttons etc.
    // you can add different AddPage methods simultanously, one which adds a scrollview, one adds a text etc.
    // then, customize the Page class
    public void AddPage(string pageText){
        Page page = Instantiate(pagePrefab, this.transform);
        page.pageText.text = pageText;
        pages.Add(page);

    }

    // what happens on the last page, when user clicks Accept
    public PageableDialog OnAccept(string text, UnityAction action){
        acceptText = text;
        onAcceptAction = action;
        return this;
    }

    public PageableDialog SetTitle(string title){
        this.title.text = title;
        return this;
    }

    public PageableDialog SetSubtitle(string subtitle){
        this.subtitle.text = subtitle;
        return this;
    }

    public void Hide(){
        cg.alpha = 0f;
        cg.interactable = false;
        cg.blocksRaycasts = false;

        // destroy or reset, better destroy cause we create dialogs in DialogManager
        // when we're finished, we destroy the dialog object. reset is not needed, you can remove it.
        Reset();
        Destroy(this.gameObject);
    }

    // we show the entire dialog and then, show the first page instantly.
    // we also setasLastSibling to make the dialog on top of other things on canvas.
    public void Show(){
        this.transform.SetAsLastSibling();
        cg.alpha = 1f;
        cg.interactable = true;
        cg.blocksRaycasts = true;

        // show the 1st page

        if(pages.Count > 0){
            ShowPage(0);
        } else throw new Exception ("We have an error, m4te! Wrong implementation. You have to add pages to the dialog before showing it.");
    }

    public void ShowPage(int pageNum){

        // safety check
        if(pageNum < 0 || pageNum >= pages.Count)
            pageNum = 0;

        // we set the currentpage
        _currentPage = pageNum;

        // if we show page 0, we disable the "Prev" button
        if(_currentPage == 0) prevButton.gameObject.SetActive(false);
        else prevButton.gameObject.SetActive(true);

        // if we're showing the last page, we change the button's text to our accept text, like "Accept Quest" and add the OnAcceptAction to be performed when clicked.
        if(_currentPage == (pages.Count - 1)){
            nextText.text = acceptText;
            nextButton.onClick.AddListener(onAcceptAction);
        }
        else // otherwise, we remove this listener or it would accept the quest on each page :D
        {
            nextText.text = "Next Page";
            nextButton.onClick.RemoveListener(onAcceptAction);
        }

        // finally, we iterate through pages, show the one we picked and hide the rest.
        for(int i=0;i<pages.Count;i++){
            if(i == pageNum){
                pages[i].Show();
            } else pages[i].Hide();
        }

    }

    // if you want to reuse dialogs, use this method to reset them, but don't reuse.
    private void Reset(){
        foreach(Page p in pages){
            p.Hide();
        }

        _currentPage = 0;
    }

}

```

Then, we create a dialog on the scene so it looks similar to this:

Then, add a `PageableDialog` component to your new dialog. Remember to add a `CanvasGroup` to the main object. Then, two things.

Drop the `Page prefab` (this one made before) onto the `PageableDialog` object on the scene and set it's width/height so it looks like you want on the dialog. Then, drop the Page back onto the prefab to save changes and REMOVE Page object from the `PageableDialog` so it looks exactly like on the image above.

Then, set the `CanvasGroup` alpha back to 0 so it's invisible during start and save `PageableDialog` as a prefab too so you have two prefabs now.

Here's how it should look like:

Finally, create a 3rd class, `DialogsManager`:

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

public class DialogsManager : MonoBehaviour {

    public PageableDialog pdPrefab;
    public Canvas canvas; // dialogs must be on some canvas

    public PageableDialog CreatePageableDialog(){
        return Instantiate(pdPrefab, canvas.transform);
    }

    private static DialogsManager instance;
    public static DialogsManager Instance() {
        if(!instance){
            instance = FindObjectOfType(typeof (DialogsManager)) as DialogsManager;
            if(!instance)
                Debug.Log("There need to be at least one active DialogsManager on the scene");
        }

        return instance;
    }
}

```

A singleton pattern creates a new dialog for us. We can customize it and show, wherever we want.

To use a dialog, make some button on your scene and make it run this code:

```
PageableDialog dialog = DialogsManager.Instance().CreatePageableDialog();
dialog.AddPage("Hello there 1");
dialog.AddPage("Hello there 2");
dialog.AddPage("Hello there 3");
dialog.OnAccept("Accept!", () => {
    Debug.Log("FINISHED");
    dialog.Hide();
});
dialog.SetTitle("Some NPC");
dialog.SetSubtitle("Some quest");
dialog.Show();

```

Also, create a `Close Button` in the `PageableDialog` prefab. Make it run method `PageableDialog.Hide()` like there:

so it closes and destroys the dialog.

If you're lazy, here's a complete package I've just shown above: https://www.dropbox.com/s/lirllhhx3afaag0/DialogsScene.unitypackage?dl=0

Create a new project, click `Assets -> Import -> Custom Package`. Open the `TestScene` and click the button in the game.

Have fun! :)
> 13 votes

# Answer
Based on the response, I created something a little less object oriented to manage the dialog. Also, I couldn't get the CanvasGroup working, so I went with a panel. But it does require use of some magic strings.

Create a Panel that contains two Text and two Button named: title, message, button1, button2

(you can tweak the code and visual to suit your needs)

Also, if you want the popup to appear to be modal, create two panels. The outer one will anchor center with zero margins and have a dark semitransparent image. Then the child panel will be this dialog

I stored the panel as a prefab, but not sure if that's really necessary. Be sure to set the panel to inactive at design time

This technique could also be expanded to ask the user for input. Add an InputField, and change the Actions into

```
Action<string>

```

Calling code:

```
public class ButtonHandler : MonoBehaviour
{
    public Button Button;
    public GameObject Dialog;  //this is the panel
    //public GameObject Dialog_Another;

    void Start()
    {
        Button.onClick.AddListener(Button_Clicked);
    }

    private void Button_Clicked()
    {
        YesNoDialog.ShowDialog
        (
            Dialog,
            "Sanity Check",
            "Are you sure?",

            "No",
            null,

            "Yes",
            () => Button.image.color = UnityEngine.Random.ColorHSV(0, 1)
        );
    }
}

```

Wrapper that sets up and shows/hides the panel:

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

public static class YesNoDialog
{
    //NOTE: If the panel you're using doesn't have title or message, the value passed in will be ignored
    public static void ShowDialog(GameObject panel, string title, string message, string button1Text, Action clicked1, string button2Text, Action clicked2)
    {
        Text[] labels = panel.GetComponentsInChildren<Text>();

        Text lblTitle = labels.FirstOrDefault(o => o.name == "title");
        if (lblTitle != null)
            lblTitle.text = title ?? "";

        Text lblMsg = labels.FirstOrDefault(o => o.name == "message");
        if (lblMsg != null)
            lblMsg.text = message ?? "";

        Button[] buttons = panel.GetComponentsInChildren<Button>();

        var btn1 = buttons.FirstOrDefault(o => o.name == "button1");
        if (btn1 != null)
            SetupButton(panel, btn1, button1Text, clicked1);

        var btn2 = buttons.FirstOrDefault(o => o.name == "button2");
        if (btn2 != null)
            SetupButton(panel, btn2, button2Text, clicked2);

        panel.SetActive(true);
    }

    private static void SetupButton(GameObject panel, Button button, string text, Action clicked)
    {
        Text label = button.GetComponentInChildren<Text>();
        if (label != null)
            label.text = text;

        button.onClick.RemoveAllListeners();
        button.onClick.AddListener(() =>
        {
            clicked?.Invoke();
            panel.SetActive(false);
        });
    }
}

```
> 0 votes

---
Tags: unity
---


title: Rotate quaternion around plane normal

text:
# Question
Title: Rotate quaternion around plane normal
How can one rotate a quaternion so that the rotation is around a plane normal?

A graphic/diagram I made below gives more detail about what exactly I am implying. Note that the tip of the quaternions in the diagram are that of the quaternions local, upwards direction, symbolizing roll (the quaternion's *w* component).

*English describing the diagram:*

The rotation is around plane normal (vector) **N** with amount θ. The global axes are X, Y, and Z (Y is up). The plane normal and quaternion are both in global space. Notice how the beginning and end of the operation does not use any reference to the global axes, only the plane.

The angle between the start quaternion (q) and end quaternion (q') and the plane is equal (a = a'). If you were to draw lines from the tips of the quaternions to the plane, the angles of intersection would be equal. In other words, the roll of the quaternions are preserved in relation to that of the plane.

---

*EDIT 6/21/2020:* Thanks to Theraot, this is possible simply by doing this in your favorite engine with quaternions:

```
quaternion qPrime = quaternion.AxisAngle(normal, θ) * q;

```

As Theraot states in his answer, order of multiplication **does matter**, and some engines may do the opposite operation compared to other engines. For Unity's Mathematics package, the above pseudo-code holds true. The formula for AxisAngle can be found by a simple google search. The following Gif shows it working while proving that all angle requirements I stated above are satisfied.

# Answer
You can create a quaternion from an axis and the angle. Use this to create a quaternion to represent the rotation around the normal of the plane by the angle theta. Then compose that quaternion with your quaternion q, which will yield a new quaternion q' which is equivalent to rotating q round the normal of the plane by the angle theta.

You need to be aware of the direction of the normal and sign of the angle, which might result in rotating in the opposite direction.

Composing the rotations of the quaternions is just multiplication of the quaternions (and normalize the result). And, yes, the order matter.

---

I haven't internalized how to order my quaternions. And, you know, engines are not helping. Apparently the product of two unit quaternions a * b means rotating by b and then by a in Unreal Engine (documentation, documentation), but it means rotating by a and then by b in Unity (documentation). *I believe Unreal is right.* Thankfully there are only two ways it can be, try one way, and if it isn't, try the other way.

---

If you are going to implement your own quaternion operations, I suggest Developing a Math Engine in C++: Implementing Quaternions. *Getting a quaternion form axis and angle, and quaternion multiplication are covered there.*
> 2 votes

---
Tags: mathematics, rotation, quaternion
---


title: Texture blends into one single color

text:
# Question
Title: Texture blends into one single color
It looks like that it's being sampled from the least detailed MIP level, at least RenderDoc sees the texture as it should be, and what the actual texture looks like is the same as MIP 9th. I'm using DirectXTex, so I think the shader resource view should be correct.

```
    DirectX::ScratchImage* pImageData = new DirectX::ScratchImage();
    LoadFromDDSFile(path.c_str(), DirectX::DDS_FLAGS_NONE, nullptr, *pImageData);
    const DirectX::TexMetadata& textureMetaData = pImageData->GetMetadata();
    const DirectX::Image* image = pImageData->GetImage(0, 0, 0);
    DirectX::CreateShaderResourceView(
        GetDevice(gfx),
        image, textureMetaData.mipLevels,
        textureMetaData,
        &pShaderResourceView);

```

and the sampler is

```
    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_ANISOTROPIC;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 4;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

    DX::ThrowIfFailed(GetDevice(gfx)->CreateSamplerState(&samplerDesc, &pSamplerState));
    pImageData->Release();

```

then

```
    GetContext(gfx)->PSSetShaderResources(0u, 1u, &pShaderResourceView);
    GetContext(gfx)->PSSetSamplers(0u, 1u, &pSamplerState);

```

Input layout might be relevant

```
    const std::vector<D3D11_INPUT_ELEMENT_DESC> inputElemDesc =
    {
        {"Position", 0u, DXGI_FORMAT_R32G32B32_FLOAT, 0u, D3D11_APPEND_ALIGNED_ELEMENT,
        D3D11_INPUT_PER_VERTEX_DATA, 0u},
        {"TexCoordinate", 0u, DXGI_FORMAT_R32G32_FLOAT, 0u, D3D11_APPEND_ALIGNED_ELEMENT,
        D3D11_INPUT_PER_VERTEX_DATA, 0u},
        {"Normal", 0u, DXGI_FORMAT_R8G8B8A8_UNORM, 0u, D3D11_APPEND_ALIGNED_ELEMENT,
        D3D11_INPUT_PER_VERTEX_DATA, 0u}
    };

```

Vertex shader

```
struct VertexIn
{
    float3 position : Position;
    float2 texCoord : TexCoordinate;
    float3 normal : Normal;
};

struct PSstruct
{
    float4 PosH : SV_Position;
    float3 PosW : Position;
    float3 NormalW : Normal;
    float2 Tex : TEXCOORD;
};
PSstruct main(VertexIn vin)
{
    PSstruct vout;

    vout.Tex = vin.texCoord;;
    return vout;
}

```

pixel shader. I removed light related code, I'm fairly sure that here it's not important. And I temporarily disabled it

```
Texture2D cubeTexture : register(t0);
SamplerState cubeSample : register(s0);

struct PSstruct
{
    float4 PosH : SV_Position;
    float3 PosW : Position;
    float3 NormalW : Normal;
    float2 tex : TEXCOORD;
};
float4 main(PSstruct pin) : SV_TARGET
{
    float4 texColor = float4(1, 1, 1, 1);
    texColor = cubeTexture.Sample(cubeSample, pin.tex);
    float4 litColor = texColor;
    return litColor;
}

```

# Answer
> 0 votes
Texture coordinates were wrong. The ones that I was sending to vertex buffer.

---
Tags: c++, textures, directx11, hlsl
---


title: SAT Collisions: Resolving rotations

text:
# Question
Title: SAT Collisions: Resolving rotations
Currently I have a working 2D SAT collision system with only boxes, but works with static rotations as well, leaving room for triangles. One of the issues I've been able to resolve was tunnelling, thanks to this thread's psuedocode that I got working for myself.

Problem is, this doesn't support moving rotations like a system using a minimum-translation-vector. If I rotate alongside the side of an object, the system will fail even if I'm not moving.

My first thought in solving this was to use the longest line you can draw in a square (that being the points on either side of a square) and comparing the length of that to whatever side on any axis, but even squares have different sizes on any given rotation projected onto an axis.

The system also doesn't work with multiple objects, because - while you can use the algorithm on a group of objects and find the shortest distance out of all of them - if I conserve my velocity relative to the colliding axis, diving into the crest of 2 objects means I will phase through one of them not beyond a 45 degree angle.

Is there an effective way to resolve collisions on rotations and groups of objects, while using this anti-tunnelling algorithm? I don't care if it's expensive, I'll take whatever you can think of.

# Answer
> 1 votes
I am not sure how you can use SAT to resolve continuous rotations but I know of two other algorithms that may do the trick, however they are made for convex shapes. The first one is conservative advancement(you can check out Erin Catto's presentation on youtube) this will give you the time of impact using translation and rotation and of course does take up some resources.

An other algorithm is GJK Raycast, it is less precise but takes up less resources. It can give you a lower time bound where you are sure that the objects will not be intersecting at that time bound. This algorithm is exact for translation, but for rotation you must "swipe" a sphere on your collider to encapsulate the rotation. Even though it's not precise it's still pretty decent. You can read more about this on Gino Van Bergen's papers(http://www.dtecta.com/papers/unpublished04raycast.pdf) or on his website (dtecta.com). However I once heard that it is impossible to resolve exactly continuous collision detection in real time, so yes it is possible but not in real time. I personally do static checks (GJK & EPA) for "slow objects" and I do a GJK raycast test for "fast" moving objects vs "slow" moving objects. It's not exact but it still gives decent results, the player/projectiles cannot go though walls anymore.

In the end I didn't really answer your question though, I haven't seen any papers on SAT continuous collision detection it probably is possible, although it might be just as complicated or maybe even more than the algorithms described above. Hope this helped at least a bit.

---
Tags: collision-detection, collision-resolution, separating-axis-theorem
---


title: Sprite changing position on its own?

text:
# Question
Title: Sprite changing position on its own?
I have a simple 2d scene, where I'm trying to have a sprite at x = -8 which I can move up and down. The problem is, when playing the scene, the sprite "jumps" by itself to the middle, x = 0, for no apparent reason. It then only goes back to x = -8 when there is input to move it. How do I get it to stop "jumping" to the middle at the start of every play?

```
using UnityEngine;
public class player1 : MonoBehaviour
{
     Vector2 targetPos;
     public float speed;
     public float step;
     void Start()
     {
         transform.position = new Vector2(-8,0);
     }
     void Update()
     {
         if (Input.GetKey("w") && transform.position.y < 3.8)
         {
             targetPos = new Vector2(-8, transform.position.y + step);
         }
         if (Input.GetKey("s") && transform.position.y > -3.8)
         {
             targetPos = new Vector2(-8, transform.position.y - step);
         }
         transform.position = Vector2.MoveTowards(transform.position, targetPos, speed);
     }
}

```

# Answer
> 1 votes
targetPos is initialised by default to (0,0), which causes the sprite to move to the centre. Add to the start() method `targetPos = new Vector2(-8,0);` which correctly initialises it to the desired position.

---
Tags: unity
---


# Question
Title: Game() parametters Content and Window are not pre initialized
I've been experiencing a really Strange problem since recently, Every variables of XNA Framework Game class seems not to be initialized before my extending Game1 class. Variables does not seem to be initialized before the point where they should be.

I do not plan to change the game engine, but I'll appreciate any help of any kind.

Thanks for your time

here is my Game1 class (a small part of it)

```
public class Game1 : Game
{
  public static GraphicsDeviceManager graphics;
  public static SpriteBatch spriteBatch;
  public static ContentManager ContentManager;
  public static SceneManager SceneManager { get; private set; }

  public Game1()
  {
    ContentManager = Content;

    graphics = new GraphicsDeviceManager(this);
    ContentManager.RootDirectory = "Content";

    // TODO: Add your initialization logic here
    /*
    GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height
    GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width
    */
    Window.IsBorderless = true;
    graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
    graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
    IsMouseVisible = true;

  }

    (...) //The code continues
}

```

and here is the errors:

the Null pointer error on the Window variable occures when i declare a new Content manager

---

Edit:

It seem that there is a conflict between System.RunTime.Serialization v4 and v2 in my project

```
1>  Impossible de résoudre le conflit entre "System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" et "System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes". Choix arbitraire de "System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089".

```

# Answer
> 0 votes
Problem solved

i solved it by creating a new Monogame project and copying the code and the content folder into my new project folder. I did not copied the 'bin/', 'obj/', 'packages/', 'x86/' & 'x64/', 'Content/bin' and 'Content/obj' since they are built automatically. then I rebuilt the content pipeline. Everything works fine except a spriteFont not loading because I've voluntarily deleted it at some point. Note that if you do like me you will need to reimport libraries that you used and worked before having your problem.

conclusion I can get from my experience, Bad usage of some libraries can cause the project to break for ever. In my case, the game class was not initializing.

Hope this will help everyone in my situation.

bye

---
Tags: c#, xna, monogame
---


# Question
Title: Is a Computer Graphics book being outdated a problem?
Me and my friends decided to make a game engine as a graduation project and this summer we are dedicating ourselves to really get into the knowledge we need before actually starting the project.

We are starting by watching the UC San Diego CG course(s) (there is an advanced course now) and also read the Essential Mathematics for Games and Interactive Applications 3rd Edition book (we are a bit undecided about the book so if you have any comments about it we will greatly appreciate them).

Our problem mainly is that while googling for CG books, answers on this community and even on other sites seem to always suggest outdated books (like Computer Graphics C Version 2nd Edition).

Now, I personally don't think a book being outdated is *necessarily* bad, but it could be. Depends on how differently things in the 2020 are being done and as a beginner I am obviously ignorant of that aspect.

Is a book being outdated a problem?

# Answer
It depends on the focus of the book.

If it is merely explaining the mathematical theory behind 3d rendering, then the math did not change.

But if it actually teaches you 3d graphics APIs, then you should look for a more recently written book. Because a lot of those changed a lot in the past years. When the book is from 1997, then it won't even know about programmable shaders yet - the fundamental building block of any modern GPU-accelerated 3d renderer.

If you really want to know what exactly you need to learn for your project, then I would recommend to search the Internet for a basic and recently written OpenGL, Direct3D or Vulkan tutorial. You will soon see what theoretical and practical knowledge you will need for your project and can then look for resources which provide you with that knowledge.
> 1 votes

# Answer
There are a couple reason why recommendation may tend to bias to older books, regardless of whether or not the older books are better.

One is that the longer a book is out the more people may have had a chance to read it. Which implies it is likely that less people have read the modern book, and thus less people would be willing to recommend it.

The other is that you will find older results that predates many modern books. They could not possibly have recommended a book that was not out yet.

---

Plenty of OpenGL books will cover some topics of computer graphics, and many books on computer graphics will have examples with OpenGL. And the OpenGL code might be obsolete.

However, focusing on the computer graphics, it is a safe bet to start with an older book. The math does not change, but new algorithms are developed. It often helps to understand the older algorithms to understand the recent ones. Plus, that a book is newer does not mean it has more advance contents.

---

About Computer Graphics C Version, it is certainly dated. It goes on and on about old hardware, not a problem, skip that. It is not focused in games. However it covers a lot of 2D and 3D graphic algorithms that you'd miss with the other book. If you want to learn the nitty-gritty of old graphic algorithms, this book is great. It covers the essential math in an appendix.

About Essential Mathematics for Games and Interactive Applications, I have the second edition, it does a great job covering the essential math (it is in the title after all), and it goes straight to 3D. I find this book more practical, it will get you started much faster, but it also seem to fall short, staying too much in the essential. There is a little OpenGL code in this book, those can be ignored.

---

My recommendations is Physically Based Rendering: From Theory To Implementation. This book cover some not so essential math (it assumes you understand some basics), and will go into implementing the pbr as the title suggests among other modern shading techniques. Consider it a complement to either of your picks. There is a free version online.

---

*And of course, if you run into something you don't understand, we have the stackexchange network.*
> 1 votes

---
Tags: books
---


# Question
Title: How should I handle interrupting the current goal with goal-oriented action planning?
I'm reading about goal-oriented planning for AI, but there I'm having difficulty finding an implementation so that I can address some questions that I have. Specifically, I don't understand how to handle scenarios in which an agent is in the middle of a goal, but then another goal gets calculated as higher priority. For example, suppose I have the following goals/subgoals/actions

```
MineGold (goal)
|--> MoveToGoldMine (goal)
|    |--> MoveToPosition (action)
|--> SwingPickaxe (action)
|--> TakeGold (action)
|--> DeliverGold (goal)
|    |--> MoveToTownHall (goal)
|    |    |--> MoveToPosition (action)
|    |--> DropGold (action)

AvoidEnemy (goal)
|--> MoveToHidingSpot (goal)
|    |--> MoveToPosition (action)
|--> Wait (action)

AttackEnemmy (goal)
|--> MoveToEnemy (goal)
|    |--> MoveToPosition (action)

```

When the game starts, my agent calculates its goal priorities and its highest priority is the `MineGold` goal. So it pushes the list of subgoals and actions for `MineGold` onto its planning stack.

Suppose the agent moves to the gold mine, mines the gold, takes the gold, and then starts to move back to the town hall. While it's moving back to the town hall, an enemy soldier gets close enough such that the `AvoidEnemy` goal becomes higher priority than the `MineGold` goal. So now the agent pushes the `AvoidEnemy` subgoals and actions into its stack, ahead of the remaining `DeliverGold` subgoal.

While the agent is avoiding the soldier, an enemy assassin sneaks up on his team's commander. The commander calls for help so the `AttackEnemy` goal becomes the highest priority. So `AttackEnemy` is pushed onto the stack ahead of `AvoidEnemy`.

Eventually the assassin is killed, so the `AttackEnemy` goal is no longer valid and gets popped off the stack. Now the topmost goal is `AvoidEnemy` to avoid the enemy soldier. But if my agent just attacked the assassin, it would be weird for him to then start running away from the soldier (or maybe the soldier is already far away and I don't want to keep moving to a hiding spot), so I would rather him return to his original goal of `DeliverGold`.

Here are my questions:

1. Am I correct in assuming that I should be periodically recalculating the highest priority goal and switching to the highest priority goal if it's different than the existing goal?
2. Am I correct that when a new goal becomes higher priority than the current goal, then I should be pushing that new goal onto the stack ahead of the current goal, as opposed to overwriting the current goal with the new goal?
3. Assuming I'm correct that new goals are additive, how do I handle this situation where sometimes I don't want an agent to return to certain prior goals? I know that I could accomplish this through a set of "mutually exclusive" flags or something, but that seems like an inelegant way and that it would start to return me to using finite state machines instead of goal-oriented planning.

# Answer
> 2 votes
> Am I correct in assuming that I should be periodically recalculating the highest priority goal and switching to the highest priority goal if it's different than the existing goal?

Yes. If you have an agent with multiple goals, you need to keep their priorities updated, and make sure the agent is on the highest priority one.

---

> Am I correct that when a new goal becomes higher priority than the current goal, then I should be pushing that new goal onto the stack ahead of the current goal, as opposed to overwriting the current goal with the new goal?

This works. It does not have to be this way.

---

> Assuming I'm correct that new goals are additive, how do I handle this situation where sometimes I don't want an agent to return to certain prior goals? I know that I could accomplish this through a set of "mutually exclusive" flags or something, but that seems like an inelegant way and that it would start to return me to using finite state machines instead of goal-oriented planning.

When you pop your goal, you check if it is still valid. You need to know when goals are valid. And don't bother with invalid goals. You don't need to update the priority of a goal if it is not valid, you just ignore the goal.

---

The system you describe is not what I would call goal-oriented. Perhaps I'm confusing terms here. Are you hard-coding plans?

For instance, I would expect that "DeliverGold" would be a goal, not "MineGold". I would expect the AI to be able to find a plan that involves a mine. But it does not have to involve a mine. Perhaps it can pick some gold from the ground if there was any.

And, no, you would not put it on a stack. If something else has higher priority, you drop the plan, and move to the new goal. If, eventually, the priority of the original goal is the higher again, then it makes a new plan. *Perhaps by picking some gold from the ground that it had dropped because it was doing a plan for a different goal that required dropping the gold to pick something else.*

So, if the goal is to deliver gold, the AI will find that the precondition is to have gold. So the agent can search all action that can give gold, then it will find that gold mines can give gold. Then it checks the preconditions of those actions. And it will find that it needs a pick tool. Then it searches all actions that can give a pick tool, and so on. Until it reaches an action that it can perform right away. BY doing this, the AI agent can create its own plan. *This example describes backtracking, other search approaches also work.*

---

That does not mean that your approach does not work. You just need to add checks for goals being valid. If the enemy is too far away, then don't make "AvoidEnemy" a valid goal.

---

*You might also be interested in smart objects.*

---
Tags: ai, planning
---


# Question
Title: Increase speed when score gets high or when the fish eats pellets
I want fish to increase speed when score gets high, or when the fish eats some balls

```
public class FlyingFishView extends View
{
    private Bitmap fish[] = new Bitmap[2];
    private int fishX = 10;
    private int fishY;
    private int fishSpeed;

    private int canvasWidth,canvasHeight;

    private int yellowX,yellowY,yellowSpeed = 10;
    private Paint yellowPaint = new Paint();

    private int  greenX,greenY,greenSpeed = 20;
    private Paint greenPaint = new Paint();

    private int  redX,redY,redSpeed = 25;
    private Paint redPaint = new Paint();

    private int score, lifeCounterOfFish;

    private boolean touch = false;

    private Bitmap backgroundImage;
    private Paint scorePaint = new Paint();
    private Bitmap life[] = new Bitmap[2];

    public FlyingFishView(Context context)
    {
        super(context);
        fish[0] = BitmapFactory.decodeResource(getResources(),R.drawable.fish1);
        fish[1] = BitmapFactory.decodeResource(getResources(),R.drawable.fish2);

        backgroundImage = BitmapFactory.decodeResource(getResources(),R.drawable.background);

        yellowPaint.setColor(Color.YELLOW);
        yellowPaint.setAntiAlias(false);

        greenPaint.setColor(Color.GRAY);
        greenPaint.setAntiAlias(false);

        redPaint.setColor(Color.RED);
        redPaint.setAntiAlias(false);

        scorePaint.setColor(Color.WHITE);
        scorePaint.setTextSize(70);
        scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
        scorePaint.setAntiAlias(true);

        life[0] = BitmapFactory.decodeResource(getResources(),R.drawable.hearts);
        life[1] = BitmapFactory.decodeResource(getResources(),R.drawable.heart_grey);

        fishX = 550;
        score = 0;
        lifeCounterOfFish = 3;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvasWidth = canvas.getWidth();
        canvasHeight=canvas.getHeight();
        canvas.drawBitmap(backgroundImage,0,0,null);
        int minFishY = fish[0].getHeight();
        int maxFishY = canvasHeight - fish[0].getHeight() * 3;
        fishY = fishY + fishSpeed;
        if (fishY<minFishY)
        {
            fishY = minFishY;
        }
        if (fishY>maxFishY)
        {
            fishY = maxFishY;
        }
        fishSpeed = fishSpeed + 2 ;

        if(touch)
        {
             canvas.drawBitmap(fish[1],fishX,fishY,null);
             touch= false;
        }
        else
        {
            canvas.drawBitmap(fish[0],fishX,fishY,null);
        }

        yellowX = yellowX - yellowSpeed;
        if(hitBallChecker(yellowX,yellowY))
        {
            score = score + 10;
            yellowX = -100;
        }
        if (yellowX < 0 )
        {
            yellowX = canvasWidth + 21;
            yellowY = (int) Math.floor(Math.random()* (maxFishY - minFishY)) + minFishY;
        }

        canvas.drawCircle(yellowX,yellowY,25,yellowPaint);

        //Green
        greenX = greenX - greenSpeed;
        if(hitBallChecker(greenX,greenY))
        {
            score = score + 20;
            greenX = -100;
        }
        if (greenX < 0 )
        {
            greenX = canvasWidth + 21;
            greenY = (int) Math.floor(Math.random()* (maxFishY - minFishY)) + minFishY;
        }

        //DangerRedBall
        redX = redX - redSpeed;
        if(hitBallChecker(redX,redY))
        {
            redX = -100;
            lifeCounterOfFish--;

            if (lifeCounterOfFish == 0)
            {
                Toast.makeText(getContext(),"Game Over",Toast.LENGTH_SHORT).show();

                Intent gameOverIntent = new Intent(getContext(),GameOverActivity.class);
                gameOverIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                gameOverIntent.putExtra("score",score);
                getContext().startActivity(gameOverIntent);
            }
        }
        if (redX < 0 )
        {
            redX = canvasWidth + 21;
            redY = (int) Math.floor(Math.random()* (maxFishY - minFishY)) + minFishY;
        }

        canvas.drawCircle(redX,redY,30,redPaint);

        canvas.drawText("Score : " + score ,20,60,scorePaint);

        for (int i=0;i<3;i++)
        {
            int x =(int)  (580 + life[0].getWidth() * 1.5 * i);
            int y = 30;

            if (i < lifeCounterOfFish)
            {
                canvas.drawBitmap(life[0],x,y ,null);
            }
            else
            {
                canvas.drawBitmap(life[1],x,y,null);
            }
        }

        canvas.drawBitmap(life[0],580,10,null);
        canvas.drawBitmap(life[0],640,10,null);
        canvas.drawBitmap(life[0],780,10,null);
    }

    public boolean hitBallChecker(int x,int y)
    {
        if (fishX < x && x <(fishX + fish[0].getWidth()) && fishY < y && y <(fishY + fish[0].getHeight()))
        {
            return true;
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
        {
            touch = true;
            fishSpeed = -22;
        }
        return true;
    }
}

```

# Answer
Please note that we generally expect users to show some effort when asking questions. Also, we expect them to show us only the relevant code necessary for the question. We also expect them to be precise with what they need. Although your question was really badly formatted at first, the downvotes you got probably come from your lack of research and code dumping.

I'll assume that you're new to asking questions online. This is a difficult skill to master.

I'll assume that you're new to gamedev and to programming in general, that you have found a complete tutorial on the internet and try to change it a bit to understand how stuff works.

I'll also assume that when you mention "speed", you mean the speed of the fish.

---

In the code you have posted, when we search "speed", we find a variable named `fishSpeed`. This variable is used to move the fish right (`fishY = fishY + fishSpeed;`). It is also incremented each frame (in the `onDraw` function; `fishSpeed = fishSpeed + 2 ;`).

We also see the variable `score`, which is incremented when the fish eats a yellow or green pellet. (`score = score + 10;` and `score = score + 20;`).

We need to combine these two values. We'll use math to make it based on the score:

```
fishSpeed = 2 + (score / 10);

```

This is a first step. Try and see how it goes. Then you can play with maths more, you could also add a variable which counts how many frames your in and further increase the speed of the fish if needed (e.g. `fishSpeed = (2 * frameCounter) + (score / 10);`).

---

Gamedev and math require you to read a lot of code, and really understand what goes on before modifying anything. Making games is hard, there is no instant satisfaction, but once you have something that works, it's really nice!
> 1 votes

---
Tags: java
---


# Question
Title: Is a 3D renderer with 1000 FPS possible?
Okay, for my phD Thesis, I need to make a simple 3D game, like towers of hanoi or whatever but there is a condition:

I need it to have high FPS, as in, the highest FPS achievable, atleast a 1000FPS. I need to have a high FPS to measure reaction times. We achieve this with 1ms monitors BUT on the programming front, here is the problem,

1. I'm confused if I should code an entire specially made engine with only the features I need (using Vulkan), and if I did would it be faster than already available engines like Unity or Unreal? Would it be worth the time and effort or can these engines be customised themselves and is that easier than doing it from scratch?
2. Or is it only achievable with specialized hardware? So I'd be better of using an available engine and going hard on the hardware?

# Answer
> 1 votes
Sure, you could do that with e.g. C#, Java/Scala, C or Rust. But in order to run an engine at that frame rate, *all* of your per-frame processing - i.e. one game loop cycle - would need to *consistently fit into a 1 millisecond window* \- this is practically impossible to achieve, even for simple games, and especially for those not familiar with optimising game loops.

You might want to look into high precision hardware timers instead. You will need to see whether they are supported in your language of choice; certainly C will always have access to such timers, where they exist in the system at all. You would probably need to use a lower level language like C or Rust to achieve this.

To quote that link,

> In many cases you may just want to read the counter value to implement a simple delay function *that does not depend on the frequency* of the processor or speed *of executing a particular code sequence*.

That is, hardware timers are independent of the frequency of your loop, e.g. 1khz suggested.

---
Tags: unity, unreal, vulkan
---


# Question
Title: Tilemaps are loading differently each time
Tilemap data is stored in a 2D array.

It is saved using the following code

```

void Chunk::save_to_file() {

    // FILENAME
    std::string filename = std::to_string(chunk_seed);

    std::fstream file;
    file.open(filename + ".chunk", std::ios::out);

    for (int i = 0; i < Constants::BIOMESIZE; i++) {
        for (int j = 0; j < Constants::BIOMESIZE; j++) {
            file << std::to_string(chunk[i][j]);
            file << ",";
        }
    }

    file.close();

}

```

And it is loaded using the following code

```

void Chunk::load_from_file() {
    // FILENAME
    // The chunk will be located at hash(chunk_x, chunk_y) ^ seed = chunk_seed
    std::string filename = std::to_string(chunk_seed);
    // Data within file
    std::string data;

    std::fstream file;
    file.open(filename + ".chunk", std::ios::in);
    file >> data;
    file.close();

    std::vector<std::string> tokens = split(data, ',');

    for (unsigned int i = 0; i < Constants::BIOMESIZE; i++) {
        for (unsigned int j = 0; j < Constants::BIOMESIZE; j++) {
            chunk[i][j] = std::stoi(tokens[i + j * Constants::BIOMESIZE]);
        }
    }
}

```

Tilemaps are *loaded* using the loading function when the program is started up and displayed.

Tilemaps are *saved* using the saving function when the program is exited.

They do not display the same way each time.

I have pinpointed that the problem is in the saving function.

This is because I commented out the saving part and when I was only loading the same files it worked and had the same output each time.

It appears as though the saving function rotates the tilemap by 180 degrees each time I save it.

How can this be fixed?

# Answer
The rotation comes from the calculation of the index in `load_from_file()`, it should be:

```
chunk[i][j] = std::stoi(tokens[i * Constants::BIOMESIZE + j]);

```

That said, it would be much better if you could save the file in such a way that you can load it back the same way. Instead of using `","` as a separator, use a space (`" "`). Then you can read it in like so:

std::ifstream file(filename + ".chunk");

for (unsigned int i = 0; i < Constants::BIOMESIZE; i++)
    for (unsigned int j = 0; j < Constants::BIOMESIZE; j++)
        file >> chunks[i][j];
```

> 2 votes

---
Tags: c++, tilemap, sfml, savegame, file-format
---


# Question
Title: Persisting score when restarting level after a rewarded video ad
I'm trying to create a reward system in my game where once the player dies, they have the option of watching a rewarded video ad after which the game restarts and the player score is set to score before the player died. I have been trying to figure this out for the last 2 hours but unable to achieve the desired result. This is my game manager script:

```
public class GameManager : MonoBehaviour
{
  public Player player;
  public Transform startLocation;

  public GameObject startPanel, ingamePanel, gameoverPanel;

  private bool gameHasStarted;

  public enum GameStates
  {
    Start,
    InGame,
    GameOver
  }

  public float playerScore = 0;
  private int savedScore;
  private int difficultyLevel = 1;
  private int maxDiffLevel = 10;
  private int scoreToNextLevel = 10;

  private void Start()
  {
    SetupNewGame();
  }

  void Update()
  {
    if(playerScore >= scoreToNextLevel)
    {
        LevelUp();
    }

    if (player.dead == false && gameHasStarted)
    {
        playerScore += Time.deltaTime * difficultyLevel;
    }

    if (playerScore > PlayerPrefs.GetInt("HighScore", 0))
    {
        PlayerPrefs.SetInt("HighScore", (int)playerScore);
    }
}

 void LevelUp()
 {
    if (difficultyLevel == maxDiffLevel)
        return;
    scoreToNextLevel *= 2;
    difficultyLevel++;

 }

public void SetupNewGame()
 {
    playerScore = 0;
    player.transform.position = startLocation.position;
    UpdateUI(GameStates.Start);
 }

 public void StartNewGame()
 {
    player.dead = false;
    gameHasStarted = true;
    UpdateUI(GameStates.InGame);
 }

public void GameOver()
{
    player.dead = true;
    gameHasStarted = false;
    UpdateUI(GameStates.GameOver);
}

void UpdateUI(GameStates gameState)
{
    startPanel.SetActive(false);
    ingamePanel.SetActive(false);
    gameoverPanel.SetActive(false);

    if (gameState == GameStates.Start)
    {
        startPanel.SetActive(true);
    }
    if (gameState == GameStates.InGame)
    {
        ingamePanel.SetActive(true);
    }
    if (gameState == GameStates.GameOver)
    {
        gameoverPanel.SetActive(true);
    }
}

 public void ReceiveLife()
 {
    savedScore = (int)playerScore;
    SceneManager.LoadScene(1);
    playerScore = savedScore;

 }
}

```

I have created a button for and added the ReceiveReward() in the onClick function. However when I click on this button, the score is reset to 0 and not the score before the player died. Can someone please help?

**EDIT 1**

I have added this code to the game manager:

```
private void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
}

```

The score is still reverting to 0.

**EDIT 2**

As per the code provided by @DMGregory, the revive button is working on. Now I'm trying to implement reward based video ads in my game for two buttons. There are two functions that provide the reward. One is a ReceiveLife() function where once the player dies, if they click on the revive button the game restarts and the score is set to score before the player dies instead of 0. The other function is ReceivePoints(), where if the player clicks on the add points button, they are rewarded with 100 extra points. Here are the functions in the game manager script:

```
public void ReceiveLife()
 {
   savedScore = (int)playerScore;
   SceneManager.LoadScene(1);
 }

public void ReceivePoints()
 {
   playerScore+=100;
   gameOverPanel.gameOverScoreText.text = "Score: " +
                                           (int)playerScore).ToString();
 }

```

Here is the unity ads manager script:

```
 public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
 {
  if (showResult == ShowResult.Finished)
   {
    gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    gameManager.ReceiveLife();
   }

  if (showResult == ShowResult.Finished)
   {
    gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    gameManager.ReceivePoints();
   }
  }

```

Once they watch the ad successfully, both the functions are being called. If the player clicks on the ReceiveLife(), he should only get one extra life and not the additional 100 points and vice-versa.

I'm not sure how to call each function separately. Do I have to create two separate admanagers in order to call these functions or is there a better method?

# Answer
> 0 votes
A quick and dirty fix would be this:

Make your `savedScore` a `static` variable, so it's shared between instances of this class.

```
static int savedScore = 0;

```

On startup, copy the saved score into your current score, and reset it for next time.

```
public void SetupNewGame()
{
    playerScore = savedScore;
    savedScore = 0;
    player.transform.position = startLocation.position;
    UpdateUI(GameStates.Start);
}

```

Now when you want to persist the score, you save it just before the scene load. If the player doesn't claim the reward, the `savedScore` stays at zero where we'd reset it to.

```
public void ReceiveReward()
{
    savedScore = (int)playerScore;
    SceneManager.LoadScene(1);
}

```

Here I assume that this script is part of the scene that's being unloaded and re-loaded, so you get a fresh instance that runs its own `Start()` next frame, after the scene has been refreshed.

# Answer
> 0 votes
The linked question gives you a few suggestions that all work, what is best for your game is for you to decide, how much data you have in other scripts that you need to transfer, etc. If your game is as simple as that, you may get away with a static data holding script.

The why you see `score = 0` is, that `SceneManager.LoadScene(1);` is the same as when you would load the scene for the first time. Your `start()` is called again, the whole `gameManager` is a different one (no reference to your saved score, it does not exist anymore).

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


# Question
Title: Euler angle and Quaternion conversion become weird when yaw is bigger than 90 degrees
I'm writing a camera which needs to change a quaternion to Euler angles than change them back, it only works when the yaw is less than 90 degrees, I wrote a example to check:

```
glm::vec3 euler_angler = {0, 0, 0};
  for (int i = 0; i < 91; i++) {

    std::cout << "before: " << euler_angler.x << ", " << euler_angler.y << ", " << euler_angler.z << std::endl;

    euler_angler.y += 1;

    glm::quat quat({glm::radians(euler_angler.x), glm::radians(euler_angler.y), glm::radians(euler_angler.z)});

    glm::vec3 new_euler_angler = glm::eulerAngles(quat);

    std::cout << "after: " << glm::degrees(new_euler_angler.x) << ", " << glm::degrees(new_euler_angler.y) << ", "

              << glm::degrees(new_euler_angler.z) << std::endl;

  }

```

and when the Euler angles is {0, 89, 0}, then the Euler angles changed back to `quat` is the same, which is {0, 89, 0}, but when the origin changes to {0, 90, 0}, the `new_euler_angler` suddenly becomes to {180, 89.0001, 180}, and makes my camera rotation a mess.

Can someone help why this happened and what should I do?

the code of my camera:

```
glm::vec3 euler_angler = glm::eulerAngles(transform_data.rotation);
euler_angler.x = euler_angler.x + glm::radians(delta_y);
euler_angler.y += glm::radians(delta_x);
euler_angler.z = 0;
transform_data.rotation = glm::quat(euler_angler);

```

and here's my calculation of view matrix(which is a suspect because all other tutorials are using lookat matrix, I'm not sure my way is right or not):

```
// the position and rotation of the camera
auto transform_data = actor_.GetTransform().GetData();
glm::mat4 view = glm::mat4(1.0f);
view = glm::translate(view, -transform_data.position);
view = glm::toMat4(glm::quat(transform_data.rotation.w,
                               -transform_data.rotation.x,
                               -transform_data.rotation.y,
                               -transform_data.rotation.z)) * view;
render_camera_.SetViewMatrix(view);
glm::mat4 projection;
projection = glm::perspective(glm::radians(fov_), (float) aspect_, 0.1f, 100.0f);
render_camera_.SetProjectionMatrix(projection);

```

# Answer
Your current code assumes it's always going to get Euler angles where x is between ±90° and z is close to 0.

Meanwhile, glm wants to return Euler angles that are standardized so that y is between ±90°, even if that means putting a large number in x & z to compensate.

So when you're in the vicinity of (0, 0-89, 0), your code behaves relatively intuitively. Adding +1 degree to the y makes your camera yaw 1 degree to the right, and adding +1 degree to the x makes your camera pitch 1 degree down (making some assumptions about your coordinate system).

When you cross 90 though, say to 91°, glm wants to keep y less than 90, so it picks an equivalent Euler angle triplet, (180, -89, 180). This is equivalent to yawing 180° opposite to the way you were facing, then pitching over backwards to reverse your heading, then rolling over to correct for the inversion. ie. It's still the same net orientation in the end.

But now, adding +1 degree to the x makes your camera pitch *up*, not down! (Because you've already pitched down 180 degrees, any more means wrapping around to the positive hemisphere now).

And the worst trouble comes from this line:

```
euler_angler.z = 0;

```

If z was close to zero as your code assumes, this would just neutralize any small bit of roll that had crept in. But we're 180 degrees away from that now, and we were counting on that 180° roll to turn us back upright after pitching ourselves upside-down. So zeroing this out actually has the effect of removing this correction and leaving the camera inverted.

Doing component-wise math on arbitrary Euler angles is fraught with problems, because the values on one axis can change the meaning of values on another axis.

A better solution for a pitch-yaw camera is to keep strict control over your Euler angles, so that you control when & where they wrap. You can store your desired pitch and yaw as member variables, so the only time their values change is when you deliberately add/subtract or wrap them. You can keep your z value always zero, so it's never roped into compensating for extreme pitch. And when you need a quaternion, you make one from your stored angles, keeping them as the sole source of truth describing the desired orientation.

As a bonus, this is faster - it's a lot quicker to read a couple floats from memory than it is to read a quaternion and then do all the trigonometry necessary to decode it into angles.
> 6 votes

---
Tags: quaternion, glm, euler-angles
---


# Question
Title: Rigidbody player controller on moving platforms
So basically, I was trying to make moving platforms. When I finished my prototype, I noticed that the movement on the platform is very wobbly: https://www.youtube.com/watch?v=hmBumsrlHGA&feature=emb\_logo To snap the player onto the platform, I am just making it a child of the platform. Anyway, I don't know what is causing this issue and was wondering if I can get any help. Thank you in advance

Here, the controller code:

```
private void Movement()
    {
        //Extra gravity
        rb.AddForce(Vector3.down * Time.deltaTime * 10);

        //Find actual velocity relative to where player is looking
        Vector2 mag = FindVelRelativeToLook();
        float xMag = mag.x, yMag = mag.y;

        //Counteract sliding and sloppy movement
        CounterMovement(x, y, mag);

        //If holding jump && ready to jump, then jump
        if (readyToJump && jumping) Jump();

        //Set max speed
        float maxSpeed = this.maxSpeed;
        if (sprinting)
        {
            this.maxSpeed = 25;
        }
        else
        {
            this.maxSpeed = 15;
        }

        if(sprinting && y < 0)
        {
            this.maxSpeed = 15;
        }

        //If sliding down a ramp, add force down so player stays grounded and also builds speed
        if (crouching && grounded && readyToJump)
        {
            rb.AddForce(Vector3.down * Time.deltaTime * 3000);
            return;
        }

        //If speed is larger than maxspeed, cancel out the input so you don't go over max speed
        if (x > 0 && xMag > maxSpeed) x = 0;
        if (x < 0 && xMag < -maxSpeed) x = 0;
        if (y > 0 && yMag > maxSpeed) y = 0;
        if (y < 0 && yMag < -maxSpeed) y = 0;

        //Some multipliers
        float multiplier = 1f, multiplierV = 1f;

        // Movement in air
        if (!grounded)
        {
            multiplier = 0.5f;
            multiplierV = 0.5f;
        }

        // Movement while sliding
        //if (grounded && crouching) { multiplierV = 0.5f; multiplier = 0.5f; }

        //Apply forces to move player
        rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
        rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
    }

```

# Answer
> 0 votes
I have had a nearly identical issue in the past. I solved it by making my Rigidbody kinematic while it is childed to the platform.

```
void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
void landOnPlatform()
    {
        rb.isKinematic = true;
    }

```

This means that you will also have to determine when to turn the physics back on. It also has the major caveat of disabling physics on the Rigidbody while it is on the platform, but for my needs, this did the trick.

---
Tags: unity, rigidbody
---