title: glDrawElements draws nothing

text:
# Question
Title: glDrawElements draws nothing
As the title says…. :( nothing is drawn on screen… is there something I'm missing?

```
Mesh *Mesh_Create(GLfloat vertices[], GLuint indices[], GLfloat uvs[], GLfloat colors[])
{

Mesh *mesh = (Mesh*)malloc(sizeof(Mesh));

mesh->vertices = (GLfloat*)malloc(sizeof(vertices));
memcpy(mesh->vertices, vertices, sizeof(vertices));

mesh->indices = (GLuint*)malloc(sizeof(indices));
memcpy(mesh->indices, indices, sizeof(indices));

mesh->elementCount = sizeof(indices) / sizeof(GLuint);

glGenVertexArrays(1, &mesh->vao);
glBindVertexArray(mesh->vao);

glGenBuffers(1, &mesh->vbo[VERTEXBUFFER]);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo[VERTEXBUFFER]);
glBufferData(GL_ARRAY_BUFFER, sizeof(mesh->vertices), &mesh->vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0);
glEnableVertexAttribArray(0);

/*glGenBuffers(1, &mesh->vbo[TEXTUREBUFFER]);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo[TEXTUREBUFFER]);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0);
glEnableVertexAttribArray(1);
*/
glGenBuffers(1, &mesh->vbo[INDICESBUFFER]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->vbo[INDICESBUFFER]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(mesh->indices), &mesh->indices, GL_STATIC_DRAW);

/*glGenBuffers(1, &mesh->vbo[COLORBUFFER]);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo[COLORBUFFER]);
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
glVertexAttribPointer(3, 4, GL_FLOAT, false, 4 * sizeof(GLfloat), NULL);
glEnableVertexAttribArray(3);*/

/*glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);*/

return mesh;
}

Mesh *Mesh_CreateQuad()
{

GLfloat vertices[] = { -0.5,  -0.5,
                        0.5,  -0.5,
                        0.5,   0.5,
                       -0.5,   0.5 };

GLuint indices[] = { 0,1,2,
                      0,2,3 };

GLfloat uvs[] = {   0 , 1,
                    1,  1,
                    1,  0,
                    0,  0 };

GLfloat colors[] = {    1, 1, 1, 1,
                        1, 1, 1, 1,
                        1, 1, 1, 1,
                        1, 1, 1, 1 };

return Mesh_Create(vertices, indices, uvs, colors);
}

void Mesh_Render(Mesh *mesh)
{
    glBindVertexArray(mesh->vao);
    glDrawElements(GL_TRIANGLES, mesh->elementCount, GL_UNSIGNED_INT, &mesh->indices);
}

```

# Answer
> 1 votes
Your main problem is that you're unbinding:

```
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

Because your VAO is still active when you unbind, you're actually setting the bindings stored in the VAO to 0 when you do this.

**So your VAO has 0 bound to GL\_ELEMENT\_ARRAY\_BUFFER meaning that no element array buffer will be used during your glDrawElements call** \- the actual outcome of which will vary depending on whether you use a core profile (GL\_INVALID\_OPERATION will be generated) or not (you might get no output, you might get garbage output, you might get a random crash).

---

Your element array buffer setup also makes no sense:

```
    glGenBuffers(1, &mesh->vbo[INDICESBUFFER]);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->vbo[INDICESBUFFER]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices) * sizeof(GLubyte), indices, GL_STATIC_DRAW);
    glVertexAttribPointer(2, 3, GL_UNSIGNED_BYTE, false, 0, 0);
    glEnableVertexAttribArray(2);

```

There's no need to use either glVertexAttribPointer or glEnableVertexAttribArray here, and in fact vertex attrib pointer setup only latches the most recently bound GL\_ARRAY\_BUFFER, so these pointers will in fact use your mesh-\>vbo\[TEXTUREBUFFER\].

That shouldn't affect the glDrawElements call working or not, however, although - depending on your vertex shader - the output might not be what you expect.

---

Finally...

```
glDrawElements(GL_TRIANGLES, mesh->elementCount, GL_UNSIGNED_BYTE, mesh->indices);

```

Where:

```
mesh->indices = (GLubyte*)malloc(sizeof(indices));
mesh->indices = indices;

```

And:

```
GLubyte indices[] = { 0,1,2,
                      0,2,3 };

```

There are lots of things wrong with this.

First of all, "indices" is a local variable declared on the stack, meaning that it will go out of scope when Mesh\_CreateQuad exits, meaning that it will just contain stack garbage any future time you might reference that memory location.

So then you malloc mesh-\>indices, but "mesh-\>indices = indices" **doesn't copy the data**; it just copies the pointer assignment. In other words, "*the memory location pointed to mesh-\>indices is set to be the memory location pointed to by indices*". But, as we've seen, *the memory location pointed to by indices* will go out of scope and potentially contain random garbage, so mesh-\>indices **likewise contains random garbage** *after indices goes out of scope*.

This is obviously all wrong, and you really need to work a lot on your understanding of memory management and pointers in C/C++ here.

---

And one last note is that you really shouldn't use GL\_UNSIGNED\_BYTE with glDrawElements because it's unlikely to be hardware accelerated. So even though it might be appealing because it saves memory, it will actually run slower than using a larger type.

---

So, in summary:

* Set up your ELEMENT\_ARRAY\_BUFFER correctly.
* Copy memory correctly using memcpy instead of just copying pointer assignments.
* Always draw from buffer objects if using a core profile; this includes both your ARRAY\_BUFFER(s) and your ELEMENT\_ARRAY\_BUFFER.
* If you unbind your ELEMENT\_ARRAY\_BUFFER while a VAO is bound, you'll unbind it from that VAO and that VAO will be unable to draw with indices. This applies even if you do everything else correctly - **unbinding is evil** \- don't do it, even if it's what a tutorial teaches (it's a bad tutorial if it unbinds).

# Answer
> 0 votes
Something is appearing but not working entirely. Can someone help?

```
Mesh *Mesh_Create(GLfloat vertices[], unsigned int vertexElements, GLuint indices[], unsigned int indexElements, GLfloat uvs[], unsigned int uvElements, GLfloat colors[], unsigned int colorElements)
{
    Mesh *mesh = (Mesh*)malloc(sizeof(Mesh));

    mesh->vertices = (GLfloat*)malloc(sizeof(GLfloat) * vertexElements);
    memcpy(mesh->vertices, vertices, sizeof(GLfloat) * vertexElements);

    mesh->uvs = (GLfloat*)malloc(sizeof(GLfloat) * uvElements);
    memcpy(mesh->uvs, uvs, sizeof(GLfloat) * uvElements);

    mesh->indices = (GLuint*)malloc(sizeof(GLuint) * indexElements);
    memcpy(mesh->indices, indices, sizeof(GLuint) * indexElements);

    mesh->elementCount = vertexElements * 3;

    glGenVertexArrays(1, &mesh->vao);
    glBindVertexArray(mesh->vao);

    glGenBuffers(1, &mesh->vbo[VERTEXBUFFER]);
    glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo[VERTEXBUFFER]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * vertexElements, &mesh->vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, NULL);
    glEnableVertexAttribArray(0);

    glGenBuffers(1, &mesh->vbo[TEXTUREBUFFER]);
    glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo[TEXTUREBUFFER]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * uvElements, &mesh->uvs, GL_STATIC_DRAW);
    glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, NULL);
    glEnableVertexAttribArray(1);

    glGenBuffers(1, &mesh->vbo[INDICESBUFFER]);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->vbo[INDICESBUFFER]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indexElements, &mesh->indices, GL_STATIC_DRAW);

    /*glGenBuffers(1, &mesh->vbo[COLORBUFFER]);
    glBindBuffer(GL_ARRAY_BUFFER, mesh->vbo[COLORBUFFER]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * colorElements, &mesh->colors, GL_STATIC_DRAW);
    glVertexAttribPointer(2, 4, GL_FLOAT, false, 0, NULL);
    glEnableVertexAttribArray(2);*/

    return mesh;
}

Mesh *Mesh_CreateQuad()
{
    GLfloat vertices[8] = { -0.5,  -0.5,//   0,
                              0.5,  -0.5,//   0,
                              0.5,   0.5,//   0,
                             -0.5,   0.5 };//,   0 };

    GLuint indices[6] = { 0,1,2,
                          0,2,3 };

    GLfloat uvs[8] = {  0 , 1,
                        1,  1,
                        1,  0,
                        0,  0 };

    GLfloat colors[16] = {  1, 1, 1, 1,
                            1, 1, 1, 1,
                            1, 1, 1, 1,
                            1, 1, 1, 1 };

    return Mesh_Create(vertices, 8, indices, 6, uvs, 8, colors, 16);
}

void Mesh_Render(Mesh *mesh)
{
    glBindVertexArray(mesh->vao);
    glDrawElements(GL_TRIANGLES, mesh->elementCount, GL_UNSIGNED_INT, NULL);
}

```

---
Tags: opengl
---


# Question
Title: How does SDL2 renderer work? Does it make sense to render to only part of a window?
In order to run a game without using the CPU/GPU too much, I want to only update the section of the window that has changed.

Does this goal even make sense? How does the texture objects/renderer work when updating the screen? My idea is that the renderer builds a matrix of ints (pixel colours) and when `SDL_RenderPresent` is called, this edits a matrix stored on the memory that controls the colours for each pixel on the screen.

If what I've said so far makes sense, then is my implementation below correct (not updating more of the screen than needed)? I've tried to keep my code very, very simple so that it's easy to read.

The programme jumps the character (picture of a prince) from the top-left of the window to the bottom-left, and visa-versa, whenever the user inputs anything. This is just to keep the code simple for the example.

```
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

using namespace std;

