# Question
Title: How to create a native windows menu / ribbon for a DirectX 11 app
I need to create menu items on top of my DX11 windowed app - similar to most windowed applications (File, Edit, etc...). How can I achieve this ? There is a `hMenu` handle to pass to the DirectX window creation function but I have no idea how to create this object.

Additionnaly I'd like to have 1 or several ribbons under the window menu with icons to trigger functionnality.

**EDIT** My menu is all good now and I chose to implement a windows ribbon, but I'm still having problems at creating the ribbon. Here is a screenshot of my app. The green color is the Direct3D clear color - I would like my ribbon to display under the menu (and eventually remove the menu after that).

My ribbon code being :

```
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT paintStruct;
    HDC hDC;

    switch (message)
    {
    case WM_CREATE:
    {
        if (!SetupMenus(hwnd)) MessageBox(nullptr, TEXT("Failed to setup GUI."), TEXT("Error"), MB_OK);
    }

    // ...
}

bool SetupMenus(HWND hwnd) {

    // Create the menu
    // ...

    // Create the ribbon
    IUIFramework* pFramework = NULL;
    HRESULT hr = ::CoCreateInstance(CLSID_UIRibbonFramework, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFramework));
    if (FAILED(hr)) std::cerr << "Fail #1" << std::endl;

    hr = pFramework->Initialize(hwnd, IUIApp);
    if (FAILED(hr)) std::cerr << "Fail #2" << std::endl;
}

```

outputs `Fail #1`. Why can't I create the ribbon ?

# Answer
> 1 votes
For `CoCreateInstance` to work you need to prepare the call with either `CoInitialize` or `CoInitializeEx` function.

## CoInitialize function

> Initializes the COM library on the current thread and identifies the concurrency model as single-thread apartment (STA).

## CoInitializeEx function

> Initializes the COM library for use by the calling thread, sets the thread's concurrency model, and creates a new apartment for the thread if one is required.

# Answer
> 2 votes
There is a CreateMenu method you can use. More information on MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646977.aspx

I don't know about the ribbon functionality.

---
Tags: directx11, user-experience, interface, menu
---


# Question
Title: Vertex data split into separate buffers or one one structure?
Is it better to have all vertex data in one structure like this:

```
class MyVertex
{
  int x,y,z;
  int u,v;
  int normalx, normaly, normalz;
}

```

Or to have each component (location, normal, texture coordinates) in separate arrays/buffers? To me it always seemed logical to keep the data grouped together in one structure because they'd always be the same for each instance of a shared vertex and that seems to be true for things like character models (ex: the normal should be an average of adjacent normals for smooth lighting). One instance where this doesn't seem to work is other kinds of meshes like say a cube where the texture coordinates for each may be the same but that causes them to be different where the vertices are shared.

Are they normally kept separate? Won't this make them less space efficient if there needs to be an instance of texture coordinates and normals for each vertex (they won't be indexed)? Can OpenGL even handle this mixing of indexed (for location) vs non-indexed buffers in the same VBO?

# Answer
It's typical to keep them together. Then when you're creating your VBO, you can easily generate an interleaved VBO with all the data. This is very fast and a typical method when creating VBOs.

I have a few different data structures for vertices. When I know there isn't going to be any data of a specific type, I will leave out that data type and just interleave the data types present. For example, some of my models have bone information interleaved with the vertex data. Others do not. So I have a vertex structure that has that extra information and one that doesn't. I use both and have separate draw calls for each to set the appropriate pointers.
> 2 votes

# Answer
Given importance of locality of reference for GPU cache, the general consensus is that you should *always* default to interleaving vertex attributes *unless* circumstances prevent you from doing so... such as the (semi-)shared circumstances you mention. There are many sources citing this on SO.

*Not* interleaving becomes important where your data set is very large and you genuinely don't want to waste space / system bus bandwidth specifying interleaved attributes that are optional or could otherwise be deduced from a smaller data set; e.g. in a 10M vertex dataset, if you could use the same value for every group of 4 vertices therein, you'd probably want to do so. But for smaller datasets, the ease of interleaving and repeating your data would override the need for reduction.

Another reason *not* to interleave is when you want your data modular, for example where geometry (i.e. positions) remain the same, but colour, normal maps etc. change (think human character geometry but textured as, say a recently-turned Borg where implants have grown under the skin).
> 0 votes

---
Tags: opengl, 3d, vertex-arrays
---


# Question
Title: Is there a way to bypass Directx Effect Files?
I am now trying to abstract my rendering pipeline, and I've been able to abstract OpenGL fairly easily. But now I have ran into a rather ugly problem with Directx.

Most of my knowledge about Dx9, 10, and 11 makes use of effect files. Something that openGL distinctly lacks. I know that this file does not have to be used. However, by the way all of DX's documentation had been written, it seems like it is required and there is no way around it.

Can anyone give me a lead here?

# Answer
FXC or `D3DXCompileShader` or `D3DCompile` to compile basic HLSL vertex/pixel/... shaders (single entry point, just like GLSL).

Then create shaders from the generated shader blobs using API functions such as `CreatePixelShader` (D3D9) or `CreatePixelShader` (D3D10/11). Then apply these shaders with `SetPixelShader` (D3D9) or `PSSetShader` (D3D10,11).

To transfer uniform data to shaders, since you want to deal with both D3D9 and 10/11, I'd suggest getting used to mapping uniform values manually by appending code like `: register(c0)` (D3D9 uniform values) and `: register(b0)` (for D3D10/11 uniform blocks). A documentation page on shader constants could help make sense of this.

This tutorial shows how to compile non-effect shaders from file in D3D11.
> 5 votes

---
Tags: opengl, architecture, directx
---


# Question
Title: Why the skyline continues to stay on the same place and how to change this?
I started my first Unity3D project and in this game main hero should be able to fly up passing clouds and then reaching open space but i faced with the problem. No matter how long and fast i am flying after takeoff the skyline continues to stay on the same place. Currently i'm going to rotate the main hero so that skyline would go down. But maybe someone can suggest me more common and better way to achieve the effect of leaving the Earth?

I think it would be bad idea to post all my code here because there is a lot of code that does not relate to the topic. But i will try to explain what i'm doing now and i will show you short piece of code. I have global parent object and a main hero is added as a child to it. Then when as main hero moving up relative to the global object i start to rotate this global object around z-axis so that gradually the main hero is looking to the sky.

And for skyline i'm using procedural skybox.

I hope this piece of code will explain better of what i'm doing now:

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

public class PlayerController : MonoBehaviour
{
    float gravity;

    GameObject global;//main hero’s parent

    Vector3 startHeroLocalPos;//start hero position relative to the global object

    public float degreesPerUnit = 1.0f;//global object will rotate by this amount of degrees after the player has moved up by one unit

void Start ()
{
    global = GameObject.FindGameObjectWithTag ("GlobalObject");
    startHeroLocalPos = transform.localPosition;
}

void Update ()
{

    float curAngle = (transform.localPosition.y - startHeroLocalPos.y)*degreesPerUnit;
    global.transform.rotation = Quaternion.AngleAxis(curAngle, Vector3.back);

}
}