int main ()
{
    // Screen dimension constants
    const int WINDOW_WIDTH = 639;
    const int WINDOW_HEIGHT = 1015;

    const int PRINCE_WIDTH = 74;
    const int PRINCE_HEIGHT = 114;

    SDL_Init ( SDL_INIT_EVERYTHING );

    SDL_Window * window =
    SDL_CreateWindow ( "example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN );

    SDL_Renderer * renderer = SDL_CreateRenderer ( window, -1, SDL_RENDERER_ACCELERATED );

    SDL_Texture * background = IMG_LoadTexture ( renderer, "./images/background.bmp" );
    SDL_Rect rect_background = { 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT };
    SDL_RenderCopy ( renderer, background, & rect_background, & rect_background );

    const SDL_Rect rect_place_one = { 400, 600, PRINCE_WIDTH, PRINCE_HEIGHT };
    const SDL_Rect rect_place_two = { 40, 60, PRINCE_WIDTH, PRINCE_HEIGHT };

    SDL_Texture * prince = IMG_LoadTexture ( renderer, "./images/prince.bmp" );
    SDL_RenderCopy ( renderer, prince, NULL, & rect_place_one );
    SDL_RenderPresent ( renderer );

    SDL_Event input;

    for ( uint8_t count = 0; SDL_WaitEvent( & input ); ++count )
    {
        // User requests quit
        if ( input.type == SDL_QUIT )
            break;

        if ( input.type != SDL_KEYDOWN )
            continue;

        if ( ( count % 2 ) )
        {
            SDL_RenderCopy ( renderer, prince, NULL, & rect_place_one );
            SDL_RenderCopy ( renderer, background, & rect_place_two, & rect_place_two );
        }
        else
        {
            SDL_RenderCopy ( renderer, prince, NULL, & rect_place_two );
            SDL_RenderCopy ( renderer, background, & rect_place_one, & rect_place_one );
        }

        SDL_RenderPresent ( renderer );
    }

    SDL_DestroyTexture ( prince );
    SDL_DestroyTexture ( background );
    SDL_RenderClear (renderer);
    SDL_DestroyWindow ( window );
    SDL_Quit ();

    return 0;
 }

```

# Answer
Your idea is essentially software rendering, where you manually update pixels in a grid and then update those pixels to the screen. Only updating the necessary pixels in that case makes a lot of sense, since copying pure image data like that can be really slow.

I would heavily recommend against this approach. GPUs are really fast nowadays, and SDL2's renderer can take full advantage of the hardware acceleration that is provided by the graphics processor. Redrawing the screen each frame will be no issue at all, and your rendering pipeline will stay a lot simpler if you don't have to track down the screen areas that have changed, removing the possibility of odd ghosting bugs appearing.

SDL2's renderer is essentially a wrapper around OpenGL, DirectX or Metal. There is also a software renderer implementation, when none of the hardware accelerated graphics APIs aren't available for use, but for common platforms, there will always be a valid accelerated renderer that SDL can instantiate for you.

Your implementation looks relatively okay, however a more common approach is to place the event loop inside a separate gameloop. Currently you stop updating if there are no events to process.

```
while (runGame) {
    SDL_Event e;
    while (SDL_PollEvent(&e)) {
        // Process events.
    }

    updateGame();
    SDL_RenderClear(renderer);
    renderGame();
    SDL_RenderPresent(renderer);
}

```

Here is a very basic outline of a common game loop. There are bits missing, like timing, but getting into that stuff is out of scope for this answer.
> 3 votes

---
Tags: sdl2
---


# Question
Title: How can I make a two-eye-view effect using two cameras?
I have two cameras. The second was made by duplicating the first. Then I changed both cameras' viewport rects:

* First Camera `X = 0 Y = 0.25 W = 0.5 H = 0.5`
* Second Camera `X = 0.5 Y = 0.25 W = 0.5 H = 0.5`

Then I created two Post Process profiles for each camera, CC and CC1 in the Inspector.

The result:

But it seems to me a bit odd. Since the view through both eyes looks the same.

Shouldn't the right eye be rotated or something, so it's completing the view from the right side? That is, I don't want both cameras (eyes) see the same (right-hand) view.

# Answer
You see, Cameras in Unity are designed to behave like a human eye:

As you can see from the image above, notional cameras have what's called a *View Frustum*; To put it simply, it simulates what the human eye would see in real life between a *near* and *far* plane (you can always read more here).

Now let's see how I would solve this:

First of all create a Canvas:

* Go to the hierarchy window, Create -\> UI -\> Canvas and set `UI Scale Mode` to `Scale With Screen Size`;
* Create an Image object as a child of the newly created Canvas by going (right-click on Canvas) UI -\> Image;
* Stretch the image to cover the size of the canvas ( remember to hold down `alt` in order to do so) :

Now that you have done that, you could have a "mask" image like these ones for instance (yes, they are both 4k res and you can use them however you want :D):

Remember that when making a mask, the white portion of the image should have an alpha of 0.

* Now that we also have a mask, we can just apply that to the Image we created (when importing the image, remember to set `Texture Type` to `Sprite (2D and UI)`:

And that's it! To improve even more the effect, you could try making the "lenses" with a gradient, adding multiple layers of textures with different drawing orders to create dirt, or waterdrops, animate the mask to act as an helmet that is being put on / took off ecc..

You can really go crazy with post processing effects too; have fun! :D
> 2 votes

---
Tags: unity, camera
---


# Question
Title: Problem with rotation a camera with the mouse OPENGL GLFW
I am trying to move my camera with my mouse, I can translate it juste by changing the current position of my camera, but when I want to move my forward vector and my up vector of my camera it doesnt work very well, the camera seem to move whereas it's not the case...

```
void Camera::moveCameraRotateUpdtade(GLFWwindow * window)
{

 //curseur mvt ...
  double xpos, ypos;
  Vec3f new_front;
  std::cout << "front = " << CameraFront << std::endl;

  glfwGetCursorPos(window, &xpos, &ypos);
  if(!(xpos > _width-1 || xpos < 0) && !(ypos > _height-1 || ypos < 0))
  {
    float x = (2.0f * xpos) / _width - 1.0f;
    float y = 1.0f - (2.0f * ypos) / _height;

horizontalAngle += mouseSpeed  * float(x) ;
verticalAngle   -= mouseSpeed  * float(y) ;

std::cout << "x y = " << x << " " << y << std::endl;
std::cout << "horizontalAngle verticalAngle = " << horizontalAngle << " " << verticalAngle << std::endl;

new_front = Vec3f(cos(verticalAngle) * sin(horizontalAngle),sin(verticalAngle),cos(verticalAngle) * cos(horizontalAngle));
Vec3f right = Vec3f(sin(horizontalAngle - M_PI/2.0f),0.0,cos(horizontalAngle - M_PI/2.0f));
CameraUp = right.cross(new_front);
CameraUp = CameraUp.normalize();
CameraFront = new_front.normalize();

std::cout << "CameraFront = " << CameraFront;
std::cout << "CameraUp = " << CameraUp;
std::cout << "position = " << _positionCam;

LookAt( _positionCam + CameraFront,_positionCam, CameraUp);
}

}

```

Here my lookAt function :

```
Mat4f Camera::LookAt(Vec3f target, Vec3f position,Vec3f CameraUp)
{
  //ce dont j'ai besoin pour calculer les parametre de ma camera...
  Vec3f f = (target - position).normalize();
  Vec3f u = CameraUp.normalize();
  Vec3f s = f.cross(u).normalize();
  u = s.cross(f);

  Mat4f R;
  R.setCol(0,s);
  R.setCol(1,u);
  Vec3f f_tmp = f*-1.0 ;
  R.setCol(2,f_tmp);
  R.setElement(0,3,-1.0f * s.dot(position));
  R.setElement(1,3,-1.0f * u.dot(position));
  R.setElement(2,3,f.dot(position));
  _LookAt = R.transpose();

  return  _LookAt;

}

```

Here a video showing my problem :

https://www.youtube.com/watch?v=Am\_1sfMQllQ

# Answer
> 2 votes
I fix my bug,it was in the implementation of my lookAt function :

```
Mat4f Camera::LookAt(Vec3f target, Vec3f position,Vec3f CameraUp)
{
  //ce dont j'ai besoin pour calculer les parametre de ma camera...
  Vec3f f = (target - position).normalize();
  Vec3f u = CameraUp.normalize();
  Vec3f s = f.cross(u).normalize();
  //u = s.cross(f);

  Mat4f R;
  R.setCol(0,s);
  R.setCol(1,u);
  Vec3f f_tmp = f*-1.0 ;
  R.setCol(2,f_tmp);
  Mat4f T;
  position = position *-1.0f;
  T.setCol(3,position);
  R = R * T;

  /*
  R.setElement(0,3,-1.0f * s.dot(position));
  R.setElement(1,3,-1.0f * u.dot(position));
  R.setElement(2,3,f.dot(position));*/
  _LookAt = R.transpose();

  return  _LookAt;

}

```

---
Tags: opengl, c++, camera, glfw
---


title: Trying to translate object

text:
# Question
Title: Trying to translate object
I'm trying to tranlate a matrix by xy but the result is strange. can someone help me translate and rotate the matrix properly?

```
void Transform_Update(Transform *transform, GLfloat depth)
{
    Matrix4_SetToIdentity(transform->transformationMatrix);
    Matrix4_Set(transform->transformationMatrix, 0, 3, transform->position->x);
    Matrix4_Set(transform->transformationMatrix, 1, 3, transform->position->y);
    Matrix4_Set(transform->transformationMatrix, 2, 3, depth);
}

```

Here is my Matrix set value.

```
void Matrix4_Set(Matrix4 *m, GLuint line, GLuint column, GLfloat value)
{
    m->data[line * 4 + column] = value;
}

```

Here is where I make the matrix to the identity matrix

```
void Matrix4_SetToIdentity(Matrix4 *m)
{
    GLfloat data[16] = { 1, 0, 0, 0,
                         0, 1, 0, 0,
                         0, 0, 1, 0,
                         0, 0, 0, 1 };

    memcpy(m->data, data, sizeof(GLfloat) * 16 );
}

```

This is where I render my mesh and update shader values

```
void Renderer_Render(Renderer *renderer, Camera *camera)
{
    glUseProgram(renderer->shader->id);

    Transform_Update(renderer->gameObject->transform, renderer->depth);

    GLint location = Shader_GetUniformLocation(renderer->shader, "transformationMatrix");
    glProgramUniformMatrix4fv(renderer->shader->id, location, 1, GL_FALSE, renderer->gameObject->transform->transformationMatrix->data);

    GLint location2 = Shader_GetUniformLocation(renderer->shader, "projectionMatrix");
    glProgramUniformMatrix4fv(renderer->shader->id, location2, 1, GL_FALSE, camera->projectionMatrix);

    GLint location3 = Shader_GetUniformLocation(renderer->shader, "viewMatrix");
    glProgramUniformMatrix4fv(renderer->shader->id, location3, 1, GL_FALSE, camera->viewMatrix);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, renderer->texture->id);

    Mesh_Render(renderer->mesh);
}

```

Here is my shader transforming the vertices :

```
#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void) {

    vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
    vec4 positionRelativeToCamera = viewMatrix * worldPosition;

    gl_Position = projectionMatrix * positionRelativeToCamera;
    pass_textureCoords = textureCoords;
}

```

Here is how I get the view and projection matrix :

```
void Camera_Render(Screen *screen, Camera *camera)
{
    glClearColor(camera->backgroundColor->red, camera->backgroundColor->green, camera->backgroundColor->blue, camera->backgroundColor->alpha);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glTranslatef(camera->transform->position->x, camera->transform->position->y, 0);
    glRotatef(camera->transform->angle, 0, 0, 1);

    glGetFloatv(GL_PROJECTION_MATRIX, camera->projectionMatrix);
    glGetFloatv(GL_MODELVIEW_MATRIX, camera->viewMatrix);
}