```

# Answer
> 3 votes
A skybox is not a standard mesh and does not behave like other meshes.

A skybox does not move (relative to the camera) when you're moving the camera, this way it simulates being very far away.

You'll likely want some kind of large cylinder around the player, maybe have the X/Y (with Z being up, I don't know what coordinate system unity uses) position set to the camera's position every frame.

---
Tags: unity
---


# Question
Title: Is this the typical approach to modern OpenGL UI & Text rendering, for mobile?
I'm implementing GUI in OpenGL ES 2.0 to fit with my application framework's existing structure. I'd like to have the UI rendering eat as little mobile processing capacity as possible. So to confirm...

**Is the following *general* approach standard these days**, for **mobile games?**

Use the following for each of **controls** and **text**:

* One VBO - one `glDrawElements()` call for all elements
* One texture atlas (certainly just one for text, preferably just one for control backgrounds)
* Many quads batched in VBO, each quad corner having appropriate UVs to access the character or detail texture in question
* For overlapping UI "panels", turn on depth buffer & use different float depths per panel
* Modifiable textfields have their own small, separate VBO modified using `glBufferSubData()` or `glBufferData()` (to shorten on backspace/delete) as noted here.

Please confirm / deny / correct existing points or add missing details where necessary.

# Answer
> 3 votes
Your points seem reasonable.

For static elements that are set up once and never change, you can certainly pack them into a `GL_STATIC_DRAW` buffer and keep it alive for as long as needed. If you still have to move these static elements around in the screen, then this approach is not very interesting anymore because each would need a transformation matrix that can only be set via uniforms, so it results in one draw call per element.

The "usual" way of handling UI is to just resubmit the whole vertex data each frame, using screen space positions. Generate the final 2D vertexes in the application code and submit to a dynamic VBO. So you can, as described in your first point, draw everything with a single draw call (assuming other things like textures are not involved. Texture altas can help).

So the decision might be between either several draw calls per frame or one large buffer update per frame and a handful of draws.

You should certainly try to batch things that share the save properties together. Drawing with depth enabled is also interesting, since it should lift the requirement of a sorting step before submission.

You can also try to be smart and avoid resubmitting individual UI elements that didn't change or move in a given frame (assuming you are taking the path of generating the final vertex position on the CPU-side).

Since this is about mobile, mandatory read: Best Practices for Working with Vertex Data.

---
Tags: opengl, performance, opengl-es, mobile, efficiency
---


# Question
Title: Texture Not Rendering in C++ SDL OpenGL(glut)
I don't understand why my texture("texture.bmp"), is not showing on the screen. Please help me.

The whole drawing function:

```
///HERE EVERYTHING IS BEING RENDERED
void Main::display(){

    int startTime = GetTickCount();

    ///BACKGROUND COLOR
    glClearColor(0.3f, 0.3f, 2.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    ///LOAD THE IDENTITY MATRIX FOR THE DRAWING
    glLoadIdentity();

    ///SO EVERYTHING HAS THE CORRECT SIZE
    glTranslatef(0.0f, 0.0f, -5.0f);

    ///CAMERA MOVEMENT
    glTranslatef(cameraX, 0.0f, 0.0f);

    ///THE SUN
    glBegin(GL_QUADS);
        glColor3f(1.0f,1.0f,0.0f);

        glVertex2f(-3.0f, 2.0f); // The bottom left corner
        glVertex2f(-3.0f, 2.5f); // The top left corner
        glVertex2f(-2.5f, 2.5f); // The top right corner
        glVertex2f(-2.5f, 2.0f); // The bottom right corner
    glEnd();

    ///THE GROUND
    glBegin(GL_QUADS);
        glColor3f(0.5f,2.0f,0.5f);

        glVertex2f(-20.0f,-4.0f);
        glVertex2f(-20.0f,-1.0f);
        glVertex2f(130.0f,-1.0f);
        glVertex2f(130.0f,-4.0f);

        glColor3f(0.0f,1.0f,0.0f);

        for(float i = 0.0f ; i < 100.0f ; i += 5.0f){
            glVertex2f(i,-1.0f);
            glVertex2f(i,ranFloat[static_cast<int>(i-4.0f)]);
            glVertex2f(i+1.0f,ranFloat[static_cast<int>(i-4.0f)]);
            glVertex2f(i+1.0f,-1.0f);
        }
    glEnd();

    ///THE GRASS
    glBegin(GL_QUADS);
        glColor3f(0.0f,0.5f,0.0f);

        glVertex2f(-20.0f,-1.2f);
        glVertex2f(-20.0f,-1.0f);
        glVertex2f(130.0f,-1.0f);
        glVertex2f(130.0f,-1.2f);
    glEnd();

    ///THE PLAYER
    glTranslatef(playerX,playerY,0.0f);
    glBegin(GL_QUADS);
        glColor3f(1.0f,0.0f,0.0f);

        glVertex2f(-3.0f,-1.0f);
        glVertex2f(-3.0f,0.0f);
        glVertex2f(-2.8f,0.0f);
        glVertex2f(-2.8f,-1.0f);
    glEnd();

    ///TEXTUREEEEEEEEEEEEEEEEEEEEEE
    glBindTexture(GL_TEXTURE_2D,texture);
    glEnable(GL_TEXTURE_2D);

    int X = 0;
    int Y = 0;
    int Width = 1;
    int Height = 1;

    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f(X, Y, 0);
        glTexCoord2f(0, 1); glVertex3f(X + Width, Y, 0);
        glTexCoord2f(1, 1); glVertex3f(X + Width, Y + Height, 0);
        glTexCoord2f(1, 0); glVertex3f(X, Y + Height, 0);
    glEnd();
    glDisable(GL_TEXTURE_2D);

    ///CLOUDS
    glBegin(GL_QUADS);
        glColor3f(1.0f,1.0f,1.0f);
        for(float i = 0.0f ; i < 100.0f ; i += 5.0f){
            glVertex2f(i,3.0f);
            glVertex2f(i,4.0f);
            glVertex2f(i+4.0f,3.0f);
            glVertex2f(i+4.0f,4.0f);
        }
    glEnd();

    if(Input::flying){
        Input::returnFly(0.007f);
    }

    elapsedMS = GetTickCount() - startTime; // Time since start of loop
    //std::cout << "FPS: " << elapsedMS << std::endl;

    ///THE ACTUAL MOVEMENT
    playerY += playerFly;//*elapsedMS;
    playerX += cameraSpeed*-1;//*elapsedMS;
    cameraX += cameraSpeed;//*elapsedMS;

    ///SWAP THE BUFFERS FOR SMOOTH RENDERING
    glutSwapBuffers();
  }

```

The rest of my code has nothing to do with the texture loading. The loading is not the problem, because I didn't get any errors.

# Answer
Are you checking that your SDL\_Surface\* is valid? Are you sure that your "Mode" is RGB/RGBA and not BGRA/BGR?

I think the problem is that you need to pass the Surface-\>format-\>BytesPerPixel as the third argument to glTexImage2D instead of Mode.

Also, I would set the Min/Mag filter before calling glTexImage2D.

Like this:

```
void Main::loadStuff() {
    GLuint texture = 0;

    SDL_Surface* Surface = SDL_LoadBMP("texture.bmp");
    if (!Surface) {
        // error, report?
        return;
    }

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    int Mode = GL_RGB;

    if(Surface->format->BytesPerPixel == 4) {
        Mode = GL_RGBA;
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, Surface->format->BytesPerPixel, Surface->w, Surface->h, 0, Mode, GL_UNSIGNED_BYTE, Surface->pixels);

    SDL_FreeSurface(Surface);
}

```

Bonus points if you want to work in `std::unique_ptr` for you surface.
> 0 votes

---
Tags: opengl, c++, textures, sdl
---


# Question
Title: Unity3D Joystick Buttons Xbox360 & PS3 have Inconsistent Button Inputs?
I've been browsing through Google and researching button inputs in Unity, and I came across this page. When looking at it I noticed that the B button on the Xbox360 controller is set to Button 1, but Button 1 on the PS3 controller is set to X.
On a side-note, I noticed that BlazBlue: Continuum Shift EXTEND on Steam also has this issue when it comes to button inputs as an Xbox360 Controller inputs exactly as shown and a PS3 controller uses Square for Confirm and X for Cancel.
Does this inconsistency in buttons exist and how can I fix this problem so that A=X, B=O, X=Square, and Y=Triangle for my Windows-distributed game if it does? I guess a more appropriate question would be what the button mappings are for PS3 and Xbox360 formatted controllers?

# Answer
Yes, PS3 controllers are a different configuration than the Xbox controllers. XBox maps to XInput while PS3 is proprietary.

If you treat Button 1 on all joysticks as the fire button, then yes it will be inconsistent. The problem gets even worse if you assume the axis's are the same.

Fortunately, you can map them however you want in Unity's Input Manager. Just don't rely on the ordering of buttons. Map the controllers to actions and then you don't need to worry about if the controllers match or not.

On the downside, if you want to support many different controllers that may have varying configurations, then you may be limited by using the input manager. This isn't a problem though until you have 80 mappings or more than 17 different controller devices to support.

Fortunately, most aftermarket controllers are DirectX compatible, meaning they will conform to the xbox configuration.

In the unlikely event you need to support lots of different devices, you might want to look at Unity Custom Input Manager. It's free, and even if you don't need to support so many devices, it's worth investigating. It lets you do some things that the builtin Input Manager won't. Like modifying the mappings at runtime (EG, let the player customize the mappings in-game).
> 2 votes

---
Tags: unity, controllers, monodevelop
---


title: OpenGL - Bind Buffer Arrays question

text:
# Question
Title: OpenGL - Bind Buffer Arrays question
So this is probably a simple question:

But how come sometimes I see it like this:

```
GLuint vbuffer;
glGenBuffers(1, &vbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vbuffer);

```

but when done in multiples:

```
GLuint VBOs[2]
glGenBuffers(2, VBOs);
glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);

```

Im curious why glGenBuffers has a & in the first one, and not in the second case. Is it because arrays are always passed by reference? and is vbuffer a POINTER to something or just a simple data structure (GLint in this case).

# Answer
> 1 votes
In C++ the deceleration of an array holds nothing more then a pointer/reference to the memory address where the first piece of data in that array is stored.

The subscript is simply used as offset to the address to read the following memory.

So yes basically an array deceleration is just a reference/pointer.

---
Tags: opengl
---


# Question
Title: Generate a 2d mesh terain out of triangles (low details)
I'd like to learn a good algorithm to generate a 2d mesh made out only of triangles to be used as a terrain.

Its not important to get a high detail terrain. It should just have a triangle looking style.

Also the mesh should be extendable endlessly in all directions because the map will be endless. I thought about to having chunks of meshes saved in a file so they can be loaded during the execution.

Something like this (from Chasing Aurora):

# Answer
Try this:

1. Generate random points
2. Compute delaunay triangulation of those points
3. Use those delaunay triangles as your mesh

By restricting the domain and distribution of the random points, you can control the height of your terrain more carefully.

If you want to go beyond this and generate consistent terrain, or geometries that aren't just random mess, you will want to try some kind of procedural terrain generation. A great write-up about this can be found on NVIDIA's GPU-Gems site. The NVIDIA write-ups are *really good* disregarding your implementation tool, you don't have to actually implement it on the GPU.
> 4 votes

---
Tags: 2d, terrain, mesh
---


# Question
Title: When to use C++ and when to use blueprints?
I'm trying to learn how to use the Unreal Engine. I have basic knowledge of C++. Recently I started making a Survival Horror Game as a project that I'm just doing for the learning experience. So far though I've implemented every feature through the Blueprint system.

So my question is for what and when will I use code to improve/make a game in Unreal Engine?

# Answer
You don't need to use C++ for anything as far as I know. Its more of a matter of preference. If you are a programmer, you might do things faster in code, while some might prefer blueprints.

The runtime performance difference is there, but is usually negligible, so don't have that in mind too much.

Bottom line, ideally, you would prefer C++ when you are writing performance critical sections and use blueprints for higher level interactions. If you are like me, you'd probably prefer writing everything, since visual programming is not something I like so much.
> 17 votes

# Answer
It depends whether you are working in a team or not. If you are the only person developing the project, this is a matter of your preference. If you are a programmer in a team it is a must that you put all logic into C++ and allow artists/level designers to react on events in game via the event system.

Also, for me, writing code is faster, but I can imagine that for some people it is the other way. Visual Studio offers many sophisticated tools like *go to definition*, robust finding options, a much better debugging environment, some refactor options and more. There are no such tools in Blueprints or they are much more basic which makes things like complex networks a pain to modify and change.

If you find C++ hard or you don't feel comfortable with it, start your first projects with Blueprints. After you're done, you will know engine better and will feel comfortable with blueprints, this will be a good moment to start to develop in C++.
> 2 votes

---
Tags: c++, unreal-4
---


# Question
Title: OpenGL SDL Texture doing really weird things
I am trying to render a .png image to the screen using C++, SDL and glut.

This the texture I made using paint

This is what I get on the screen:

Does anyone have an idea what could cause this?

How I loaded the image:

```
void Main::loadStuff() {
    SDL_Surface* surface = IMG_Load("C:\\Users\\VliegendeGeit\\Desktop\\Programming\\C++ Projects\\OpenGL\\texture.png");
    if (!surface) {
        std::cout << "errror";
        return;
    }

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    int Mode = GL_RGB;

    if(surface->format->BytesPerPixel == 4){
        std::cout << "errror2";
        Mode = GL_RGBA;
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w,surface->h, 0, GL_RGB,GL_UNSIGNED_BYTE,surface->pixels);

    SDL_FreeSurface(surface);
}

```

How I rendered the image:

```
///TEXTURE
    glBindTexture(GL_TEXTURE_2D,texture);
    glEnable(GL_TEXTURE_2D);

    int X = 0;
    int Y = 0;
    int Width = 1;
    int Height = 1;

    glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex3f(X, Y, 0);
        glTexCoord2f(0, 1); glVertex3f(X + Width, Y, 0);
        glTexCoord2f(1, 1); glVertex3f(X + Width, Y + Height, 0);
        glTexCoord2f(1, 0); glVertex3f(X, Y + Height, 0);
    glEnd();
    glDisable(GL_TEXTURE_2D);