```

The current output when I change X is this :

# Answer
It looks like your matrices are row-major, whereas OpenGL expects column-major matrices. In your calls to `glProgramUniformMatrix4fv()`, you should set the transpose parameter to `GL_TRUE`, like this:

```
glProgramUniformMatrix4fv(renderer->shader->id, location, 1, GL_TRUE, renderer->gameObject->transform->transformationMatrix->data);

```
> 1 votes

---
Tags: opengl, c
---


# Question
Title: Need advice concerning the creation of open world game in Unity 3D
I just wanted to ask for advice those being an expert in Unity 3d and overall in game industry about how it is possible to create an open-world game by means of Unity 3D, that is, I already tried to combine several tiles of terrains, 4 to be exact, and their respective size is 500x500. However, once I started to add the fifth terrain to those terrains, Unity stopped working. Moreover, another problem that I faced was with light mapping in Unity, that is, the more terrain I add to the scene the more it is difficult to bake the light mapping. The question is if I am doing correctly by adding terrains to each other and how open-world games are actually created. Yes, I heard of chunk loading but is it possible to code it on my own without using ready plugins. Lastly, Is it possible to combine tiles of terrains just manually without using any tools like Terrain Slicing kit or Gaia please I really need your help Thank you for your attention))).

# Answer
Unity makes these things a bit difficult. First things first, unity was mainly built on an architecture for indie and mobile games which might explain why this is difficult to accomplish. Unity is breaking out of that indie and mobile space but lacks some tech that makes things like this easy for developers.

As a professional who has used unity for almost 10 years and has somehow been always working on games that push the engine to it’s limits, I can honestly say this is more of a technical challenge than you might have signed up for.

You asked for out of the box or simple code solutions so the best I can provide for you is the built in ability for unity to load multiple levels at one time. If you imagine your world as a grid and just make several scenes that represent each square then you can just load levels (using the LoadLevelAsync function to not block the main thread) and unload levels as you move closer or farther to different squares.

Unfortunately, unity’s current component system of using Start/Awake/OnEnable in scripts causes a massive issue when loading levels. Once you tell unity to load a level it has to load everything in that scene and then all at once BAM! You have every single component in there starting up and allocating memory or spending CPU cycles, which usually results in hitching.

Also if you are wanting a breath of the wild type thing (where you can see very very far away) you will likely want to have the ability to slow down or stop update cycles on components that are very distant. Usually you want the highest poly and most CPU expensive things happening only where they matter... where they are close to or visible by the player. This is also not available by default in unity.

This is an issue I am personally setting out to solve on my own and hopefully offer up as a unity asset for others. I just thought I would share my own experiences and findings with you.

Basically level streaming is the solution here and there isn’t much out of the box that can help you get there.
> 2 votes

# Answer
A terrain will have a large area and large memory usage to go along with it and an open world will needs lots of these and, as you've already discovered, this is not an option.

Unless you can find a way to put in multiple, small terrains and only render those within certain areas, you're going to keep coming up against the same problem.

You should investigate voxel level design. This is what is used by titles such as Minecraft, 7 Days to Die and Space Engineers.
> 0 votes

# Answer
Method 1- Instead of terrain, use well cleverly designed 5, 10, 30, 20000 etc small meshes as terrain, and put imaginary boxes around each mesh, when mesh is out of Cam sight the just don't render them. Hence well cleverly designed meshes that just don't pop up in cam view will not get drawn. If possible learn coding functionality how not to render out of Cam view meshes.

Method 2- learn how to draw scene on the fly by creating chunks/lots of mesh quads that will be Cam view. that us the best way to produce maximum FPS scenes, as only fraction of a mesh is drawn that is only in Cam view.

Method 3- Use the most awesome method- mixing 2D + 3D within the scene, just it is done in Manga Japanese movies, ie the scene in background is 2D, and the mesh items on top of that are either 3D or 2D- as low as 7FPS.
> 0 votes

---
Tags: unity, 3d
---


# Question
Title: How do I implement efficient collision avoidance in 100 enemies
I am developing a libgdx game. It is a top down shooter and I am trying to make a good AI. I have tried to implement A\* from the AI library from libgdx and it works fine but when i have a lot of enemies it starts to slow down the game. Have tried implementing a Pathfinding manager to manage threads and path requests but I have trouble implementing it and still slows down.

Also I know A\* is a bit overkill for my game, which is a big open zone mostly (see pic of my map)

So I tried to implement this collision avoidance Steering Behaviors: Collision Avoidance but it doesn't go well when the player is inside houses.

My question is, does exists some type of algorithm that fits perfectly for what I am asking? There are a lot of games with hundreds of enemies going to kill you so I bet there is a way, just I cant find out

pd: Any doubt ask and I will provide more information if necessary

# Answer
> 1 votes
Followed @DMGregory advice and I implemented flow field algorithm.

I made a graph and store in each node its neighboors, its distance and its direction vector. So zombies can ask its node what direction may he go.

# Answer
> 2 votes
Instead of path finding from every enemy to the player pathfind from the player to every enemy and make every enemy follow the `from` pointer. You cannot use A\* for this until you have reached most of them.

You don't need to repath every enemy every frame. Instead you have a rotating set of enemies getting repathed to the player. Because the player isn't going to move a big distance far lot this is fine. If you ever implement teleports you can use the delay of the animation of the teleport to repath every enemy to the destination of the teleport.

Decrease the density of the nav graph. in wide open spaces reduce the number of nav nodes and use a path smoothing algorithm.

---
Tags: libgdx, collision-detection, box2d, ai
---


# Question
Title: Draw line between tiles of tiled map in libgdx
I want to draw line between two tile of my .tmx map in libgdx . I want to get a tile position but not in pixels , in maps grid numbers like : (0 , 6 ). or is there any way to change a tile color in libgdx. i can get tile like below:

```
layer=(TiledMapTileLayer)tiledMap.getLayers().get(0);
layer.getCell(row, col).getTile()

```

but can not to draw some thing on the tile.

# Answer
You can use a `ShapeRenderer` to draw a line from one cell to another. If you set the `Camera` used by the `ShapeRenderer` then the coordinates will be tile coordinates (plus an adjustment of (0.5, 0.5) to get the center of the tile.

```
    shapeRenderer.setProjectionMatrix(camera.combined);
    shapeRenderer.begin(ShapeType.Line);
    shapeRenderer.setColor(Color.RED);
    Vector2 v0 = new Vector2(2, 4);
    Vector2 v1 = new Vector2(10, 8);
    shapeRenderer.line(
            v0.add(0.5f,  0.5f), // Add .5 to each coordinate to get the center of the tile
            v1.add(0.5f,  0.5f));
    shapeRenderer.end();

```

To change the image of a `TileMapTile` an easy way is to replace the tile with another tile in the existing `TileSet`.

```
TiledMapTileLayer layer =  (TiledMapTileLayer)map.getLayers().get(0);
Cell cell = layer.getCell(1, 3);
TiledMapTile newTile = map.getTileSets().getTileSet(tilesetName).getTile(32);
cell.setTile(newTile);