```

Ps. Yes I made the `GLuint texture` variable, it is static defined in the header file, oh and there are no errors it could not load or something.

# Answer
`glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w,surface->h, 0, GL_RGB,GL_UNSIGNED_BYTE,surface->pixels);`

See: https://www.opengl.org/sdk/docs/man3/xhtml/glTexImage2D.xml

You need to pass the `surface->format->BytesPerPixel` instead of `GL_RGBA` for the 3rd parameter.

Additionally, are you sure about the format? You can get it for sure with:

```
        switch (surface->format->BytesPerPixel)
        {
        case 4:
            if (surface->format->Rmask == 0x000000ff)
                Mode = GL_RGBA;
            else
                Mode = GL_BGRA;
            break;
        case 3:
            if (surface->format->Rmask == 0x000000ff)
                Mode = GL_RGB;
            else
                Mode = GL_BGR;
            break;
        default:
            std::cout << "Error, image is not truecolor." << std::endl;
            return;
        }

```

You would then call `glTexImage2D` like this:

```
glTexImage2D(GL_TEXTURE_2D, 0, surface->format->BytesPerPixel, surface->w,surface->h, 0, Mode,GL_UNSIGNED_BYTE,surface->pixels);

```
> 1 votes

# Answer
Try changing:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w,surface->h, 0, GL_RGB,GL_UNSIGNED_BYTE,surface->pixels);

```

To (if surface has alpha):

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w,surface->h, 0, GL_RGBA,GL_UNSIGNED_BYTE,surface->pixels);

```

Or (if surface doesn't have alpha):

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, surface->w,surface->h, 0, GL_RGB,GL_UNSIGNED_BYTE,surface->pixels);

```
> 0 votes

---
Tags: opengl, c++, textures, sdl
---


# Question
Title: What are the disadvantages of R-Trees in collision detection?
I was poking around in SQLite and discovered R-trees. A little digging revealed that R-trees are really just fancy AABB-trees.

Then I realize that the state of the art in collision detection (often a perf-limiting sub-system for physics simulation) is dynamic trees (simple AABB trees).

So this is indicating to me that we can produce more efficient physics with this as a drop-in replacement.

Here is a pretty convincing argument for R-trees from half a decade ago. To really distill it to the core, R-trees were developed for databases to optimize disk access where getting the right data into RAM is the happy place, and now we can recycle the technique to optimize memory access where keeping the right data in cache is the happy place.

Sadly it seems that this has not caught on. I wonder what the reasons are?

I also found no reference to this BVH method in my Real-Time Collision Detection (Ericson) text (though, that book is a bit older than 2010).

# Answer
> 1 votes
R-trees and AABB-trees are two names for the same thing, so it doesn't make any sense to say one has an advantage over another.

# Answer
> 1 votes
From what I can see, when implemented in 2 or 3 dimesions it's just another name for a hierarchical AABB / BVH setup as noted. Searching on "r-tree GIS" gives a lot of info, and being an inherently spatial field has much similarity to game dev (graphs, computational geometry etc.).

The point on which R-trees really win out over spatial/geo hashes and N-ary trees like binary trees, quadtrees and octrees is their neat fitting to arbitrary features with minimal wasted (search) space.

Re cache performance... Here's what I found on cache-oblivious R-trees:

> Memory layout. Even though our cache-oblivious R-tree is defined in terms of kd-nodes and line-based nodes **\[see fig. 1 in the linked paper\]**, it is simply a tree of bounded height with nodes of degree at most four. We need to specify how to lay this tree out in memory in order to obtain an efficient query algorithm. Unlike most previous cache-oblivious structures we do not use a Van Emde Boas layout, but simply lay the tree out in depth-first order: to lay-out a tree Tv rooted in a node v , we define an ordering of the children v1, v2 ... vc of v and lay out the tree such that v is followed by a recursive layout of the tree Tv1 rooted in v1, followed by a recursive layout of Tv2 , and so on.

After reading this, my deduction from Sebastian's vague notes on *his* approach is simply that the data layout is extremely compact and avoids pointers altogether in favour of some 8- or (probably) 16-bit IDs use to access nearby nodes with impunity, many of which will already be in L2 at query time. I was surprised; I really thought that something like a 3D Z-curve would have been used to increase locality of reference but no, apparently it's just brute compactness - as noted in quote. I've seen quadtree and octree implementations like this as well - e.g. the original NVidia SVO paper.

**Conclusion**

What's clear from Sebastian's notes is first eliminating all that pointer dereferencing that is typical in naively-implemented graph-like structures. Again, we've seen this in the SVO paper ref'ed above.

Secondly, pack what you can into the smallest space possible. 1MB L2 cache on the author's XBox360 which he talked about at GDC may not seem like a lot - if you're not using it efficiently. Actually, R-trees don't need to be very large to accomplish a great deal of acceleration.

---
Tags: collision-detection, algorithm, physics-engine, bounding-boxes, space-partitioning
---


title: Unity trigger timer

text:
# Question
Title: Unity trigger timer
So essentially I'm attempting to implement a "security" system by using an object with no mesh collider to act as an invisible trigger (stretched across a doorway or something) which sets off an audible alarm sound. The feature I want to add is for it not to keep restarting the alarm loop every time you touch the collider, as that just doesn't happen IRL. I've tried everything from countdown timers with Time.deltaTime, OnTriggerExit booleans even a Thread.Sleep hack which just froze the whole game engine up while the function executed. Is there a nice way to achieve this kind of behaviour? If not, what's a better way of implementing a similar system? It's fairly generic and could be applied to more than just alarm systems.

EDIT:

```
public class Sensor : MonoBehaviour
{

public AudioClip alertLoop;
float timer = 3f;
bool isTriggered = false;

public void OnTriggerEnter(Collider col)
{
    if(!isTriggered)
    {
        isTriggered = true;
        AudioManager.instance.PlayOneShot(alertLoop);
        print("Alarm Triggered!");
    }

}
public void OnTriggerExit(Collider col)
{
    timer -= Time.deltaTime;
    if(timer == 0)
    {
        isTriggered = false;
    }
}
}

```

That's my current attempt, I've deleted pretty much everything else I tried. Anything that required me to use the update function for the timer confused me, as the OnTriggerEnter is already MonoBehaviour, not a custom function.

# Answer
> 2 votes
How about you just use a System.Timers.Timer (https://msdn.microsoft.com/en-us/library/system.timers.timer.aspx)?

If not isTriggered, you start the Timer and have the elapsed time to your delay for the alarm (it uses milliseconds, so 3000?).

You can then set the elapsed event to reset your isTriggered back to false. Make sure you set the auto reset to false, so the Timer doesn't star again until the player triggers it (https://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx).

So, pseudo code

```
System.Timers.Timer timer;

public Sensor()
{
    timer = new System.Timers.Timer();
    timer.Interval = 3000;
    timer.AutoReset = false;
    timer.Enabled = false;
    timer.Elapsed += OnTimerTick;
}

private void OnTimerTick(object sender, System.Timers.ElapsedEventArgs e)
{
    isTriggered = false;
}

public void OnTriggerEnter(Collider col)
{
     if (!isTriggered) {
        isTriggered = true;
       AudioManager.instance.PlayOneShot(alertLoop);
        print("Alarm Triggered!");
        timer.Start();
     }
}

```

That's the general idea at least.

# Answer
> 1 votes
One problem I see is that your timer only decreases on OnTriggerExit. OnTriggerExit only happens as an object leaves the trigger area. On subsequent frames, OnTriggerExit isn't being called again, so the timer is no longer going down.

You want your timer to go down as long as it's not touching the trigger, right? So I'd put in another bool (call it, *touchingTrigger*, for example). Set it to true in OnTriggerEnter and false in OnTriggerExit.

Then have your countdown go down in Update. Something like this:

```
float cooldownTime = 3f;

public void Update()
{
    // alarm has been triggered, but we're no longer touching it?
    if (isTriggered && !touchingTrigger)
    {
        // countdown!
        timer -= Time.deltaTime;
        // time's up?
        if (timer <= 0)
        {
            isTriggered = false;
            timer = cooldownTime; // reset the timer; you could do this in OnTriggerEnter, instead
        }
    }
}

```

I hope that's helpful :)

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


# Question
Title: How do I set the Jump distance and height of my sprite in C#
I have been able to make my sprite jump for a platformer I am making in unity. I can't seem to be able to make him jump a certain height or distance though, every time he jumps it's like he's jumping on the moon, any suggestions? Here's my code:

```
using UnityEngine;
using System.Collections;

public class playerScript : MonoBehaviour {
    public bool grounded = true;
    public float jumpPower = 190;
    public float jumpSpeed = 100f;

private bool hasJumped = false;

// Use this for initialization
void Start () {
}

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

    if(!grounded && GetComponent<Rigidbody2D>().velocity.y == 0) {
        grounded = true;
    }
    if (Input.GetKey(KeyCode.Space) && grounded == true) {
        hasJumped = true;
    }   GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumpSpeed);
}

void FixedUpdate (){
    if(hasJumped){
        GetComponent<Rigidbody2D>().AddForce(transform.up*jumpPower);
        grounded = false;
        hasJumped = false;
    }
}

```

Any help would be greatly appreciated :)

# Answer
> 0 votes
By default `AddForce()` is applied over time, not in an instant (which is what you want). You can change that though by using the second parameter, such as...

`AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse)`

Another way that is probably more common, is to just set the `velocity` instead. This doesn't quite interact with the physics in the same way though, so it's up to you and what you need from the jumping behaviour.

You should try both.

If you want the player to jump a specific height or distance, then `velocity` is probably going to be easier for you. It's trickier to calculate how a force is going to affect your jump compared to using velocity.

Here is a question on the Unity site that talks about your specific issue.

---
Tags: unity, c#, platformer, jumping
---


title: How does server correct late input

text:
# Question
Title: How does server correct late input
Imagine the following scene: The height one player can reach on jumping depends on how much time the button for jumping is pressed. When the player jumps, the input is sent to the server and physics are updated.

Now, imagine that for some reason, one input packet is lost or due to lag it begins to arrive late. From the point of view of server, the player is not jumping anymore, and its character will start its fall. Every other client will receive this information and let the character fall. Then, a new packet arrives that corrects this problem. From the perspective of the player, the character is still jumping. Maybe, thanks to this extra input the character can reach a higher slope. But from the point of view of the server and rest of clients, it wont make it.

This could happen, but online games that i have played (except for long jumps and high lag) it doesnt happen. My question then is: How does the server handle this situation? It cannot wait forever for input, it must update physics and acknowledge other clients on what's going on.

# Answer
For this to be handled correctly you need to design your network protocol to do something called "continuous transitions". Client send's all time packages to the server with a order. This way the server has always the last state of the client, regardless of lag or lost packages.

Next step is you need to analyze the packages arrived.

Back to your jump example.

The user presses the jump button, and the client sends the following packages:

NKP = No Key Pressed JKP = Jump Key Pressed

\[NKP\] -\> \[JKP\] -\> \[JKP\] -\> \[JKP\] -\> \[JKP\] -\> \[JKP\] -\> \[NKP\] ...

Each package has a order.

So the server receives JKP and start's to update physics. Now the server doesn't receive packages of the client for any time.

Now u have 2 possibilities

* Sign the client as Disconnected
* Predict something

Most games are designed, that they predict something for a short period of time. So in our case, the server hasn't received the NKP package, so he predicts, the user is still jumping. This will happen for let's say 100ms. After that the server predicts that the user falls back to a default which in our case would be NKP.

After some time, the server receives again packages of the client. Corresponding to the correct order, he now knows the correct state of the last package of the Client send.

In our case still JKP. Now the server looks in his list and has 2 options:

* Am I still predicting? Then correct to the state of the Client
* Am I fallen back to default? Then correct the Client to the state of the Server

In the first case, what is happening, is exactly what people hate, when a lagging person enters any shooter game, that uses this prediction behavior. They start teleporting short distances.

In the other case, what is happening, is exactly what people see, when they cry for lagging server, because their characters start to flicker or teleport back.

You need to find the best prediction timings for your game design.
> 3 votes

---
Tags: physics, networking, jumping
---


# Question
Title: Increase the speed of my grid/render system?
I currently have a simple Minecraft-like grid system setup.
The game has a world -\> a world has multiple chunks -\> a chunk has blocks.
The world asks the chunks to render (if needed), but the render function in the chunk class takes up 97.4% of the application!
72.8% of that method is checking whether a block is at a specific location. This is needed, because I want to check if the block is surrounded by other blocks. If so the block is not visible, so it doesn't need to be rendered.

World.cpp

```
//97.4% of the application
void World::render()
{
    m_Renderer.prepare();
    for (int i = 0; i < CHUNKS_AMOUNT; i++) {
        m_Chunks[i]->render();
    }
}

//33.8% of the application
bool World::hasBlockAtLocation(const int& x, const int& y, const int& z)
{
    int chunkX = x / CHUNK_WIDTH;
    int chunkZ = z / CHUNK_WIDTH;

    Chunk* const& chunk = getChunk(chunkX, chunkZ);

    if (chunk) {

        int blockX = x - chunkX*CHUNK_WIDTH;
        int blockZ = z - chunkZ*CHUNK_WIDTH;

        if (chunk->hasBlockAtLocation(blockX, y, blockZ))
            return 1;
    }
    return 0;
}

```

Chunk.cpp

```
//97.4% of the application
void Chunk::render()
{
    int xMin = xLoc * CHUNK_WIDTH;
    int xMax = xLoc * CHUNK_WIDTH + CHUNK_WIDTH;

    int zMin = zLoc * CHUNK_WIDTH;
    int zMax = zLoc * CHUNK_WIDTH + CHUNK_WIDTH;

    if (xMax < m_Camera->getXMin()) return;
    if (xMin > m_Camera->getXMax()) return;

    if (zMax < m_Camera->getZMin()) return;
    if (zMin > m_Camera->getZMax()) return;

    for (int i = 0; i < CHUNK_SIZE; i++) {
        if (m_Blocks[i] != nullptr) {
            glm::vec3& pos = *m_Blocks[i]->getPosition();

            //If statement takes 72.6% of the application!
            if (!m_World->hasBlockAtLocation(pos.x - 1, pos.y, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x + 1, pos.y, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y - 1, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y + 1, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y, pos.z - 1) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y, pos.z + 1))

            {
                m_Renderer->addToRenderQueue(m_Blocks[i]);
            }
        }
    }
    m_Renderer->render();
}

//13.3% of the application
bool Chunk::hasBlockAtLocation(const int& x, const int& y, const int& z)
{
    if (x < 0 || y < 0 || z < 0) return 0;
    if (x >= CHUNK_WIDTH || y >= CHUNK_HEIGHT || z >= CHUNK_WIDTH) return 0;

    if (m_Blocks[CHUNK_WIDTH * CHUNK_WIDTH * y + CHUNK_WIDTH * z + x])
        return 1;
    return 0;
}

```

So how can I increase this speed? Because it's a real bottleneck and I ran out of ideas...
Any help would be appreciated!
If any additional information is required please ask.

# Answer
You're going about this in a way that will prevent you from being able to optimise that away. In other words, you're at a dead end, code-wise.

The way this is supposed to be done is not to render every individual block (not even just the surface blocks like you are trying to do) but rather to build a single large mesh manifold that collectively describes all air-exposed voxel surfaces for the current chunk.

This way you only do those expensive "surrounds" checks during mesh construction and when the mesh is updated, which is relatively infrequent. Then you render the entire chunk manifold every frame, without per-frame visibility checks.
> 6 votes

# Answer
There is one optimization you can still do, which is to create a cache of polygons that need to be rendered:

```
//only called when a (neighboring) chunk changes or is loaded
private void Chunk::buildRenderQueue(){
    int xMin = xLoc * CHUNK_WIDTH;
    int xMax = xLoc * CHUNK_WIDTH + CHUNK_WIDTH;

    int zMin = zLoc * CHUNK_WIDTH;
    int zMax = zLoc * CHUNK_WIDTH + CHUNK_WIDTH;

    if (xMax < m_Camera->getXMin()) return;
    if (xMin > m_Camera->getXMax()) return;

    if (zMax < m_Camera->getZMin()) return;
    if (zMin > m_Camera->getZMax()) return;

    for (int i = 0; i < CHUNK_SIZE; i++) {
        if (m_Blocks[i] != nullptr) {
            glm::vec3& pos = *m_Blocks[i]->getPosition();

            //If statement takes 72.6% of the application!
            if (!m_World->hasBlockAtLocation(pos.x - 1, pos.y, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x + 1, pos.y, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y - 1, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y + 1, pos.z) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y, pos.z - 1) ||
                !m_World->hasBlockAtLocation(pos.x, pos.y, pos.z + 1))

            {
                //push into vector<Block*> as cache
                m_renderableBlocks->push_back(&m_Blocks[i]);
            }
        }
    }
}

```

and rendering becomes the simple:

```
void Chunk::render()
{
    for(auto it = m_renderableBlocks.begin(); it != m_renderableBlocks.end(); ++it){
        //get blocks to render from cache
        m_Renderer.addToRenderQueue(*(*it));
    }
    m_Renderer->render();
}

```

Beyond that if your chunk size is a power of 2 then the optimizer can change the math in `World::hasBlockAtLocation` and `Chunk::hasBlockAtLocation` by bit operations. You can do that explicitly if you don't trust the optimizer to catch it.
> 2 votes

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


# Question
Title: Testers for multiplayer game? Where to find them?
I am indie game developer and we created multiplayer and realtime game IQ Wars (www.iqwars.net). We made Windows/Mac/Linux Beta version of our game public and were hoping to find some beta testers to see if it works without problems with 50+ or 100+ players playing simultaneously.