```

This get the (relevant) `MapLayer` as a `TiledMapTileLayer` and get a `Cell` from that, then by getting a `TiledMapTile using the`getTileSets`and`getTile`methods on`TiledMap\` a new tile can be set.

Complete **libGDX** example code (code assumes a map called *test\_map.tmx* with a tileset called *terrain* in the `assets` folder).

```
    package com.bornander.sandbox;

    import com.badlogic.gdx.ApplicationAdapter;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.Input.Keys;
    import com.badlogic.gdx.assets.AssetManager;
    import com.badlogic.gdx.graphics.Color;
    import com.badlogic.gdx.graphics.GL20;
    import com.badlogic.gdx.graphics.OrthographicCamera;
    import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
    import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
    import com.badlogic.gdx.maps.tiled.TiledMap;
    import com.badlogic.gdx.maps.tiled.TiledMapTile;
    import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
    import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
    import com.badlogic.gdx.maps.tiled.TmxMapLoader;
    import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
    import com.badlogic.gdx.math.Vector2;

    public class SandboxGdxGame extends ApplicationAdapter {
        private AssetManager assetManager;
        private OrthographicCamera camera;
        private OrthogonalTiledMapRenderer mapRenderer;
        private TiledMap map;

        private ShapeRenderer shapeRenderer;

        @Override
        public void create () {
            String mapFile = "test_map.tmx";
            assetManager = new AssetManager();
            assetManager.setLoader(TiledMap.class, new TmxMapLoader());

             assetManager.load(mapFile, TiledMap.class);
             assetManager.finishLoading();
             map = (TiledMap)assetManager.get(mapFile);

            float viewportWidth = 32.0f; // Number of horizontal tiles to show
            float aspectRatio = (float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight();
            camera = new OrthographicCamera(viewportWidth, viewportWidth / aspectRatio);
            camera.update();
            camera.position.set(camera.viewportWidth / 2.0f, camera.viewportHeight / 2.0f, 1.0f);

            float tileSizeInPixels = 32.0f;
            mapRenderer = new OrthogonalTiledMapRenderer(map, 1.0f / tileSizeInPixels);

            shapeRenderer = new ShapeRenderer();
        }

        @Override
        public void render () {
            Gdx.gl.glClearColor(1, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            // When space is pressed, rewrite tile at (1,3) to be tile 32 from tileset 'tilesetName'
            if (Gdx.input.isKeyJustPressed(Keys.SPACE) ) {
                String tilesetName = "terrain";
                TiledMapTileLayer layer =  (TiledMapTileLayer)map.getLayers().get(0);
                Cell cell = layer.getCell(1, 3);
                 TiledMapTile newTile = map.getTileSets().getTileSet(tilesetName).getTile(32);
                 cell.setTile(newTile);
            }

            // Render map
            camera.update();
            mapRenderer.setView(camera);
            mapRenderer.render();

            // Render line between center of tile (2,4) to center of tile (10, 8)
            shapeRenderer.setProjectionMatrix(camera.combined);
            shapeRenderer.begin(ShapeType.Line);
            shapeRenderer.setColor(Color.RED);
            Vector2 v0 = new Vector2(2, 4);
            Vector2 v1 = new Vector2(10, 8);
            shapeRenderer.line(
                    v0.add(0.5f,  0.5f), // Add .5 to each coordinate to get the center of the tile
                    v1.add(0.5f,  0.5f));
            shapeRenderer.end();
        }
    }

```
> 0 votes

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


title: Time loop/ticking architecture

text:
# Question
Title: Time loop/ticking architecture
Say I build a snooker game, where balls need to jitter around.

Balls belong to a class (ball class), where all the ball functions are defined.

In the animation, time evolves by a clock ticking within a time loop.

I wonder if the clock function/time loop should be optimally defined in the main program or the class file?

If defined in the class, the advantage is that all functions regarding ball movements, collisions etc, which take time to happen, can be put in the class, without worrying about the time loop; the disadvantage is that time will tick for every ball separately, which obviously looks bad.

# Answer
Under the single responsibility principle, the Ball class should be responsible for ball behaviour, not timekeeping.

You'll have other code in your game that cares about time. (eg. UI animations) Under the DRY principle, you should not repeat the basic time-tracking functionality in multiple places.

A typical approach is to manage your time step in your main game loop and either pass the time delta to your game entities' update methods via a `dT` argument, or publish it via a globally-accessible access point like Unity's static Time class
> 0 votes

---
Tags: software-engineering, game-loop, timestep
---


title: Terminology in a hierarchy of levels

text:
# Question
Title: Terminology in a hierarchy of levels
My game has a 2-tier hierarchy of levels, it is composed of 6 or more "outer levels" that consist of 8 or more "inner levels". Reaching an inner level unlocks the next inner level. Reaching the top inner level of an outer level unlocks the next outer level. The first inner levels of an outer level resemble the inner levels of the previous outer level, but each outer level has more inner levels than its predecessor.

What terms are common to refer to "outer levels" and "inner levels" in such a situation? The game is very abstract, so something like "world" for the outer level would be inappropriate.

# Answer
Some options for an "outer" level:

* Group
* Set
* Stage
* Phase
* Tier (also suggests escalating value/difficulty)
* Folder (like a file system)
* Book

Some options for an "inner" level:

* Puzzle
* Entry
* Challenge
* Node

So a player could say "I'm on the second puzzle of group three" or "Those tier-5 challenges are really hard!"
> 1 votes

# Answer
"Levels" and "sub-levels" are the first thing that come to mind.

The actual terminology you use, "outer" and "inner," also seems viable if a little technical. Other options might be "overworld" and "world," or "major" and "minor" levels. Older games sometimes used "world" and "stage" (or the reverse, in a few cases if I remember correctly).

Ultimately you can probably call them whatever you want, there isn't a lot of standardization. It's possible (as noted in the comments) that more thematic or contextual options might exist if you provided more information about the setting of your game.
> 1 votes

---
Tags: terminology, levels
---


title: Detecting collisions during animations

text:
# Question
Title: Detecting collisions during animations
I am creating a prototype enemy swordsman, and I'd like to be able to parry his attacks, like the parry system from VR Dungeon Knight.

This is my method of implementation:

1. Parent a sword to his hand that has a child cube trigger collider + kinematic rigidbody + a custom script called ParryableWeapon.
2. In the animation clip, when he raises his hand before his swing, use an AnimationEvent to tell the ParryableWeapon to start 'listening' for a parry. This is done by checking an internal boolean during OnTriggerEnter of the sword.
3. If the ParryableWeapon collides with another ParryableWeapon while listening, the UnityEvent 'OnParried' is invoked.
4. After the swing completes, use another AnimationEvent to tell ParryableWeapon to stop 'listening'.

I have a simple model and animation from the Asset store that I'm using to accomplish this. For some reason, the OnParried event is only being fired every 5 or so swings at a stationary test sword.

I played the animation frame by frame, and I found that the enemy swords' position sometimes does not go through the other sword, despite them being on a collision course. In one frame, the enemy sword is to the left of the other, and in the next frame, it is on the other side.

It seems that the interpolated frames between the animation keyframes can only sometimes collide with the other sword. What would be the proper way to remedy this? Adding more keyframes to the animation? Some sort of calculation of the sword's path between the two keyframes?

# Answer
> 1 votes
My issue was that I expected OnTriggerEnter() to perform the same continuous collision detection that OnColliderEnter() would. That is apparently not the case. Instead of the collision detection implementation I described, I did a CapsuleCast during the parryable weapon frames, setting the ends of the capsule at the sword's tip and guard and against a custom collision layer.

---
Tags: unity, physics, animation, combat
---


# Question
Title: Roguelike game: detect intent of other actors by observing their moves
In grid turn-based roguelike game, how can I detect the following scenarios:

* other actor is following observing actor
* other actor is intentionally moving to block its path

Path blocking can happen if for example player intentionally stops right in front of actor and then when actor moves to avoid player, player moves in front and that keeps repeating as long as player does it. I managed to detect that situation in hackish way and I would like to know if there is a better method for solving things like this.

# Answer
> 1 votes
I'd recommend thinking of this as hypothesis testing. Form a hypothesis about the agent's goal, then check whether observations are consistent with that hypothesis.

For example, if we hypothesize that a character is trying to block our movement, then the next time we plan a route around them we suppose that within a given time horizon they'll try to move into our planned path. If they do, that's a point for this hypothesis. If they don't, that's a strike against it.

If we hypothesize that a character is following us, then we can model a pursuit behaviour (either a naive follow or an intercept course) and score how closely the character's subsequent moves follow this predicted behaviour.

After several iterations, the hypothesis may reach a sufficient threshold of confidence that we accept as fact, and change our behaviour accordingly.

We can reduce false positives by also scoring alternative hypotheses: maybe the character isn't following me, but pathing toward some attractive feature near me, for example.

If you want to get really crafty, this lets us conduct an experiment: deliberately change our movement to deviate from the path toward that attractive feature: does the character continue pathing toward the feature, or do they change course along a pursuit path to our new trajectory? This gives strong evidence to break a tie between the chasing and null hypotheses. ;)

---
Tags: ai, turn-based, roguelikes
---


# Question
Title: LibGDX Textfield has no pointer cursor or blinking on hover / focus
```
    stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
    Gdx.input.setInputProcessor(stage);
    TextField.TextFieldStyle style = new TextField.TextFieldStyle();
    style.font = font;
    style.fontColor = Color.BLACK;
    style.cursor =
    style.selection = new Image(new Texture("core/assets/skin/textfield-big.png")).getDrawable();
    style.background = new Image(new Texture("core/assets/skin/textfield-big.png")).getDrawable();
    text = new TextField("Name", style);
    text.setWidth(500);
    text.setHeight(37);
    text.setPosition(50, 50);
    stage.addActor(text);

```

When I draw my stage, I can see my `textfield`, but when I hover it, my cursor doesn't change, and when I focus I can't see that blinking " | " at all, like normal textfields have.

What did I do wrong? Is it because `style.cursor` is null? If yes, how can I set it to the default cursor that libgdx uses?

# Answer
This is an old issue, but for future scrollers: A lot of people suggest that you load up a seperate drawable, but to me that feels like overkill for the one character. Instead, what I do (as of today) is use a Pixmap to get a black rectangle the size of the '|' character, then feed that in as the drawable for the cursor image.

Similar logic also works for the selection variable, which you may be interested in changing as well.

```
Label oneCharSizeCalibrationThrowAway = new Label("|", yourLabelStyle);
Pixmap cursorColor = new Pixmap((int) oneCharSizeCalibrationThrowAway.getWidth(),
            (int) largeSizeCalibrationThrowAway.getHeight(),
            Pixmap.Format.RGB888);
cursorColor.setColor(Color.BLACK);
cursorColor.fill();

yourTextFieldStyle.cursor = new Image(new Texture(cursorColor)).getDrawable();

```
> 2 votes

---
Tags: java, libgdx
---


# Question
Title: How do online games deal with lerp overshooting?
From what I understand, when you lerp in an online game, you travel from point a to b based on the elapsed time since the last update. The problem is when you have a higher latency, and you start receiving updates at inconsistent rates. So lets say I have variable `t`, variable t tracks the time since the last update and is only reset when a new update is received. The variable `t` is also responsible for moving the lerp like so:

```
lerp(a, b, t)

```

But when we receive updates at an inconsistent rate, `t` is reset inconsistently, so if there is any lag between the updates, `t` will keep incrementing, thus, the lerp will overshoot. How do online games deal with this?

# Answer
> 1 votes
Often, we'll just accept some overshoot, and blend it out as needed when we eventually get the next update packet some milliseconds later.

A lot of things in games move in reasonably straight lines or or broad arcs on the timescale of update packets, so assuming the object keeps going the direction it was last known to be travelling in is often a very accurate first guess.

If you have some domain-specific knowledge, of course, you can propose better predictions. Say you're dealing with an object on a tether, or a vehicle with its wheels turned to steer around a corner - you might decide to predict its motion in an arc instead of a straight line.

If prediction is absolutely off the table, then you could clamp your lerp parameter at 1 so the object will stop and wait for the next update before proceeding, but that can cause it to visible hesitate & stutter in its motion.

To avoid this without predicting, you can instead choose to let it live further in the past. Say, instead of living one average packet interval behind the server, you let it stay up to 2, or even 3 updates back. This gives you a much longer buffer to absorb a late or missing packet before you run out of movement history to replay.

In Watch\_Dogs 2's multiplayer, they allow this "time in the past" parameter to vary as a function of the player's average measured lag as well as vehicle speed and collision probability, so they keep the movement looking as smooth and accurate as possible with interpolated history most of the time, and zero-in toward the current moment in cases where a collision is likely so that the two sides observe roughly the same collision event.

---
Tags: movement, lag, lerp
---


# Question
Title: Find Entity Orientation In Degrees Given Two Coordinates
I'm trying to find the orientation for an entity, as an angle in \[0º-360º). I've searched for an answer and tried to implement something of my own, but it always fails on the edge cases. For a better understanding of what I am trying to achieve I've created the following image.

EDIT: It is worth mentioning that I do the conversions to and from radians where needed. Additionally, this is used for an internal simulation (meaning this will not be rendered on screen).

**What is known**: the center point coordinates which is always at (0,0) and the position of the red entity (x,y)

**What needs to be computed**: the orientation of the red entity such as it faces the center point (0, 0) in degrees 0-359

In my particular case I have to support negative coordinates. The degrees start at 0 which is at the top and goes CW.

**What I tried**

I've tried using **atan2(y, x)** which I almost got working, but it fails at some edge cases as I will describe.

When the entity is in the first quadrant I get, let's say 45 degrees, but this is not good in my case, because if the entity is in the first quadrant and it's facing the center the angle should be between 270 and 180. So I did some mapping and it seems to be working.

When the entity is in the second quadrant I get, let's say -45 degrees, which again is not good because I need it to be in range of 0-359. So I check if the degree is less than 0, add 360 and mod by 360. The result I get is good since it's between 270 and 359.

I could go on about the rest of the quadrants, but then I get another issue: when the x or y coordinates for the entity are 0 (only one, not both).

I could write some if cases to adapt the result accordingly, but I figured there must be a smarter solution to this and a faster one, since this needs to be computed 60 times a second.

I've also tried some custom math, using triangles, but ultimately I have to manually do some checks to get the correct answer.

I don't know if this is of any value for the answer, but I'm trying to implement this in Java/Kotlin, though I'm **not** looking for someone to just give me the magic piece of code that I can just paste and have it working, I'm looking to understand how it can be done better.

Is there a better way to achieve the result I want here?

---

**The solution that worked perfectly for me is the following**

```
angle = -(toDegrees(atan2(y, x)) + 90) % 360

```

As far as I can see it covers the edge cases.

# Answer
> 1 votes
We have - at least - three issues to consider:

1. `atan2(x, y)` gives you the angle from the origin to the given point (the position of the red entity on this case). What you want is the opposite direction.
2. However, the angle is from the positive x axis (0 = on the positive x axis), but given your picture you are measuring from the y axis (0 = on the positive y axis).
3. Futhermore, the angle given by `atan2(x, y)` is given as a positive rotation, and that means counterclockwise. Yet, your picture indicates you want clockwise angle.

Let us be clear, measuring from the x axis, counterclockwise, is the convention.

---

I said at least three issues because there is another one to consider. You depict the positive y axis on the top. That is what we do in math, however... well, for screens the y axis increases downwards because of historical reasons. In fact, the origin is in the top left corner.

I do not know if you want to take this into account, of you already are doing it (or whatever software you are using takes care of it for you).

---

So, what transformation on the orientation will take it from the `atan2` representation to the one you want...

Add a quarter turn (it is plus half turn to fix issue 1, and minus a quarter turn to fix issue 3), and change the sign of the resulting angle (to fix issue 2). Of course mod by a whole turn.

```
angle = -(atan2(x, y) + quater_turn) mod whole_turn

```

If you also need to take the position from another point:

```
angle = -(atan2(x - x_origin, y - y_origin) + quater_turn) mod whole_turn

```

If you also need to flip the vertical axis because of screen coordinates:

```
angle = -(atan2(x - x_origin, y_origin - y) + quater_turn) mod whole_turn

```

Oh, and add a whole turn if it is negative

```
if (angle < 0) angle += whole_turn

```

**Note**: Libaries often work in radians, however you use degrees. I speak in turns to keep it agnostic. Do your angle conversions as needed.

---

As Quentin points out we can do this by just flipping the parameters of atan2.

```
angle = atan2(y, x)

```

If it isn't clear that is the same, consider that we needed to do a counterclockwise quarter rotation, and change the sign. We do the rotation by doing this `atan(-y, x)` (if you wish, you can confirm by trigonometry), and then change the sign. We should not need to mod by a whole turn here. However, we still need to add a whole turn if the result is negative.

---

`<rant>` It bothers me that you say 0-359. I know you mean degrees because you mention it later, I will ignore that you do not specify it here... however 359.5º is a valid angle isn't it? And it is not in the range 0º-359º. I think you mean \[0º-360º). Well, if you don't, I hope that means that you take the integer part of the angle once you have it degrees. `</rant>`

# Answer
> 0 votes
Let's say (xi,yi) are the normalized coordinates of the red entity (length = 1), then:

to compute the angle:

if xi \> 0 then angle = acos( yi ); // acos in degrees

if xi \< 0 then angle = 360 - acos( yi ); acos in degrees

# Answer
> 0 votes
A formula for a clockwise angle from 0 to 360 degrees:

```
f(x,y)=180-90*(1+sign(y))* (1-sign(x^2))-45*(2+sign(y))*sign(x)

      -180/pi()*sign(x*y)*atan((abs(y)-abs(x))/(abs(y)+abs(x)))

```

---
Tags: mathematics
---


# Question
Title: How can we achieve Earthquake Simulation in Unity - Simulation of P and S Waves
> I Cannot use Water waves as P and S Waves are different than water waves. I tried to use it but not satisfied with the result.

I am trying to simulate how Earthquake takes place in real time which you cannot simulate in the real world. Here is the reference link to understand the basics of Earthquake and to understand better here is the better-simulated Example. I wanted to Simulate P and S Waves. My first attempt will be simulating with mesh instead of showing lines, I don't know how to compress mesh (P Waves) but I found out a good example to simulate wave like effect (S Waves).

The solution I am looking forward to is :

1. Any idea of how I can compress - decompress mesh in Unity (P Waves).
2. wave like effect (S waves), I have an example but it moves only Plane, in my case, i want to do more like a deformation of mesh, so it gives me an real effect like S Waves.

# Answer
> 3 votes
In order to do this you will have to write some code to modify the mesh programmatically. This is how you read the vertices of a mesh from a C# script:

```
Mesh mesh = GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;

```

And this is how you write them back:

```
mesh.vertices = vertices;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
mesh.RecalculateTangents();

```

(Note that depending on the shader your mesh is using, recalculating the normals and/or tangents might not actually be needed. If you comment it out and the light on the mesh still looks correct, you can leave it out).

Now about the complicated part: Calculating the deformation of your mesh. I think the best way to do this would be to create a copy of the original vertex array in the Start method. Your Update method should now take that original array and run each vertex through a function which takes the vertex and a timecode as input and then returns a new vertex which says where that vertex should be at that timecode.

I am not a seismologist, so I can't tell you how this function would look exactly for physically correct S-waves or P-waves. So here is an example which applies a simple sine wave to the z-axis of the mesh which travels in x direction. You should be able to edit the wave functions to do what you want it to do:

```
private Vector3[] originalVertices;
private Mesh mesh;

void Start() {
    mesh = GetComponent<MeshFilter>().mesh;
    originalVertices = mesh.vertices;
}

void Update() {

    Vector3[] newVertices = new Vector3[originalVertices.Length];

    for(int i = 0; i < originalVertices.Length; i++) {
        newVertices[i] = WaveFunction(originalVertices[i], Time.time);
    }

    mesh.vertices = newVertices;
    mesh.RecalculateBounds();
    mesh.RecalculateNormals();
    mesh.RecalculateTangents();
}

private Vector3 WaveFunction(Vector3 origin, float timeCode) {
     // sine wave with an amplitude of 1 unit and a period of 2π units,
     // traveling with a speed of 1 unit per second.
     // Change this to your own wave function.
     return new Vector3 (
          origin.x,
          origin.y,
          origin.z + Mathf.Sin(origin.x + timeCode)
     );
}

```

My testing mesh in Blender:

The result in Unity (quite hypnotic):

---
Tags: unity, mesh, dynamic-mesh
---


# Question
Title: Enabling / disabling Static objects in Unity
The Unity docs clearly explain that game objects marked static should not be moved for performance reasons but I can't find any info regarding enabling / disabling.

Almost everything in my games levels is destructible so I only use real-time GI. When the player damages a game object enough it's either removed or replaced with a damaged version of the model, usually via an object pool.

What effect does enabling or disabling a static game object have on performance?

# Answer
When you set a `GameObject` as static, Unity starts optimising behind the scenes and assuming stuff about your objects. If for example you mark multiple objects as "batching static" you are basically telling Unity that these objects will never move. This means there is a chance on your final game all these objects will be "merged together" as one mesh, and be rendered like that, to make performance faster.

This is just one example, as far as I know the optimisation behaviour in Unity is not defined, and can be different from platform to platform as different things can be faster or slower on specific devices.

Although I can't know in detail, I image that when you are disabling/enabling static objects in a scene, you interfere with these optimisations, as it's not possible to disable part of a mesh.

A simple rule is, if your `GameObject` is not really static and needs to be moved or be altered in any other way, do not mark it as static. Make sure you are not trying to prematurely optimise your project, make something that works, and when that's done, only then start optimising on the most performance-intensive parts.
> 1 votes

---
Tags: unity, instancing, batching
---


# Question
Title: How can I implement pathfinding that avoids obstacles on a spherical planet?
Hi everyone, I am trying to make the enemy go around the planet, towards the player (I am using Faux Gravity for the movement logic).

I tried using Unity's NavMesh tools, but because this is not a flat mesh, they didn't really get the job done;

How can I make my enemies go around the planet towards the enemy in a physics based way?

I thought about calculating the a direction from the enemy towards the player and then moving the player towards a vector perpendicular to the planet's surface (in this case `transform.forward`) like so:

This way I can correctly move enemies towards the player, but the AI doesn't have any notion of any possible obstacle it should avoid.

I am specifically looking for some sort of A\* algorithm, that would work on a spherical surface, like the one of a planet.

Is there a better way to do this?

# Answer
> 3 votes
> I am specifically looking for some sort of A\* algorithm, that would work on a spherical surface

The name for an A\* algorithm that can work on a spherical surface is: A\*

You don't need to do anything special to make A\* work on arbitrary spaces. That's already its jam. Anything you can represent as a graph of connected sites/regions will work just fine — whether those sites are on a grid, an irregular web, in 2D, 3D, 4D or more, even non-spacetime dimensions (see past notes on pathing through dimensions of bomb inventory / key debt), or yes, even on a sphere.

To make such a graph over the surface of the sphere, a popular method is to take the grid of a wireframe unit cube and project it onto the sphere, either by normalizing the position vectors, or "spherifying" them.

You could also take your current planet mesh and create a graph node for each face or vertex, and a graph edge for each mesh edge joining them. Just make sure you maintain connectivity wherever you cross a normal/UV seam.

I'd avoid a latitude-longitude based grid here, since the pinching at the poles makes the distribution of points very uneven. But if your topography lets you park the poles out of the way in non-pathable terrain like a mountain or ocean then it might be OK. ;)

Now that you have a graph of connected sites across the sphere, you can mark those occupied by obstacles as obstructed, then search the graph for an unobstructed route to your goal using the usual A\*, or any of the variants of it you like.

Your heuristic function can still be Euclidean distance (ie. the length of the spherical cord joining two points), since all that's required of the heuristic is that it never overestimates the distance.

You could also use arc length as your heuristic: `acos(dot(start, end))` (where start & end are unit vectors in the respective directions). This takes curvature into account so it's a tighter bound and might result in better prioritization. If you go this route, you should measure your graph edge lengths in arc distance too, to ensure they never take a shortcut smaller than the heuristic predicted.

# Answer
> 0 votes
There are many options but projecting vectors is a common and efficient way of constraining movement - possibly the most elegant way.

Another possible solution - have a dummy transform at the center of the sphere as a parent of the enemies, and rotate that dummy transform using unity's built in quaternion rotation functions. However this way seems less flexible to me, since it only works with a perfect circle and is less able to deal with obstacles. I think you're on the right track.

---
Tags: unity
---


# Question
Title: How would I apply force to a bullet in 2D?
I wrote the code below in order to try to get a bullet to fire at a specific angle for my top-down shooter. However when I press space the bullet just spawns in front of the game object despite it having a bullet speed. I made sure that my bullet prefab has a rigidbody and I am calling to it in my script.

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

public class FireAway : MonoBehaviour
{
private Vector3 mouse_pos;
private Vector3 object_pos;
private float angle;
private float bulletSpeed = 1;
public GameObject ammo;
private Rigidbody2D rb2D;

void Start()
{
    rb2D = ammo.GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void FixedUpdate()
{
    // Point the cannon at the mouse.
    mouse_pos = Input.mousePosition;
    mouse_pos.z = 0.0f;
    object_pos = Camera.main.WorldToScreenPoint(transform.position);
    mouse_pos.x = mouse_pos.x - object_pos.x;
    mouse_pos.y = mouse_pos.y - object_pos.y;
    angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg - 90;
    Vector3 rotationVector = new Vector3(0, 0, angle);
    transform.rotation = Quaternion.Euler(rotationVector);

    if (Input.GetKeyDown("space"))
    {

        GameObject BulletPlayer = (GameObject)Instantiate(ammo,
transform.position, transform.rotation);
        //bullet.transform.LookAt(mouse_pos);
       rb2D.AddForce(BulletPlayer.transform.forward * bulletSpeed);
    }
}
}

```

# Answer
> 1 votes
Your problem is that you're spawning an instance of the `ammo` prefab, and then applying force *to the prefab* instead of to the instance you just spawned.

To avoid this, just have one variable for the prefab instead of two:

```
 public Rigidbody2D bulletPrefab;

```

Then instantiate it, and capture a reference to the *instance's* rigidbody:

```
 Rigidbody2D bulletInstance = Instantiate(bulletPrefab, position, orientation);

 bulletInstance.velocity = bulletInstance.transform.forward * bulletSpeed;

```

I don't recommend using force for this if you just want to set a specific launch velocity. Force can be affected by mass and timestep, so it's simpler for a case like this to just set the velocity directly.

# Answer
> 1 votes
I don't use unity myself, so I can only give you general information here:

```
rb2D.AddForce(BulletPlayer.transform.forward * bulletSpeed);

```

In order to accelerate any object to from velocity (v0), to velocity (v1), you must apply a force of newtons(N), in a direction , over a time interval (t).

At the moment, all you are doing is applying a direction (unit vector, has length of 1), then multiplying by 1, which has no effect on the vector.

The magnitude of that impulse will then be reduced by the bullet's mass, further reducing the visible effect of the impulse.

In short, the bullet has velocity, but it's so slow you can't see it move.

```
a = (F * t)/M where M is mass of the bullet, a is the change in velocity (v1-v0)

```

Basically, F must increase for your bullet to fly.

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


title: 2D character movement

text:
# Question
Title: 2D character movement
My character moves right and left correctly, I want to know if it is possible to move character forward and backward to collect hearts  (I know that in 2d no z axis I want to know if it is possible or not? )

# Answer
> 1 votes
There are definitley ways of accomplishing this without altering actual position of the character but instead making it appear that way.

For instance : You could try adding animations that show the character walking forward and backward (toward/away from screen) and scale his size to make it look like he is moving in the z axis.

# Answer
> 2 votes
Giving the illusion that there's a 3rd dimension has always been used on video games. It can be as simple or as complicated as you like, depending how you'd like the final result to look like.

In your case for example, you can move the character up/down using the Y-axis, to simulate that the character moves "back and forth". As long as the character interacts properly with the environment (in your case, picking up hearts when moving on the same plane as them) the illusion will not be noticed.

One example being Streets of Rage, which didn't even have an animation for moving up and down (it was just using the walk left/right one) and it made a very nice illusion. The character interacts perfectly with objects on the same plane as them, forcing the player to simulate this as 3D while they play.

You can of course change the scaling of the character as well, making them smaller as they move upwards, and bigger as they move downwards. This adds complexity, but gives a more realistic effect.

You can always add more complexity to add realism, but at the end of the day, it depends on the style you want your game to have. There is no wrong or right solution.

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


# Question
Title: How do I store destructible terrain that characters can walk on?
I'm trying to make a 2d game like Worms (in JS, if it's important). I found 2 possible ways of implementing destructible terrain:

1. Bitmap. Store every pixel in a huge 2-dimensional array
2. Represent the terrain as a `f(x, y)` function somehow and use the marching squares algorithm with linear interpolation.

But I still don't quite understand how should I calculate worms' movements. When a worm is standing on the ground and is walking in a certain direction, how do I calculate its next position?

I have an idea for how to do it with a bitmap, but I don't think its the best one:

1. Before the match find pixels where the worm can stand
2. When the worm starts walking find some nearby standable pixels with `standablePixelsX = wormX + direction`, where `direction = -1 or +1` based on which direction the player is moving (left or right)
3. And check those selected standable pixels with an `areConnected(pixel1, pixel2)` function which determines whether a worm can move form `pixel1` to `pixel2` (checks for blocking ceilings and stuff)

Which way should I implement destructible terrain and whats the best way to calculate worms' movements?

# Answer
# Storage of destructible terrain

For the terrain I would recommend looking at the quadtree data structure. It provides an efficient way to store destructible terrain. For an excellent, in-depth explanation, see Coding Challenge #98.1: Quadtree - Part 1 by The Coding Train.

The core idea of a quadtree is that you don't need to store every individual pixel. When talking about terrain, you will usually have large chunks of neighbouring pixels that have the same value (solid or non-solid). A quadtree takes advantage of this by storing your maps as rectangular chunks. If a chunk is broken (e.g. an explosion destroys terrain causing part of the chunk to be solid and part of the chunk non-solid) it is subdivided into smaller rectangular areas until the granularity is fine enough to have uniform solidity within all rectangles.

Here is an image from a similar Stack Exchange question to illustrate the datastructure:

# Movement along arbitrary terrain

You could break movement down into one pixel steps (to the left or the right) and examine three scenario's with each step:

```
player can move 1 pixel to side and one pixel down
    -> player is moving downhill

player can move 1 pixel to side
    -> player is moving horizontally

player can move 1 pixel to side and up
    -> player is moving uphill

```

You can simply evaluate the above cases and perform the first possible movement. If none of the three movements are possible, the player is moving into a slope steeper than 45 degrees which is considered a wall.

If you want to move more than 1 pixel per frame, you simply repeat the above procedure multiple times a frame. I.e. instead of

```
int player_speed = 4;
check_if_can_move(player.x + player_speed) { player.x += player_speed; }

```

you do:

```
int player_speed = 4;
for(int i = 0; i < player_speed; i++) {
    check_if_can_move(player.x + 1) { player.x += 1; } else { break; }
}

```

This is certainly not the most efficient kind of movement, however it perfectly complements a quadtree with detail up to one pixel. Movement is pixel-perfect. For a simple 2D game like Worms this strategy works fine.
> 6 votes

---
Tags: 2d, movement, terrain, procedural-destruction
---


# Question
Title: Structuring game narrative. Handling NPC, Quest, General Dialogue. Is Json/XML the right way to go? Or any other solutions?
Hello guys I'm try to make some games that have more to it than just simple high score scrolling shooters etc.

I'm trying to design my own systm of handling narrative. I want to be able to place NPC's in the game world, with scripts attached to them. Some of the NPC's would just have *n* random greetings. Others will be mission givers and will offer you a quest of sorts. (The quest could be go speak to Bob in the pub, or it might be bring me the Holy Grail and Crown Jewels, or something in between).

I've wracked my brain for a long while over this but sadly keep slipping back to the only way I know how, which is to manually code all the strings that people can say and have a horrible web of if statements and other such insanity to give me a rudimental dialogue system. Its not good enough even with just a few characters, but if I had dozens/hundreds of characters it would be even worse.

I've read lots about it already but I'm still very confused when I start trying on my own project. I've read that Json/XML might be the way to go and that I can add custom markups in the Json text to call methods in my code, but I dont even know if this is right and if so how I can do it.

The back of my brain is screaming at me that there is a simpler way to do it, but I've sat here for a very long time without managing to think of ideas.

Here is a diagram I drew which pretty much shows the flow of how I want my NPC to behave. If anyone can see this and then tell me how they might do something like this that would be fantastic!! (note: if Json is the correct advise, please give me a exact example of how exactly to format the Json in order to check the bools I mention in my flowchart - thanks!):

note: The circles denote an output from the data as Text for the dialogue system. The bools will need to be checked against by the data file to see which output to give (hope that makes sense and is possible)

# Answer
> 7 votes
It looks like you're trying to describe behaviour, and "tool for describing behaviour" is basically the definition of a programming language.

Data formats like XML and JSON suck for describing behaviour, because you can't have e.g. conditionals or mutable state. If you make your parser clever (such that it turns certain XML/JSON constructs into conditionals etc.), you'll soon realise you've implemented the world's worst programming language.

Use a programming language.

---

More specifically, perhaps you want a finite-state machine as an object for each mission, to track the player's progress in it? It could listen to appropriate events (like inventory changes), and change state accordingly. Then every NPC related to the mission could refer to that common data when deciding what they will say.

# Answer
> 2 votes
Data belongs into files and logic belongs into code.

If you try to encode logic in form of JSON files, you are essentially inventing a JSON-encoded scripting language. Unity already has a scripting language. It's called C#. So adding a JSON layer on top of it won't be any simpler or more maintainable than just expressing your logic in C#. The attempt to avoid hard-coding logic by inventing a new language to hard-code your logic is a well-known anti-pattern called the Inner-platform effect.

But if you are going to implement complex NPC behaviours in C# in form of if/else trees, you will notice a few problems:

* You will discover certain recurring patterns you want to reuse, like the typical fetch-quest or kill-quest loop.
* You will want to have non-blocking logic. For example, you might have a player decision deep in an NPCs dialog tree. You can't just put that in an if-statement, because the engine needs to keep running while the player decides which option to click on.

Fortunately there is a design pattern which solves these two issues in a very elegant way: behavior trees.

* Behavior trees can be nested, which allows you to create reusable behavior trees.
* Behavior trees can be built at runtime, so you can have factory-methods which generate recurring behavior tree branches like the aforementioned fetch-quest branch.
* Behavior trees can be processed asynchronously. A "let the player pick a response" node can return "running" while the player is making their decision.

---
Tags: unity, c#, dialogue-tree
---


title: Adding 2 sounds to 1 asset

text:
# Question
Title: Adding 2 sounds to 1 asset
I've got a sound looping from the start of the game, working exactly as I need it to. What I need is a second sound to alert the player that they have located the hidden object (the first sound is a locator sound to help them go in the right direction). My problem is that when I add the second sound to the object, there seems to be no change. Is there a way to add this second sound to go off when the player gets within the attenuation sphere? I don't want it to shut off the first sound though, just make the sound over it. That way if the player wanders away, they know where to go back to because the first sound will still be playing.

# Answer
> 0 votes
Add an (another?) AudioComponent that can be triggered or toggled as needed.

# Answer
> -1 votes
Reference on sound attenuation in Unreal Engine Sound Attenuation

---
Tags: unreal-4, sound, sound-effects, blueprints
---


# Question
Title: Moving an object at an angle based on quaternion rotation matrix (c++)
I have been trying to figure this out for a while now, and can't seem to get a working method. I am building a space ship movement with the following movement keys:

P = accelerate (move forward)

A = yaw left

D = yaw right

W = pitch down

S = pitch up

The following the code I have to perform the movements for keys A,D,W and S. They all work as expected. I just can't figure out how to move forward at the angle the space ship is.

```
void Player::yawRight(float deltaTime)
{
    this->yaw -= this->rotationAngle * deltaTime;

    if (this->yaw < 0.0f) {
        this->yaw = 360.0f;
    }

    cout << "yawRight: " + to_string(this->yaw) << endl;

    this->yawQuat = glm::angleAxis(glm::radians(this->yaw), glm::vec3(0, 1, 0));
    this->pitchQuat = glm::angleAxis(glm::radians(this->pitch), glm::vec3(0, 0, 1));
    this->rollQuat = glm::angleAxis(glm::radians(this->roll), glm::vec3(0, 0, 1));

    glm::mat4 rotationMatrix = glm::toMat4(glm::normalize(this->yawQuat * this->pitchQuat * this->rollQuat));

    this->model = glm::mat4(1.0f);
    this->model = glm::translate(this->model, this->position) * rotationMatrix;
}

void Player::yawLeft(float deltaTime)
{
    this->yaw += this->rotationAngle * deltaTime;

    if (this->yaw > 360.0f) {
        this->yaw = 0.0f;
    }

    cout << "yawLeft: " + to_string(this->yaw) << endl;

    this->yawQuat = glm::angleAxis(glm::radians(this->yaw), glm::vec3(0, 1, 0));
    this->pitchQuat = glm::angleAxis(glm::radians(this->pitch), glm::vec3(0, 0, 1));
    this->rollQuat = glm::angleAxis(glm::radians(this->roll), glm::vec3(0, 0, 1));

    glm::mat4 rotationMatrix = glm::toMat4(glm::normalize(this->yawQuat * this->pitchQuat * this->rollQuat));

    this->model = glm::mat4(1.0f);
    this->model = glm::translate(this->model, this->position) * rotationMatrix;
}

void Player::pitchDown(float deltaTime)
{
    this->pitch += this->rotationAngle * deltaTime;

    if (this->pitch > 360.0f) {
        this->pitch = 0.0f;
    }

    cout << "pitchDown: " + to_string(this->pitch) << endl;

    this->yawQuat = glm::angleAxis(glm::radians(this->yaw), glm::vec3(0, 1, 0));
    this->pitchQuat = glm::angleAxis(glm::radians(this->pitch), glm::vec3(0, 0, 1));
    this->rollQuat = glm::angleAxis(glm::radians(this->roll), glm::vec3(0, 0, 1));

    glm::mat4 rotationMatrix = glm::toMat4(glm::normalize(this->yawQuat * this->pitchQuat * this->rollQuat));

    this->model = glm::mat4(1.0f);
    this->model = glm::translate(this->model, this->position) * rotationMatrix;
}

void Player::pitchUp(float deltaTime)
{
    this->pitch -= this->rotationAngle * deltaTime;

    if (this->pitch < 0.0f) {
        this->pitch = 360.0f;
    }

    cout << "pitchDown: " + to_string(this->pitch) << endl;

    this->yawQuat = glm::angleAxis(glm::radians(this->yaw), glm::vec3(0, 1, 0));
    this->pitchQuat = glm::angleAxis(glm::radians(this->pitch), glm::vec3(0, 0, 1));
    this->rollQuat = glm::angleAxis(glm::radians(this->roll), glm::vec3(0, 0, 1));

    glm::mat4 rotationMatrix = glm::toMat4(glm::normalize(this->yawQuat * this->pitchQuat * this->rollQuat));

    this->model = glm::mat4(1.0f);
    this->model = glm::translate(this->model, this->position) * rotationMatrix;
}

void Player::accelerate(float deltaTime)
{
    float x = cos(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    float y = sin(glm::radians(this->pitch));
    float z = sin(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));

    glm::vec3 front = glm::vec3(x,y,z);
    front = glm::normalize(front);
    glm::vec3 right = glm::normalize(glm::cross(front, glm::vec3(0, 1, 0)));

    glm::mat4 rotationMatrix = glm::toMat4(glm::normalize(this->yawQuat * this->pitchQuat * this->rollQuat));

    this->position += front * 0.01f;

    this->model = glm::mat4(1.0f);
    this->model = glm::translate(this->model, this->position) * rotationMatrix;
}

void Player::accelerate(float deltaTime)
{
    // get the forward vector
    float x = cos(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    float y = sin(glm::radians(this->pitch));
    float z = sin(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));

    glm::vec3 front = glm::vec3(x,y,z);
    front = glm::normalize(front);

    glm::mat4 rotationMatrix = glm::toMat4(glm::normalize(this->yawQuat * this->pitchQuat * this->rollQuat));

    // update the position
    // this is incorrect
    this->position += front * 0.01f;

    this->model = glm::mat4(1.0f);
    this->model = glm::translate(this->model, this->position) * rotationMatrix;
}

```

Note: the actual code is crappy as it has a lot of reptition, I will fix that.

For the `accelerate()` method I get the forwad vector from the yaw and pitch, but it doesn't move in the right direction. Can someone provide me a guide or an explanation as to how I can make the ship move forward in the orientation it current is in? Thanks!

# Answer
I'm not sure if this question is actually about quaternions or about orienting an object in 3D space via Euler angles. It seems your main concern is object orientation, so that is what I'll focus on in this answer.

For the sake of this answer:
x-axis rotation: pitch
y-axis rotation: yaw
z-axis rotation: roll

```
//orient the game object in 3D space and move it (pseudo-code)
void MoveGameObject(float xMove, float yMove)
{
    //add the move amount for this frame to the rotation angles
    gYaw += xMove;
    gPitch += yMove;

    //make sure: 90 > pitch > -90
    if(gPitch < -90.0f)
    {
        gPitch = -90.0f;
    }
    else if(gPitch > 90.0f)
    {
        gPitch = 90.0f;
    }

    //convert: degrees->radians
    float yawRad = gYaw * (3.14 / 180.0f);
    float pitchRad = gPitch * (3.14 / 180.0f);

    //convert orientation to spherical coordinates
    Vector3 tar;
    tar.x = cos(yawRad) * cos(pitchRad);
    tar.y = sin(pitchRad);
    tar.z = sin(yawRad) * cos(pitchRad);
    tar.normalize();

    //move forward
    if(direction == FORWARD)
    {
        position += tar * speed;
    }
    //move back
    if(direction == BACK)
    {
        position -= tar * speed;
    }
    //move left
    if (direction == LEFT)
    {
        Vector3 leftVector = tar;
        leftVector = leftVec.crossproduct(0, 1, 0);
        leftVector.normalize();
        position -= leftVector * speed;
    }
    //move right
    if(direction == RIGHT)
    {
        Vector3 rightVector = tar;
        rightVector = rightVector.crossproduct(0, 1, 0);
        rightVector.normalize();
        position += rightVector * speed;
    }
}

```

This code will move your object in the correct direction based on its orientation.
An excellent tutorial on this sort of thing.
> 2 votes

# Answer
The most common problem for beginners, is the multiplication order of the rotational matrices, and determine what coordinate system is used left/right handed, and whether axis-Y is up or forward etc. You'll need to know exact understanding what being used, and what your math will result into.
> 0 votes

---
Tags: opengl, c++, vector, quaternion
---


# Question
Title: Is any Update() called always first than any LateUpdate() from other scripts?
If a script is called at a specific moment in the script execution order, will every LateUpdate() functions from the rest of the objects work after that Update()? The documentation isn´t clear about it.

# Answer
> 1 votes
Execution order effects only scripts initialization, not the main loop methods like Update or LateUpdate.

Awake is called right after construction, Start before first Update. Use these methods to resolve dependencies between components.

Execution order of Event functions

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


# Question
Title: Destroying 1 of 2 GameObjects with that same script attached in UNITY
So I have 2 GameObjects, and they have exactly the same script attached to them called 'RoomSpawner'. Via this script, I want to destroy just ONE of these TWO GameObjects. How can I do this? By typing Destroy(gameObject); It will destroy 2 GameObjects :/, I'm confused, any ideas?

Those 2 GameObjects are in the same positions, and I want to delete them by OnTriggerEnter2D

# Answer
> 0 votes
Pretty simple. Have the one you don't wanna destroy with a public bool and check it true in the inspector:

```
//other variables...
public bool doNotDestroy;
//other code...
function OnTriggerEnter(Collider collision)
{
  //other statments...
  if (collision.gameObject.name = /*name of needed object to hit*/  && doNotDestroy == false)
{
  //destroy code...
}
}
//rest of code follows...

```

Comments indicate places where the rest of your script would be.

# Answer
> -1 votes
I can put my head through, ok Create An empty gameObject and make your GameObjects Childrens of the former, Add the script and create a private List of gameObjects, Set it in the Start,
Use foreach statement to get the component GameObject,
Instead of Destroy, SetActive the gameObject at the index to False. I think that will do.

# Answer
> -2 votes
Okay So I found out solution, I've simple checked GameObject's ID and destroy them.

# Answer
> -2 votes
Super simple solution use static variables

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


# Question
Title: How can I highlight words in a word search puzzle?
For days I am struggling to implement the highlighting functionality in game as there is not much tutorial also for this. I did how ever make the cell of the grid change the material color but it looks ugly that's why I prefer to choose this method (see pic).

How can I implement a highlighting method that will work the same on link.

---

---

My try:

```
 private bool first_sel = false;
    private void Update() {
        if (Input.GetMouseButton(0)) {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out pressed)) {
                if (pressed.transform.tag == "cell") {
                    if (!first_sel) {
                        GameObject sel = Instantiate(sel_cell, new Vector3(pressed.transform.position.x,
                            pressed.transform.position.y, pressed.transform.position.z - 0.55f), Quaternion.identity);
                    }

                }
            }
        }

```

# Answer
> 1 votes
I would just use the line render with a transparent material and a slight offset on the Z axis so it doesn't clip with your board.

```
public float DistanceFromBoard;

private bool mouseDownOnLastFrame = false;
private GameObject startingCell;
private GameObject hoveredCell;
private Vector3 mouseWorldPosition;
private LineRenderer lineRenderer;

private void Awake()
{
    lineRenderer = GetComponent();
    lineRenderer.enabled = false;
}

private void Update()
{
    if(Input.GetMouseButton(0))
    {
        HandleDrag();
    }
    else if(mouseDownOnLastFrame)
    {
        FinishHighlight();
    }
}

private void HandleDrag()
{
    RaycastHit hit;
    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);

    mouseDownOnLastFrame = true;

    if (Physics.Raycast (ray, out hit))
    {
        currentCell = hit.collider.gameObject;
        mouseWorldPosition = hit.point;

        if (startingCell != null && go.tag == "cell") // instead of using a tag here I would add the cells to a layer and use a layermask
        {
            startingCell = go;
            lineRenderer.enabled = true;
        }
    }

    lineRenderer.positions[0] = startingCell.transform.position - new Vector3(0f, 0, DistanceFromBoard);
    lineRenderer.positions[1] = hoveredCell.transform.position - new Vector3(0f, 0, DistanceFromBoard);
}

private void FinishHighlight()
{
    startingCell = null;
    lineRenderer.enabled = false;

    // here you might want to validate the highighted word and save the word to a collection of found words.

    // You're also going to want to copy this line renderer's positons and copy them to a new gameobject.
    // this is because we cannot only use one line to highlight all the words
}

```

Also remember to add a line renderer component to your gameobject and give it 2 blank positions.

As for the material, create a new material using the standard shader but change it from "opaque" to "transparent" and lower the alpha.

---
Tags: unity, 3d
---


# Question
Title: How to create a looping or spherical world?
I wish to create a 3D first person world, in which the player, once they reach one end of the map are unknowingly transported back to the opposite end, or a spherical world with a surface where the player can walk on while still experiencing gravity like normal. Unfortunately I couldn't find a good solution for doing that in either unity or ue. Any ideas would be appreciated.

# Answer
> 6 votes
I am not familiar with the Unreal engine, so this answer will focus solely on Unity.

Unity's game scenes are strictly euclidean and do not allow real portals. But what you can do is separate the level into individual prefab segments which you remove and add to the scene while the player is moving through the game or looking away. This method is, for example, used in the game Antichamber to create spacially impossible levels. In a game with more open scenarios you could divide the game world into cubic chunks which you destroy when the player moves out of view-range and instantiate when they come closer (I suspect Kerbal Space Program uses this approach to render planet surfaces).

If you want to create a spherical planet and it will not be too large and complex to keep it completely in memory all the time, you can do that by not using the gravity of the Unity physics system but instead calculate the gravity acceleration by yourself based on the relative position to the center of the planet and orientate all objects to always be rotated perpendicular to the center of gravity.

# Answer
> 1 votes
In Unity you can do this:

I had the same "dream" of making a spherical gamemap for years. I eventually made a solution for gravity on a spherical map. And even if it's not perfect, here is a simple example of how I did it. Apply this script to an object (fx a car or whatever) with a rigidbody in Unity. Vector3.zero is the center of the "planet" and can be replaced with your "planets" transform.position. Don't forget to make your planets rigidbody kinematic (check the box) so that the planet doesn't move too on impact from other objects. Hope this helps :)

C-sharp (C#) script code:

```
using UnityEngine;
using System.Collections;

public class Gravity : MonoBehaviour {

    public float gravityForce;
    public Rigidbody rb;

    void Start()
    {
    rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
    rb.AddForce((Vector3.zero - transform.position) * gravityForce);
    }
}

```

if you fx want a motorcycle to stand upright you can lower its com (center of mass)

---
Tags: unity, unreal
---


# Question
Title: "DirectX will only draw polygons with an [X,Y] from [-1,-1] to [1,1] and with a Z from 0 to 1.", What does this mean and how to work around it?
I've been following the D3D11 tutorials on Rastertek to expand my knowledge on rendering which I will need as I want to build my own engine, as a hobby.

After finally getting a model to be rendered to the screen in 3D space, and being able to move and rotate both the camera and the model, I wanted to import custom FBX models instead, which isn't included in the tutorial. I found this tutorial online on just that, which I followed alongside the fbx SDK's documentation.

It now works to load and render FBX models, however, the vertices are quite messed up on some models, and on some, it works perfectly, then I read in the tutorial, and I quote:

"Finally, if you don’t use the shitty-bell FBX attached up at the top of this post, take note. In its default state, DirectX will only draw polygons with an \[X,Y\] from \[-1,-1\] to \[1,1\] and with a Z from 0 to 1. Look through the vertices in your FBX and make sure everything is in that range!"

As you can guess, that "shitty bell" works perfectly to draw. Anyway, what does it mean that it'll draw polygons within that range, also, how do I work around that when modeling?

# Answer
> 15 votes
While technically true, the statement in that tutorial is phrased somewhat misleadingly and in a bit of an alarmist fashion.

Generally speaking you do not need to worry about this.

> Anyway, what does it mean that it'll draw polygons within that range?

Model vertices in the graphics pipeline go through several different stages as they pass through the graphics pipeline. Each of these stages is its own coordinate system, and a vertex passes between those coordinate systems by way of transformation matrices.

This tutorial is referring to one of the final stages in the pipeline that vertices exist in just prior to rasterization, called *homogeneous screen space* (but note that it also has other names). The purpose of this coordinate space is to scale all the vertex data down into a known, *normalized* range so that it can be mapped to the pixel space of the target window. Typical ranges for axes in this space in various graphics APIs are -1 to 1 or 0 to 1, because both are simple to then map to the 0-to-some-large-integer pixel space of the target window.

Normally you normally configure the model, view and projection matrices (as well as the viewport transform if needed) appropriately for your scene. The tutorial you linked omits these steps, perhaps for brevity. If you don't explicitly do any transformation of vertex data in your shaders or the like, the net result is as if all your transformations were identity matrices, which means all transformations that do end up done by the pipeline automatically also end up essentially be no-ops (except the viewport transform) and you do effectively have a visible range that matches the ranges of homogeneous screen space.

> how do I work around that when modeling?

You don't. Model your objects however you need, and then adapt *Direct3D* to those needs, as above, rather than the other way around. While ultimately it is true that your coordinates will end up in some normalized, -1-to-1 type of form just prior to drawing, you can configure D3D to transform and scale any coordinate range you want into that penultimate range.

# Answer
> 7 votes
The range `[-1 ; 1] x [-1 ; 1] x [0 ; 1]` mentioned in the tutorial refers to the ***canonical view volume***. It is the final ***coordinate space*** vertex data gets mapped to before everything is rasterized to your screen. To understand what exactly this means, it helps to take a look at what a rendering pipeline typically looks like.

# Coordinate spaces

A coordinate space refers to the coordinate system you use to define the positions of vertices within it. As a real-life example, imagine you have a desk with a keyboard on top of it and you want to express the position of the keyboard. You could define the front left corner of the desk to be position `(0, 0, 0)` — this is called the ***origin*** —, the X-axis to be along the length of the desk (left to right), the Y-axis to be along the depth of the desk (near to far), and the Z-axis to be vertically upward from the desk. If your keyboard is located 50 centimeters to the right of this corner, and 10 centimeters away from the nearest edge, it is located at position `(50, 10, 0)`.

Alternatively, you could define the corner of your room to be position `(0, 0, 0)`. Lets say your desk is located 200 cm from the left wall, 300 cm from the front wall, and the desk is 70cm in height. In this case your desk's top is located at position `(200, 300, 70)`, and your keyboard is located at `(250, 310, 70)`.

These are two examples of different coordinate spaces, and how they affect the position coordinates of the objects within them. Similarly, vertex data in a 3D rendering pipeline is transformed across various coordinate spaces before it ends up on your screen.

# Coordinate spaces in a 3D rendering pipeline

Individual objects are modelled in 3D software such as Autodesk Maya, Blender ... . They are often modeled centered around the origin. This coordinate space is called ***model space***. If you were to render several objects in model space together, they would all be piled up centered around the origin.

Instead a new coordinate space called ***world space*** is defined. Think of this as your game world, with the origin being the center of the world. When transforming model space to world space coordinates, translations, rotations, scaling and other operations are performed. For example if you want to render a keyboard at position `(250, 310, 70)` of your world, you would offset all its vertices by this vector. Mathematically speaking, this is done using a transformation matrix. You can apply a different transformation to each individual object to place objects in your game world.

You now have a big pile of vertices where every objects is placed in the correct position. You now need to define what part of the world you want to look at. This is done by moving all vertex data to ***camera space***. An often-employed convention is have the camera positioned in the origin of ***camera space***, to have it look towards the positive Z-axis (the ***eye-vector***) and to have the positive Y-axis point upward (the ***up-vector***). When converting from world space to model space, we thus want to move and rotate all vertex data so that our objects of focus are near the origin and have positive Z-coordinates.

When you look at objects in real life, you will notice a phenomenon called ***foreshortening***. This means objects near you appear bigger (i.e. take up more of your view), while objects far away from you appear smaller (i.e. take up less of your view). We simulate this by applying a ***perspective transformation***, which moves our camera space vertex coordinates to ***projected space***.

Finally, note that we have 3D vertex data, that needs to be rendered on a 2D screen (e.g. 1920 by 1080 pixels). The vertex data in camera space is therefore transformed to ***screen space***. Your graphics API takes care of rendering the screen space vertex data to your screen. The process of converting vertex data to pixels on your screen is called ***rasterization***. But what vertex coordinates end up where on your screen? This is where the ***canonical view volume*** comes into play.

DirectX specifies that the X-coordinate of the vertex is mapped to the horizontal position on the screen. Specifically: range `[-1 ; 1]` is mapped to `[0 ; 1920]` (in case of a 1920 x 1080 screen). The Y-coordinate of the vertex is mapped to the vertical position on the screen. Specifically: range `[-1 ; 1]` is mapped to `[0 ; 1080]` (in case of a 1920 x 1080 screen). The Z-coordinate is used to determine what vertices need to be rendered in front or behind each other. Specifically, vertices near 0 are near the camera and should be rendered in front. Vertices near 1 are far away from the canera and rendered behind. Vertices with a Z-coordinate smaller than 0 are behind the camera and thus ***clipped*** — i.e. not rendered. Vertices with a Z-coordinate larger than 1 are too far away and are clipped as well.

Your perspective transform thus needs to move all vertices you want visible on your screen inside this canonical view volume. In the tutorial you followed, all of these transformations are omitted to keep the tutorial simple. You are thus directly rendering to the canonical view volume. This is why the author says anything outside of range `[-1 ; 1] x [-1 ; 1] x [0 ; 1]` is not visible.

# References

For an article with images to illustrate these various coordinate spaces, see World, View and Projection Transformation Matrices by CodingLabs.

---
Tags: rendering, directx11, fbx
---