So basically I was thinking about some kind of page or service were indie game developers publish their games so gamers can play and give (or not) some feedback. Is there any place where I can put the game (it's Setup.exe) or link to the game? Or maybe my understanding is wrong and I have to do it some other way?

Would be very appreciated for help.

# Answer
> 2 votes
I could list some websites where you could announce your game, but the process to find non-paying players is pretty much the same as the one to find paying players. That means I would just be duplicating the answers to "How can I promote my game?" and similar questions.

The problem with public beta tests is that they easily escalate to a PR event for the game, which can be a mistake if the product is not yet polished enough for the public. A professional studio would pay beta testers and have them sign an NDA which forbids them from talking about the game and all of its bugs and flaws, but I have the impression that this is outside of your budget constraints.

When it is just about stress testing your server technology, you might consider writing a headless bot to play your game and start a few hundred instances of that bot. The advantage of this is that you can easily scale the load accurately and also repeat your test with minimal organization overhead when you want to find out how some minor changes affect the overall performance. When you would like to simulate real-world network performance as well, you might want to take a look at the question "How can I simulate a bad internet connection for testing purposes?".

It can sometimes be hard to accurately simulate player behavior, because players sometimes behave in ways which are hard to predict for the developer which might result in far different server load than expected. That's why it is a good idea to have a small circle of testers you trust personally whose behavior you can use as a basis for your bots behavior.

---
Tags: multiplayer, testing, playtesting
---


# Question
Title: 2015 android multiplayer server based Implementation
There are a lot of old posts about multiplayer implementations on SE, so i'm looking for an up-to-date answer. What is the best server-client implementation of real-time multiplayer now? I have an Amazon MYSQL Server hosted by digitalOcean, I've made a REST web service that communicates with the Server and Android app, and I have my Android app running receiving and sending data.

I want to add a multiplayer minigame to what I have right now where 2 players would see the same screen and one user would receive location data (which i'm already storing in the server and sending to all devices with the app) from the other and would have an interface to interact with the data they're receiving (like building towers around the location and deploying units). The computer AI would need to be synced between both devices.

The matches would last maybe 3 minutes tops and the location data would have to be streamed constantly as well as the interaction from the other user. The computer AI would be streamed to both.

I've done a lot of research on the topic, and most of my experience was from a bluetooth P2P game I created in 2011 using sockets. So what are the most common implementations today? What are the most common libraries? I'm currently using Android Studio for the app and Notepad++ for the PHP webservice.

**EDIT:** I'm fine with answers promoting their own products, but explain how your product is better than Google's Game Services (which appears to be the best choice right now). I'm really looking for a way to implement the multiplayer with the server I'm already using.

# Answer
> 1 votes
You could use a pub/sub messaging platform like Realtime (http://framework.realtime.co/messaging). Whenever you need to update the position of a player simply publish the location to a pub/sub channel that the other players are subscribing. Simple as that.

*\** I am the CTO for Realtime Framework at Realtime.co \***

---
Tags: android, multiplayer, server, client-server, realtime
---


title: Making games In Python

text:
# Question
Title: Making games In Python
I'm a beginner at making games, and my eBook that I learnt Python from just made a 2D game and simple game like snake in Nokia because I want to know more Python in correlation with game development.

Can someone tell and explain to me what the Python language can do to make a game?

# Answer
> 3 votes
If you are using Python it is almost impossible to create a game with textures, like snake without using libraries. You should use the Pygame library if you want to create games like that in the Python language. Pygame offers many things like: Draw figures, render images to the screen, settings fps etc. I hope this answered your question, sorry for bad English.

This is an example of a game written in Pygame and Python: https://libregamewiki.org/Eskimo-run

**Conclusion:**

*The Python language itself can not do much for creating a game, you have to use libraries for that.*

# Answer
> 1 votes
Usually programming languages do not offer a lot for making games natively. Some languages are just used commonly for creating game engines, which then in turn can be scripted with other languages.

I recommend you to have a look at the Blender Game Engine which uses Python as scripting languages, and offers a lot of functionality for access with Python through its API. The engine itself is not quite the most modern game engine, but it has by far enough features for someone who wants to use Python for developing games on a non- or semiprofessional level (for example for small indie games).

Note that every game engine has its functionality implemented in a low level language (e.g. for physics, graphics, ...), which is often not the same as the language used for the game logic.

For very simple games you can just use a library for drawing 2d graphics instead of a game engine.

# Answer
> -4 votes
\*Python. Most games are developed in a language like C or JavaScript; it is uncommon to see a modern game created in Python. If you want to create a game I suggest downloading a program like Unity, learn some basic JS or C#, and create a simple 2D platformer, there are tons of tutorials on the net for them! Also, if you don't have enough money for Unity Pro, try the Unreal Engine.

---
Tags: python
---


# Question
Title: How to animate a character with props in Blender and then have these props modifiable in Unity3D?
I have created a fully rigged and fully animated humanoid model in Blender with rigging based on Unity's Mecanim standards for humanoid models.

Now, I want to create custom animation for it in Blender where it's attacking with a sword. I also want to create a sheathing/unsheathing animation.

Also, once the model is imported into Unity, I want to be able to replace the sword and the sheathe props with another model, but still be able to retain the animation.

**What's the best way of doing this?**

* Do I need to modify the rig to include the sword and sheathe meshes? Will adding new bones break my model's compatibility with Mecanim?
* If I'm going to add new bones, then that means I will have to include the mesh data of the sword and sheathe to the model, but if that's the case, then how can I replace the sword and sheathe models in Unity if the sword and sheathe are part of the character model?
* If the sword and sheathe aren't going to be part of the character armature, then how can I create their animations in Blender which Unity will use?

Fig. 1. The model and its armature.

# Answer
> 2 votes
Parent an empty object to the hand bone and use it for swapping and holding props. Whenever you pick up another object, create it at the empty object's position and parent it to it.

This way you can keep your animations you did with Blender and just replace the props in Unity.

# Answer
> 0 votes
Could you not have the sheath attached to the hip bone in unity? and the sword attached to the hand?

That way they could follow the motions and could still be swappable. If you wanted a custom animation for sheathing or something you could have an animation play on the sheath when or something like that.

---
Tags: unity, 3d, animation, blender, rigging
---


title: Drawing collision detection boxes

text:
# Question
Title: Drawing collision detection boxes
So I have a `TileSprite` class that makes a `TileSprite`object with a collision box in it named `bCollisionRect`:

```
public TileSprite(Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
        : base (textureImage, position, frameSize, currentFrame)
{
    bCollisionRect = new Rectangle((int)position.X + collisionOffSet, (int)position.Y + collisionOffSet, frameSize.X - (collisionOffSet * 2), frameSize.Y - (collisionOffSet * 2));
}

```

But when I try to draw the collision boxes (to test collision detection), it doesn't draw the box. I tried using this:

```
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    // This is what I tried:
    spriteBatch.Draw(textureImage, bCollisionRect, Color.White);

    // base.Draw draws the texture (.Draw method from another abstract class)
    base.Draw(gameTime, spriteBatch);
}

```

I use this line of code in another class to draw my tiles (pure for testing!):

```
tilename.Draw(gameTime, spriteBatch);

```

# Answer
Code to create a blank texture at runtime (after discussing with you via comments above):

```
Texture2D blankTexture = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
Color[] color = new Color[1];
color[0] = Color.White;
blankTexture.SetData(color);

```

Then your draw call... specify a color if you want to tint it:

```
spriteBatch.Draw(blankTexture, bCollisionRect, Color.Red);

```
> 3 votes

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


# Question
Title: top down game - checking, drawing enemy's line of sight area with obstacles
Examples of what i'm going to need:

I'm using cocos2d to draw a CCTMXTiledMap, on those tiles i'll have to draw the LOS cone.

How would i test if the player is within that cone, taking obstacles into account? How would i draw the line of sight area on the map tiles, again taking obstacles into account, like in the examples above?

This is a re-post of a question i've put on stackoverflow.

# Answer
There's an article on GDNet about walls and shadows in 2D; the technique can be applied to visibility determination as well. Additionally there this old-school post on 2D visibility, this post on StackOverflow and a variety of other resources online you can find via Google.

Once you have a logical understanding of the visibility region for an agent in your game, you can convert that to a visual one for display (you can and should keep these distinct, so you could render a smooth cone even if your algorithm is working with tiles, for example).

One way to do that is with a stencil buffer -- you render your normal scene, and write to the stencil buffer every time you draw an obstacle, then render your visibility cone with an appropriate stencil test enable. Unfortunate cocos2d may not support the requisite functionality for you to do this (but that linked thread has some notes on using texture combiners to simulate the effect).

An alternative, very crude, solution if your game is more like the second screenshot you posted (top-down) is to render the floors, then render the visibility regions, then render obstacles. However this will not give you the effect like in the Commandos screenshot where you can see that the tree (for example) are blocking the visibility.

The GDNet article discusses a rendering technique as well, but it's triangle-based and will need some adjustment to remove the jagged edges it produces.
> 6 votes

# Answer
First, most of these sensors system don't use "triangles", but an opening angle and a distance at which the NPC can detect the player. Doing this kind of detection is pretty easy, determine the distance and angle between the heading of the NPC and the player's position. Using these two values you can test if the player is within the range of the sensor, if it is you can then apply the more costly check, a ray cast that tests if an obstacle is between both characters. If the raycast doesn't hit anything, you see your target, otherwise you don't see it.

As for rendering... you either follow the same strategy that is used for projected shadows or you could render a "triangle fan" representing your sensor after rendering the floor and before rendering the obstacles and actors, allowing you to see the sensor on top of the floor but below everything else. This will not be as good looking as the projected sensors and will not take obstacles into account (removing parts of the sensors when hitting an obstacle) but should be faster to implement and have a lower processing cost.
> 1 votes

# Answer
The project I asked this question for (2 years ago) didn't progress, but I got to tackle this issue again. I actually implemented the line of sight thing treating it as a red light. This is the tutorial that helped finally understand how to get it done: http://archive.gamedev.net/archive/reference/programming/features/2dsoftshadow/

I made a CCNode subclass that overrides the 'draw' method and put the rendering code in there, the class also received an array of shadow caster classes that had convex hull data...
> 1 votes

# Answer
I used an A\* search algorithm. If your game is rendering tiles, then use this to determine if the tiles are solid or not. It creates a path of "passable" tiles for the enemy to follow the player around walls, in the shortest distance. It could easily be adapted for detecting if the surrounding tiles are solid or not (see through or not). Basically, you need something like the following:

```
public List<Tile> visibleTiles(Entity e){
    List<Tile> visibleTiles = new ArrayList<Tile>();
    Tile at = null;
    for (int i = 0; i > 9; i++){
        int x = current.tile.getX();
        int y = current.tile.getY();
        int xi = (i % 3) - 1;
        int yi = (i / 3) - 1;
        Tile at = getTile(x + xi, y + yi);
        if (at.isSolid()){
            continue;
        } else {
            visibleTiles.add(at);
        }
    }
    return visibleTiles;
}

```

This will search the tiles surrounding the entity passed through, and return a list of tiles that are "visible". All you need to do is update them so they appear to be lit up. Hope this is helpful. Apologies it is in Java, it is taken from my game which is Java. Hope you get the idea though
> -1 votes

---
Tags: graphics, mathematics, algorithm, objective-c, cocos2d
---


title: Acceleration problems

text:
# Question
Title: Acceleration problems
Im trying to make a car game, but i cannot get the acceleration code right. With this code:

```
        if(gas){
        speed += 3;
    }else if(break_ && !(speed < 6)){
        speed -= 3;
    }else if(!break_ && !gas && !(speed < 6)){
        speed -= 0.3;
    }else{
        speed = 6;
    }

```

it is up on 1000 within 5 secounds. I tried multiplying it with smaller numbers, but it still doesnt work(in fact it got worse). So, how can this be improved so it has reasonable parameters? Asof the maximum speed, i can implement that on my own.

# Answer
> 3 votes
Try adding in a Velocity variable. But more importantly, you need to keep track of your deltaTime, which is the time that elapsed since your last frame.

More than likely the framework you are using has this, if not you will need to implement one.

```
float Velocity;
float Speed = 3;     //Your speed could vary here

if(gas){
   Velocity += Speed * deltaTime;     //when gas is pressed, speed up
}
else if (brake && (Velocity > 6)) {
   Velocity -= Speed * deltaTime;      //When brakes are pressed, slow down
}
else if(!brake && !gas && (Velocity > 6)){
   Velocity -= Speed * deltaTime;     //friction should be a different value than Speed
}
else {
    Velocity = 6;
}

//Update the position
Position.Axis += Velocity;

```

---
Tags: java, physics, movement
---


title: Shaperenderer circle line width

text:
# Question
Title: Shaperenderer circle line width
Is there any way to increase the width of the line that makes up the shaperenderers circle?

```
shape.begin(ShapeRenderer.ShapeType.Line);
shape.setProjectionMatrix(batch.getProjectionMatrix());
shape.setColor(1, 0.53f, 0.53f, 1);

shape.circle(nest.getCenter().x, nest.getCenter().y, radius, 500);

```

If not, is there any other approach that can give a similar effect?

# Answer
Set the OpenGL line width.

```
Gdx.gl.glLineWidth(32); // Or whatever thickness you need

// Then render the lines or circles as per what you're currently doing
shape.begin(ShapeRenderer.ShapeType.Line);
shape.setProjectionMatrix(batch.getProjectionMatrix());
shape.setColor(1, 0.53f, 0.53f, 1);

shape.circle(nest.getCenter().x, nest.getCenter().y, radius, 500);

```
> 8 votes

---
Tags: libgdx
---


# Question
Title: Counting multiple touches using Cocos2dx 3.2
I'm trying to count the number of active touches in screen in order to perform an an action in case that there are two touches:

```
auto jumpListener = EventListenerTouchAllAtOnce::create();
    jumpListener->onTouchesBegan = [=](const std::vector<Touch*>& touches, Event* event)
    {
        CCLOG("Multi-touch detected %d", touches.size());
        if(touches.size() == 2)
        {
            this->_player->jump();
        }

    };

```

But even if I'm touching with two fingers, I get that only 1 touch has been made, any suggestions?

# Answer
> 0 votes
Most simple and reliable is to use the singular event "ccTouchBegan/ccTouchEnded" events, instead of the multiple one "ccTouchesBegan/ccTouchesEnded".

Also, make sure you do this in a class that inherits from Layer/LayerColor, otherwise it won't work.

```
virtual bool ccTouchBegan(cocos2d::Touch *pTouch, cocos2d::Event *pEvent);

bool MySceneLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *)
{
    // use location with 'pTouch->getLocationInView()'
    return true;
}

```

# Answer
> 0 votes
```
//.h
int touchCount = 0;

//.cpp
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
listener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded, this);

void HelloWorld::onTouchesBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
touchCount++;
CCLOG("Multi-touch detected %d", touchCount);

if (touchCount == 2){

CCLOG("two finger are on the screen");

  }

}

void HelloWorld::onTouchesEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
touchCount--;
}

```

touchCount will keep track of how many touches are on the screen and you can do whatever you want with it.

# Answer
> -1 votes
```
auto jumpListener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);

void HelloWorld::onTouchesBegan(const std::vector<cocos2d::Touch *> &touches, cocos2d::Event * event)
{
CCLOG("MULTI TOUCH BEGAN");
}

```

Try this

---
Tags: android, cocos2d-x, multitouch
---


# Question
Title: One big Instance or One instance for every moving entity?
I am creating a multiplayer JavaScript game with a PHP central server. Each user will be able to move around in a 3D world, with other users and NPCs. These NPCs will be controlled by the central server in PHP. **Should I create one big world simulation PHP file that simulates all the NPCs in turn or a smaller controller that will be ran for each active NPC (on its own thread)?** Each NPC has its own row on an SQL table and will be retrieved by the client to determine its position, state, etc.

*Note: This is my first time creating a networked game, so if there is anything that I can do better, or a unique way of doing things that could work for this, feel free to comment*

# Answer
While I don't have much experience creating games with php/js I'd say that there are a few things you should consider.

First thing that popped out to me is that you wanted to save positions in an SQL database - this seems like a terrible idea. It would be incredibly slow, consider how many times a second a game loop would run, times the number of entities you have and you have an insane amount of sql queries and no real hope of performance.

Second, you'll have to consider the overhead of opening a new thread for each entity - likely, it will be faster to have one thread taking care of all the entities. Besides, what would be the upside of parallell updating compared to procedural?

But again, I'm no expert in php.
> 2 votes

# Answer
my first instinct when seeing this is that you are using all of the wrong technology. that is the big optimisation win to be had.

i am a bit old school so maybe these days you can get away with it, but networking games were never historically made in these ways. even TCP is considered too much overhead (it introduces a lot of lag for dropped packets, a lot of the time, e.g. with positions, you don't care so much because you get another update very quickly).

if you want to progress towards doing this professionally you should use C++ or a similar low level language with access to BSD sockets etc. although you can do the same with php for the server, i don't think you can with javascript from a browser (i am not expert though).

there is some excellent information on these classical approaches here:

http://gafferongames.com/networking-for-game-programmers/ http://beej.us/guide/bgnet/

i doubt you will ever get decent performance for these sorts of things without dropping to this level... and 'being able to send things over udp with sockets' is about what i would consider 'the basics'. so i have no idea what you read which gave you the impression otherwise.
> 1 votes

---
Tags: javascript, networking, optimization, php
---


title: seamless stereographic projection

text:
# Question
Title: seamless stereographic projection
i have been struggling with this problem on and off for a few years now - making a seamless stereographic projection texture mapping on a sphere where the two halves of the sphere use the projection onto planes touching the poles as appropriate.

intuitively it seems possible provided that the right data is in the texture and i've taken many approaches, but i always get a nasty seam around the equator.

i've tried smearing the colours out along the path i imagine the interpolator would take to try and get between the distant texels, but this still leaves a seam (though it makes it less objectionable).

i thought it might be to do with mipmapping, but forcing the lod in a shader does nothing.

i've tried overriding the derivatives (although this isn't always possible) and that doesn't fix it either (and i wouldn't expect it to because forcing the lod didn't).

i figured i might be able to get around this by wasting lots of texture space and making a sort of tiling texture that contains flipped versions of the projection at the top and bottom so that the interpolation path passes through something sensible-ish...

i've also tried limiting the interpolation paths along the x-axis/u-axis in the texture, since it also naively seems like this should have the right colours for the interpolator to run over inbetween the two halves.

i've also tried the very simple thing of multiplying by 0.9999 to remove rounding errors, as well as clamping the samples onto the circles.

i should point out that the same problem occurs with any texture addressing mode (wrap, mirror, clamp) and even if i manually clamp the texture coordinates in the shader.

also that i have debugged the uvs by putting them out through the shader and there is only the expected sharp seam in them:

none of this stuff properly gets rid of the seam, and its exceptionally objectionable compared to the usual kinds of seams.

does anyone have any other ideas for how to approach this? i can't find anything online about this. perhaps my approach is too novel...

now i know i can cheat, expand the projection and blend between the two across the equator, but i'd really, really, like to not double the number of texture samplings i'm doing per pixel for this.

(also i can avoid the problem with a cylindrical mapping, but thats no fun at all :D)

thanks in advance.

# Answer
turns out that my understanding of GLSL was at fault, and my theory about miplevels due to it lerping across large swathes of texture was correct.

the third parameter for texture2D is a bias for the mip level, not the lod, and i had assumed incorrectly it was the lod.

unfortunately texture2DLod is missing under my driver (and others) but i've been able to come up with a little hack using that bias parameter to remove the problem in a visually acceptable way.

hopefully this information proves useful to someone else in future.
> 1 votes

---
Tags: rendering, projection, planet
---


# Question
Title: Is index drawing faster than non-index drawing
I need to draw a lot of polygons consisting of 6 vertices's (two triangles).

Without any texture coordinates, normals etc., both approaches result in 72 bytes. In the future I would definitely also need texture coordinates and normals, which would make index drawing consume less memory. Not a lot though.

So my question is: For VAOs with few vertex overlaps, which approach is faster? I don't care about the extra memory consumed by non-index drawing, only speed.

**Edit:** To make it clear.

Non-index approach:

```
float[18] vertices = {
//Triangle 1
1,1,0,
1,0,0,
0,0,0,

//Triangle 2
1,0,0,
0,1,0,
0,0,0,
};

```

Index approach:

```
float[12] vertices = {
1,1,0,
1,0,0,
0,0,0,
0,1,0,
};

int[6] indices = {
//Triangle 1
0,1,2,

//Triangle 2
0,3,2
};

```

# Answer
> 4 votes
I try to answer the question. I think that you should go with indices, for few reasons:

1) In any case, indexing is free operation at GPU side, you don't take penalties there. (added) Of course, indices are random access operations, and can hurt GPU memory cache performance.

2) Indexing may allow GPU vertex cache to make those few optimizations for overlapping vertices.

3) Smaller memory footprint at GPU side many times means better performance, as memory bandwidth is one of the bottlenecks, and because many times extracting operations (e.g. 10\_10\_10\_2 -\> 4 x float) are non-cost.

The speed difference is probably not noticeable if there is not much overlapping vertices where you may get speed improvement. But I really don't have any hard facts to support my opinion (to go with indices).

---

Look also this:

https://stackoverflow.com/questions/17503787/buffers-indexed-or-direct-interlaced-or-separate

# Answer
> 1 votes
If the positions are always the same you can even do without any buffers by storing the array in the shader and using `gl_VertexID` to select the vertex in the vertex shader.

```
#version 330 core

const vec3 data[4] = vec3[]
(
//Triangle 1
vec3(1,1,0),
vec3(1,0,0),
vec3(0,0,0),

//Triangle 2
vec3(1,0,0),
vec3(0,1,0),
vec3(0,0,0)
);

void main()
{
  gl_Position = vec4( data[ gl_VertexID ], 1.0);
}

```

# Answer
> 0 votes
as with all performance things, don't guess, profile it to find out.

it will vary depending on the hardware and very many complicated factors. measuring it by profiling will automagically consider all of these things for you without you needing to know anything about them.

---
Tags: opengl, rendering, vbo, vao
---


# Question
Title: Replace black color by transparent color XNA
I'm actually trying to replace black color of my texture by a transparent one.

How can I do to remove the black pixels, should I use a AlphaTestEffect, or can I use the BasicEffect?

Thank you.

# Answer
If your image background is already transparent, then you may need to enable alpha blending on the basic effect if its not already enabled.

If the textures background is not transparent, the easiest way would be to edit the texture outside of XNA, and replace the black background with a transparent one. If you have Gimp, Photoshop or Paint.NET installed, this is rather trivial.

If you are looking for a way to do this in code, one way will require you to use a custom shader in order to so so. My answer here describes how to do something similar with a different colour, and I've also copied across the code as well in case anything happens to that answer.

```
// WARNING! UNTESTED CODE FOLLOWS
void SpriteVertexShader(inout float4 color : COLOR0, inout float2 texCoord : TEXCOORD0,
                        inout float4 position : POSITION0)
{
    if (color == float4(0, 0, 0, 1)
        color = float4(0, 0, 0, 0)
}

```

Essentially what this psuedo shader code is meant to do is replace any black coloured pixel with a transparently one. If you are not familiar with custom shaders, or not comfortable using them, something similar can be done in C# code, but is best done when you load the texture, as it is not something you would want to run every draw call.
> 3 votes

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


title: Libgdx : surround sound

text:
# Question
Title: Libgdx : surround sound
in libgdx there is a lot of audio classes but i haven't seem to of found anything relating to balancing sound in one speaker and or the other to get surround sound

say you check if an object is more to the left or to the right of the screen, is there anything or any classes relating to something like set speaker balance by percent like 50% would be default audio on the left and right side equally where you can change the balance, 50 - 100 percent is right side, 0 - 50 percent would be left

if this isn't possible, would it be possible two have 2 different audios (Left Explosion sound & Right Explosion sound) with each being 100 percent on the left or right side then change the volume percent of either one to get a surround sound feel?

# Answer
You can use the `pan` parameter on `Sound`s `play` method to balance a sound.

**-1** is full left, **1** is full right and **0** is center.

```
// last parameter is pan and this will play the sound with a full left pan
mySound.play(1f, 1f, -1);

```

There is also a `setPan` method which you can use to update the pan of an already playing `Sound`.
> 3 votes

---
Tags: java, libgdx, sound, audio
---


title: Failed to build WebGL

text:
# Question
Title: Failed to build WebGL
I'm using unity 5.2.2, and cannot build my project to WebGL. I have 3 DLLs in my project, all of which are built using .Net 3.5 and below. (`System.Drawing.dll, Newtonsoft.Json`, and a custom version of Libnoise-unity)

Here is the error I'm getting:

> `Failed running C:\Program Files\Unity\Editor\Data\Tools/UnusedByteCodeStripper2/UnusedBytecodeStripper2.exe -out "D:\Documents\UnityProjects\WarWorldInfinity\Temp\StagingArea\Data\Managed\tempStrip" -l none -c link -x "C:\Program Files\Unity\Editor\Data\Tools\native_link.xml" -f "C:\Program Files\Unity\Editor\Data\il2cpp\LinkerDescriptors" -x "D:\Documents\UnityProjects\WarWorldInfinity/Temp/StagingArea/Data/methods_pointedto_by_uievents.xml" -d "D:\Documents\UnityProjects\WarWorldInfinity\Temp\StagingArea\Data\Managed" -a "D:\Documents\UnityProjects\WarWorldInfinity\Temp\StagingArea\Data\Managed\Assembly-CSharp.dll" -a "D:\Documents\UnityProjects\WarWorldInfinity\Temp\StagingArea\Data\Managed\UnityEngine.UI.dll"`
>
> `stdout: Fatal error in Mono CIL Linker System.NullReferenceException: Object reference not set to an instance of an object at UnusedBytecodeStripper2.ResolveFromPreserveAttribute.IsPreserveAttribute (Mono.Cecil.TypeReference arg) [0x00000] in :0 at UnusedBytecodeStripper2.ResolveFromPreserveAttribute.m_0 (Mono.Cecil.CustomAttribute c) [0x00000] in :0 at System.Linq.Enumerable.Any[CustomAttribute] (IEnumerable`1 source, System.Func`2 predicate) [0x00000] in :0 at UnusedBytecodeStripper2.ResolveFromPreserveAttribute.HasPreserveAttribute (ICustomAttributeProvider type) [0x00000] in :0 at System.Linq.Enumerable+c_Iterator1E`1\[Mono.Cecil.PropertyDefinition\].MoveNext () \[0x00000\] in :0 at UnusedBytecodeStripper2.ResolveStep.MarkProperties (Mono.Linker.LinkContext context, IEnumerable`1 properties) [0x00000] in :0 at UnusedBytecodeStripper2.ResolveFromPreserveAttribute.ProcessType (Mono.Cecil.TypeDefinition type, Mono.Linker.LinkContext context, Boolean assemblyHasPreserveAttribute) [0x00000] in :0 at UnusedBytecodeStripper2.ResolveFromPreserveAttribute.Process (Mono.Linker.LinkContext context) [0x00000] in :0 at Mono.Linker.Pipeline.Process (Mono.Linker.LinkContext context) [0x00000] in :0 at Mono.Linker.Driver.Run () [0x00000] in :0 at Mono.Linker.Driver.RunDriver (Mono.Linker.Driver driver) [0x00000] in :0 stderr:`
>
> `UnityEngine.Debug:LogError(Object) UnityEditorInternal.Runner:RunManagedProgram(String, String, String, CompilerOutputParserBase) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:66) UnityEditorInternal.AssemblyStripper:RunAssemblyLinker(IEnumerable`1, String&, String&, String, String) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:192) UnityEditorInternal.AssemblyStripper:StripAssembliesTo(String, String, String&, String&, String, String, IEnumerable`1) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:185) UnityEditorInternal.AssemblyStripper:Strip(String, String, String&, String&, String, String, IEnumerable`1) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:136) UnityEditorInternal.AssemblyStripper:Strip(String\[\], String\[\], String, String, String&, String&, String, String, IEnumerable`1) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:121) UnityEditorInternal.IL2CPPBuilder:RunAssemblyStripper(IEnumerable, String, String[], String[], String) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:444) UnityEditorInternal.IL2CPPBuilder:StripAssemblies(IEnumerable`1, String) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:417) UnityEditorInternal.IL2CPPBuilder:Run() (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:291) UnityEditorInternal.IL2CPPUtils:RunIl2Cpp(String, IIl2CppPlatformProvider, Action`1, RuntimeClassRegistry) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:218) UnityEditor.PostprocessBuildPlayer:Postprocess(BuildTarget, String, String, String, Int32, Int32, String, String, BuildOptions, RuntimeClassRegistry)`

# Answer
It was the System.Drawing reference in Libnoise that was causing it to fail.
> 0 votes

# Answer
More than likely you are trying to build with a featureset that is not yet compatible with WebGL builds.

For example, if you try to add a Networking component and build to WebGL, you will get that same error about UnusedByteCodeStripper2.
> 1 votes

---
Tags: unity
---


title: Peer to Peer world download

text:
# Question
Title: Peer to Peer world download
I am creating a multiplayer JavaScript game with a PHP central server. Each user will be able to move around in a 3D world, with other users and NPCs. It came to my attention that SQL is not going to handle all the requests being made in a reasonable time. So I cut down on SQL requests being made as often, using RAM when I can, but each user that logs into my world, or switches worlds requires a lot of data to be filtered from the server (So the client does not get any information it should not have, and so I don't have to distribute the entire world for every logon) and then uploaded to the client. So I had an idea: **What if I can get the World data from the users near to the player(In the 3D world), like a BitTorrent? How to resolve syncing issues? What are my options to prevent Hacking?** My ideas were: check with more than one user, get a hash from a server(will probably have syncing problems), have bots who request worlds from clients: then checks with server to see if they are being honest, how ever they all seem to have their problems, and am not sure which one(s) I should incorporate, or if there is a better way I could get correct world data from peers, with minimal server interaction.

*Note: Peer to Peer is only used to get the world, block/world updates are still handled between the server and each client*

# Answer
For peer-to-peer communication between web browsers, WebRTC is likely the best option available. But keep in mind that it is not universally supported yet.

Also keep in mind that while you might save traffic on the server this way, the perceived performance for your clients might be far worse, because consumer-grade internet connections will likely have far worse peering than your server in a datacenter. But even when the client has a good connection, sending data to a client first and then from that client to another client will almost always have a higher latency than sending it to the other client directly. So I would only recommend this technique for large bulk-downloads, not for time-critical frame-by-frame updates.

To prevent players from spreading misinformation, you could use public/private key cryptography.

* On login, give each player the server's public key directly from the server.
* When the server sends a chunk of data to a player, have the server sign it with their private key.
* When a client relays that chunk to another player, include the signature from the server.
* Have the receiving client validate the signature of the server with the server's public key before you trust it.
> 5 votes

---
Tags: javascript, networking, optimization, php, peer-to-peer
---


title: Collision detection with moving objects

text:
# Question
Title: Collision detection with moving objects
I searched a lot about this problem. I found many answers here in Stack Exchange but none of them really answers when positions for objects get updated.

For a game with fixed size map and that has all the time:

* 200+ moving objects with different sizes (bullets, players, NPCs, etc.)
* 100+ static objects with different sizes (obstacles, health packs, etc.)

I am looking for an efficient way to do collision detection. Here is the pseudo code:

```
in each game loop (15 ms):
   collect movement commands and apply force on objects of those commands
   loop with very small physics time steps (0.1 ms):
      for object in movingObjects:
         get objects that might collide with current object   // --> 1
         check if any collision occurs
      for object in movingObjects:
         update position of object (based on command collected) // --> 2

```

So:

1. I get the objects that might collide with given object. It is done using a data structure like quadtree or spatial hashing grid (or something else that makes more sense).
2. Object's position is updated. Now, how do I inform the data structure that this object's position is updated? I don't want to remove and insert. That is not efficient at all.

I feel like quad tree and spatial hash implementations all over the internet are avoiding this problem.

I would also appreciate if you tell me my pseudo code above is problematic. I have the feeling this uses too much CPU.

# Answer
> 1 votes
If you need further optimisation, consider dynamic spatial hashing if you have heterogeneous spatial spaces, e.g. one grid has 30 objects and many others less than 5. Segregate overpopulated grid spaces into a new spatial hash grid.

Also, implement a probabilistic line collision detection. Mark the chage in distance between two frames. If distance is increasing, flag as "ignore". Only check again probabilistic collision detection if speed has changed.

Set speed vector to 0 and flag as static if object is moving minimalist, e.g. less than abs(0.0001). Don't check, of course, collision between two static objects. Don't update position of static flagged objects.

Use an preprocessed tables for squarerot distance calculations or use square distances instead of directly using square roots which can speed up your algorithm by up to 20%. You can do the same for trigonometric calculations.

That's all what I could think of. I get good performance of 20000 objects with my implementations. Surely you can squeeze out even more, e.g. line of flight probabilistic collision, update collision detection every 2nd frame for less relevant objects or objects that are not being rendered.

# Answer
> 1 votes
First, looking just at the code you might want consider the timings. Your main game loop is running every 15ms, fine (approx 60 fps). If you are actually running your inner physics at 0.1ms intervals inside that 15ms outer loop then thats 150 physics updates per frame - thats way to much.

I normally run my physics at 60fps but decoupled from the frame rate. Read this for more info. If your doing that to fix tunneling, there are other solutions.

Regarding the broad-phase algorithm there are many to choose from, but you need to pick a suitable one. As you point out, many have relatively high cost to maintain lots of dynamic objects. Other factors for choosing include:

* How big your world is
* How fast and clustered the game objects are
* How large the objects are

With the numbers you talk about above I'd either go for a regular grid or sweep and prune. They are both relatively simple to update each frame. For a regular grid, you mostly just need to clear each grid cell, and re-hash all the game objects each frame. Sweep and Prune can be even easier, you just need to maintain a sorted list in 1 dimension, its pretty good for long linear levels (2d Platformers etc).

If your really interested, I suggest you read this, a pretty detailed comparison of various algorithms in different use cases. http://0fps.net/category/programming/collision-detection/

---
Tags: collision-detection
---


title: Limit buttontext to one line in Unity?

text:
# Question
Title: Limit buttontext to one line in Unity?
I have many buttons in my game. There are different texts on them every time. But some texts are too long and get split up into two different lines. Is there any way I can fix this without resizing the button. How do I limit the button to one line. p.s I do have best fit on and need it.

# Answer
Just change the horizontal overflow to Overflow:
> 1 votes

# Answer
My solution would be to re-evaluate you button text to something that fits with in the buttons as they are. You either reduce the font uniformly across all buttons (reduces readability) or simply reduc the amount of text they contain, this may make make it more difficult to understand the UIs purpose but this can be offset by tool-tips and icons and button groupings. For example:

Launch Fire and Forget Missle

Launch Heat Seaking Missle

Launch Chaff

Launch Big Bomb of Instant Death

Rather:

-------LAUNCH CONTROL---------

FIRE AND FORGET

HEAT SEEKER

CHAFF

BBID!

There are a lot of resources out there on UX design and the best way to give the user the information he/she needs as easily and efficiently as possible.

The reason I say this is because Unity recommends using BestFit sparingly (See Here).

Also setting your text to overflow has it own set of problems but you could over flow to an ellipses (See Here) however this could leave your button text rather ambiguous.
> 0 votes

---
Tags: unity, gui, text
---


# Question
Title: Applying Transformation Matrices to VBOs in OpenGL
So I've recently tried to add Vertex Buffer Object Matrix transformation to an OpenGL engine I'm working on. I could go about this by applying the matrix to a copy of each vertex individually, but this would take a lot of CPU resources, so I am trying to implement transformation natively using OpenGL. This code works:

```
    /// <summary>
    /// Sets up the required OpenGL settings so as to create the necessary environment for the models to work (must be called on a thread on which an OpenGL context is set up, preferably on the thread on which the model was loaded).
    /// </summary>
    public static void Setup(Size viewPort, ref Matrix4 camera) {
        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        if (!(viewPort.Width == 0 || viewPort.Height == 0)) {
            Matrix4 matrix;
            Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver3F, (float) viewPort.Width / viewPort.Height, 0.01F, long.MaxValue, out matrix);
            GL.LoadMatrix(ref matrix);
        }
        GL.MatrixMode(MatrixMode.Modelview);
        GL.PushMatrix();
        Camera = camera;
        GL.LoadMatrix(ref Camera);
        GL.Enable(EnableCap.DepthTest);
        GL.Enable(EnableCap.Lighting);
    }

    /// <summary>
    /// Renders the model (must be called on a thread on which an OpenGL context is set up, preferably on the thread on which the model was loaded).
    /// </summary>
    public override void Render() {
        if (IsVisible) {
            /*Matrix4 matrix = Matrix4.CreateTranslation(location);
            GL.MultMatrix(ref matrix);*/
            if (Cull)
                GL.Enable(EnableCap.CullFace);
            else
                GL.Disable(EnableCap.CullFace);
            texture.Bind();
            if (DataBuffer == 0) {
                GL.GenBuffers(1, out DataBuffer);
                GL.BindBuffer(BufferTarget.ArrayBuffer, DataBuffer);
                GL.BufferData<Vertex>(BufferTarget.ArrayBuffer, BufferSize, BufferData, Optimization);
            } else {
                GL.BindBuffer(BufferTarget.ArrayBuffer, DataBuffer);
                if (UpdateFrame) {
                    GL.BufferData<Vertex>(BufferTarget.ArrayBuffer, BufferSize, BufferData, Optimization);
                    UpdateFrame = false;
                }
            }
            IndexBuffer.Bind();
            GL.VertexPointer(3, VertexPointerType.Float, Vertex.SizeOfVertex, IntPtr.Zero);
            GL.TexCoordPointer(2, TexCoordPointerType.Float, Vertex.SizeOfVertex, TexturePointer);
            GL.NormalPointer(NormalPointerType.Float, Vertex.SizeOfVertex, NormalPointer);
            GL.DrawElements(BeginMode.Triangles, IndexBuffer.Count, IndexBuffer.Format, IntPtr.Zero);
            GL.Disable(EnableCap.CullFace);
            //GL.LoadMatrix(ref Camera);
        }
    }

    /// <summary>
    /// Resets the OpenGL settings set by calling Setup().
    /// </summary>
    public static void Reset() {
        GL.PopMatrix();
        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();
    }

```

First Setup() is called to set up the projection matrix, then several meshes are rendered using the Render() method, then Reset() is called at the end to restore the matrices before I swap the buffers to the window.

However, when I comment out the commented lines in order to apply a simple translation matrix, I only get flickers all over the window. I tried using GL.Push() and GL.Pop() at the beginning and end of the Render() method, but to no avail. I also tried using GL.LoadIdentity() first and GL.MatrixMode(MatrixMode.Projection), but still no success.

Can anyone be kind enough to point out the mistake in my code please?

# Answer
> 2 votes
I've been in a similar spot some time ago, then i asked this question. You should try to apply the transformation matrix on the GPU side with vertex shaders, so it wont take years to change every vertex in your model.

I hope it helps

---
Tags: c#, opengl, matrix, transformation, opentk
---


title: AddComponent with Network* at runtime?

text:
# Question
Title: AddComponent with Network* at runtime?
I am trying to figure out how to dynamically add network components to game objects that are managed by the network.

I started unity about a month ago, and I started writing all sorts of components that I then wired together in the editor. I have now reached the point where I realize how cumbersome it is to manage a complex project that is built that way.

I am now going through and trying to create "controller" mono behaviors for all of my entities. The intent is that the controller will use AddComponent to add the behaviors it needs. So instead of creating a prefab with a dozen components that are all wired together in the editor, I create a prefab with a single controller component. That controller then adds components like a rigid body, collider, etc., and wires them together via code.

This works well until I get to networking the entity. It seems like network components need to be part of the prefab or they don't work at all. I tried using OnStartServer and OnStartClient to add NetworkTransform components, but the transform wasn't synchronizing. I could add the NetworkTransform to the prefab, but then it needs a rigid body... and I suspect other network behaviors would also need to be there. And then I'm right back where I started, with a large, opaque prefab.

I have no problems getting networked entities working with monolithic prefabs and the built in network manager. But when I try the " grown up" way, by adding components in code, it goes pear - shaped.

Is what I'm attempting even possible? How deep do I have to go into unity's networking in order to do this? Is there a way that involves the sparsely documented ClientScene methods? Do I need to somehow make the network server aware of the newly added NetworkTransform?

# Answer
> 2 votes
Maybe it is possible, but I don't think that this is supported in the new HLAPI network system. What you could do is have all the componentes in the prefab you instantiate disabled, and enabling them during runtime

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


# Question
Title: How do you avoid lag with Three.js and mousemove?
I'm trying to create a browser moba-like game using three.js. I'm using `WASD` for movement and the player rotation follows the mouse with mousemove then lookAt() the intersection.

**The problem:**

As I start to move the mouse rapidly and doing other stuff like movement or shooting the game starts to lag and slow noticeably.

How can I increase performance of the game, should I create a worker thread for the raycasting, use other movement technique (e.g. right click to move). What is your recommendation?

```
var mouseCallback = function(e){
  if(e.clientX >= renderer.domElement.clientWidth-2){
    mouse.x = 1;
  } else {
    mouse.x = ( e.clientX / renderer.domElement.clientWidth ) * 2 - 1;
  }
  if(e.clientY >=  renderer.domElement.clientHeight-2){
    mouse.y = -1;
  } else {
    mouse.y = - ( e.clientY / renderer.domElement.clientHeight ) * 2 + 1;
  }
  if(player){
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObject( terain );
    var direction;

    for(var i = 0; i< intersects.length;i++){
      direction = intersects[0].point;
    }

    if(direction){
      var focalPoint =
        new THREE.Vector3(
            direction.x,
            player.position.y,
            direction.z
            );
      player.lookAt(focalPoint);
    }
  }
}

```

# Answer
I suggest that you don't directly couple browser-input-events to your game-logic. I would do something like this:

In your `mousemove` event-handler, read the current screen position and store it as a variable.

In your game-update loop, get the latest mouse-position (the variable you stored previously) and calculate the players looking direction there.

The general idea is to handle the mouse-events as quickly as possible (do not perform costly operations in the event-handler). And most importantly: Don't alter the game-state in your mouse-handler, since all this is redundant until the next frame gets rendered. So you better update the game state once, just before rendering the next frame (in your game-update loop).

*Update:* Keeping the current mouse-position as a variable is the most basic way to solve this. This might be good enough for something like the mouse-position but bad for keyboard-events (where you might get more than one in-between a single update). The solution to this would be input-buffers where you keep a list of the events that occurred and process the list in your next update.
> 3 votes

# Answer
Why do you need to use ray casting?

Simply get the direction vector (vector between actor and mouse pointer) and have the character face that direction. If it's in 3d you might need to convert from screen to world coordinates.

If you want more detailed answer you should provide some code.
> 0 votes

---
Tags: movement, raycasting, three.js
---


# Question
Title: move sprite relative to position on another sprite (sword and player)
I'm sure this is a common problem people face but I can't find much on this topic after some googling.

I have a sword, and a player, both which are sprites. I want the sword to be attached to the player -- Normally you would be able to just child the sword sprite to the player sprite and change the relative position of the sword sprite -- but my player's hands move during the walking animation.

So is there an easy way of moving the position of the sword sprite during each frame of the player walking animation? Or some way of attaching the handle of the sword sprite to the player's hand?

# Answer
You could try making the sword and the hand same object so when you animate the hand the sword will be animated too.
> 1 votes

# Answer
You could modify your character sprite so that the arm is separate and moves on its own as your character moves.

Then you could just attach the arm to the character, add in some code to handle making it wag around when you walk, and now you simply child the sword off of the arm and it will be moved around when the arm moves.
> 1 votes

# Answer
Unfortunately theres no easy built in solution to do this. What you need is a series of reference points that your sword object can position and align itself with according to what frame of the animation your character is on.

What I did personally in such situations was to open the sprite sheet up and get the pixel location of each frame where I wanted and attached object to be and write this out into an XML doc. Then using that pixel offset you can calculate where your object should be in relation to the parent at each frame of the animation. If you have a large number of these to do it would be well worth your time to find a third party app or write a utility that can expedite outputting the coordinates.
> 0 votes

---
Tags: unity
---


title: Android with SDL2

text:
# Question
Title: Android with SDL2
How to link native code (it has SDL\_CreateWindow) with Java application code? In my case, there `libSDL2.so`, also my `.so` library that uses the SDL. My `method` contains functions `SDL_CreateWindow` and `SDL_Init`

Under Win32 (collected in the dll) it works. Called the "method" and creates a new window. But in the same way by running method, the function works and completes execution without exceptions thrown, but nothing visually appears

*my.cpp*

```
int method(){

    SDL_Init(SDL_INIT_EVERYTHING);
    window = SDL_CreateWindow("test!!!!!!!!!!!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

    return 0;
}

#ifdef ANDROID
    extern "C" JNIEXPORT jint JNICALL Java_com_example_ni55an_ndktest_HelloClass_method(JNIEnv * env, jclass obj){
         return (jint)method();
    }
#endif

```

my.java

```
  static {
        System.loadLibrary("SDL2");
        System.loadLibrary("proj");
    }
    public native int method();

```

Sorry, but I'm forgot do validation for SDL\_Init. Initialization fails, and I get an error `Application didn't initialize properly, did you include SDL_main.h in the file containing your main() function?`

# Answer
> 0 votes
I found the solution using the example.

In Java application must be SDLActivity. It calls nativeInit of SDL\_android\_main.c, which must be compiled along with my .so library(like here)

`nativeInit` runs the method `SDL_main`, which essentially is the entry point of my library and contains `SDL_Init` and other initialization methods

---
Tags: android, sdl2, ndk
---