title: Interface or Class Inheritance

text:
# Question
Title: Interface or Class Inheritance
I am making an inventory system. Different inventory item will have different uses so i am thinking about making a base class called InventoryItem and derive Wood, Gold, Weapons and so on. This way all InventoryItems will share some basic functionality and can have their unique as well.

My questions are:

1. If instead i use a interface i cannot count on specific fields or variables as it only takes methods. Is there any reason to use interfaces?
2. If i use derived classes and have a List with mixed items from different derived classes i would need some code that goes through each class and casts it to the proper class to use its unique abilities. How is this best handled?

# Answer
> 0 votes
> 1. If instead i use a interface i cannot count on specific fields or variables as it only takes methods. Is there any reason to use interfaces?

While this is basically true, interfaces may include getters and setters. So you can mimic variable members without actually using them.

Just a simple example:

```
interface IWeapon {
    unsigned int CurrentAmmo { get; set; }
    unsigned int MaxAmmo { get; }
    TimeSpan ShootInterval { get; }
    TimeSpan ReloadTime { get; }
    string Name { get; }
    void Reload();
}

```

> 1. If i use derived classes and have a List with mixed items from different derived classes i would need some code that goes through each class and casts it to the proper class to use its unique abilities. How is this best handled?

That's exactly the reason for using polymorphism. If done right, your system will automatically call the apropriate member, without forcing casts or any special handling. Have a look at the virtual keyword.

Another short example:

```
class Drawable {
    virtual void Draw(RenderClass renderer) {
    }
}

// ...

foreach(Drawable d in Entities)
    d.Draw(myRenderTarget);

```

Derived classes can now do one of two things:

* Don't implement `Drawable::Draw` which will essentially redirect all calls to the base class (i.e. default behavior).
* Reimplement `Drawable::Draw` using the override keyword to overwrite the default behavior.

If a member is marked as `virtual`, you'll always call the most derived `override` being available.

Using an abstract base class is similar, but compared to interfaces this allows you to already implement parts, while leaving others unimplemented (they'll have to be implemented in derived classes).

---
Tags: polymorphism
---


# Question
Title: What are the common rendering optimization techniques for the geometry pass in a deferred shading renderer?
I have been developing a game engine using OpenGL 3 and C++ (and glfw for window management). I have advanced so far, got most of the things done except sound entities and optimizations. The engine uses deferred shading so since deferred shading is itself a tiring process for an average GPU, I want to optimize the rendering process as much as possible.

The current system consists of a Scene, containing a Renderer and the current World and the World holds entities and lighting entities as separate `std::vectors`.

So basically every time the Scene gets called by `->render()`, and it calls the Renderer, passinng the world as a parameter and gets the entity iterators from the world, draws them to the FBO and then goes through the lighting entities for the second pass. And I think this is not enough.

My current algorithm iterates through everything even if the entity is not in the screen space. I am thinking of a way to optimize the current rendering algorithm so it only calls the API functions only for the visible objects, so what are the common techniques for optimizing such renderer ?

# Answer
> 45 votes
Deferred shading is only a technique to "defer" the actual shading operation for later stages, this can be great to reduce the number of passes needed (for example) to render 10 lights which needs 10 passes. My point is regardless of the rendering technique you are using there are certain possible rendering optimizations that reduce the number of objects (vertices, normals etc) that your rendering pipeline need to process.

There are no de facto standard for rendering optimizations, but rather a number of techniques that can be used interchangeably or together to achieve certain performance characteristics. Using each technique highly depends on the nature of the scene being rendered.

Deferred rendering tries to solve the problem when the number of lights increases, which in forward rendering might make the number of passes explode.

Those techniques does not directly optimize the deferred shading part, but according to your description, **the deferred shading part is NOT your problem.** Your problem though is that you are submitting the whole scene to rendering pipeline. So your engine has to process (for example all the 100 million vertices) in your scene just to be able to submit the result to the g-buffer, while most of theses 100 million vertex can trivially be culled away, and not submitted to the pre-process vertex and fragments pass.

In case of a forward renderer the N vertex will be processed by the vertex stage as a total of `vertex count*lights count` and by the fragment stage as a total of `fragments count*number Lights`, deferred shading effectively reduces this to only `vertex count` for the vertex stage and `fragments count` for the fragment count, before resolving the actual shading. But still N can be too much to process, especially when most of them can be trivially culled.

This makes culling more effective in case of forward rendering/multiple passes. But keep in mind that most engines will use a dual rendering approach, because deferred shading alone can **not** resolve transparent objects, this makes using those optimizations a must, I don't know of any commercial engine that don't do all of them.

## Frustum Culling

Only Objects that are fully or partially included in the view frustum, ever need to be submitted to the rendering pipeline. This is the basic concept of frustum culling, unfortunately checking if a mesh is in/out of the view frustum can be an expensive operation, so instead, engine designers use an approximate bounding volume like an (AABB)Axis Aligned bounding box or bounding sphere, even though this might not be as accurate as using the actual mesh, the accuracy difference isn't worth the trouble of checking with the actual mesh.

Even with bounding volumes, you don't really need to check each one, alternatively you can construct a bounding volume hierarchy to do an earlier culling, using this is highly dependent on the complexity of the scene.

This is a good and a simple technique for a smaller engine, and is almost used in every engine I ever used. I recommend using a "normal" Bounding Volume/Frustum checking without hierarchies if your engine does not require rendering very complex scenes.

## Back face culling

This is a must, why draw faces that won't be visible anyway? rendering APIs provide an interface to turn on/off back face culling. Unless you have a strong reason why not to turn it on, like some of the CAD applications that need to draw backfaces in certain circumstances, this is a must do thing.

## Occlusion Culling

Using the Z-buffer you can resolve visibility determination. But the problem is that Z-buffer isn't always great in terms of performance, since Z-buffer can only be resolved at later stages of the pipeline, objects being occluded should be rasterized and might be written to the Z-buffer and the Color buffer before failing the Z test.

Occlusion culling solves this, by doing some early tests to cull occluded objects that are in the rendering frustum. One practical implementation of occlusion culling is using point-based queries and checking if certain objects are visible from a specific point view. This can also be used to cull lights that do not contribute to the final image this is especially useful in a deferred engine renderer.

A great real world example of such technique is in GTA5, where the skyscrapers are stratigically placed at the center of the city, are not only decorations, **but they also work as occluders, effectively occluding the rest part of the city and preventing it from being rasterized.**

## Level of Detail

Level of detail is widely used technique, the idea is to use a simpler version of the mesh when the mesh is less contributing to the scene. there are two common implementations; one simply switches the mesh with a simpler one when it's no longer greatly contributing, the mesh is selected based on some factor like the distance and the number of pixels (area on the scree) the mesh is occupying. The other version dynamically tessellates the mesh, this is widely used in terrain rendering.

## What if all of these didn't work ?

Well, that's a good question.

The first thing you need to do is to Profile your application using a graphics profiler, and determine where the bottleneck is. Keep in mind that the bottleneck may change as the content being rendered change. Bottlenecks might be also be part of the code running on CPU so you need to measure that too.

After that you need to do some optimizations on the bottleneck, keep in mind that there is no right answer for this, and will be different from hardware to another.

Some common GPU optimization tricks:

* Avoid branching in shaders.
* Try different vertex structures for example `{VNT}` interleaved in the same array or `{V},{N},{T}` in different arrays.
* Draw scene front to back.
* Turn off Z-buffer at some points for example if an image doesn't need Z testing.
* Use compressed textures.

Some common CPU optimization tricks:

* Use inline functions for small functions.
* Use SIMD (Single instruction multiple data) when possible.
* Avoid cache unfriendly memory jumps.
* Use VBOs with the "right" amount of data. (depending on your hardware) but usually less draw calls are better.

## But what if my bottleneck was in the deferred shading ?

In this case, since deferred shading is more concerned about lights then the most obvious part is to optimize the actual shading calculations. some of the points to keep an eye on:

* Render lights that actually affect the final image. In other words cull the lights that don't contribute. This can be effectively implemented using the occlusion culling I mentioned before.
* Does this light need the specular or some other components? Maybe not.
* Does this light cast shadow ? Some lights don't need to cast shadows.
* Can this light contribution be pre-computed? If it is not moving probably some aspects can be pre-computed.

# Answer
> 6 votes
**Your problem is not related to deferred shading whatsoever**, you need to implement the basic core elements of a renderer before you try to speed up some specific part.

When you have finished with what concept3d has explained, if you actually find that you need to optimize the **deferred shader** itself (as opposed to the whole rasterization pass) you can implement Tile-Based Deferred Shading.

If you are not limited by the number of dynamic lights you should consider why you are using deferred shading at all, but if you *are* then you will want to try the optimization that made Battlefield 3 possible. (They hint to it in slide 10 of their public PDF: http://dice.se/wp-content/uploads/GDC11\_DX11inBF3\_Public.pdf)

---
Tags: opengl, c++, optimization, deferred-rendering
---


# Question
Title: glDrawArrays (layered rendering using geometry shader) only draws one point
I have been debugging this for a while but I can't seem to find the issue.

I created a framebuffer for layered rendering like this

```
GLuint buffer;
glGenFramebuffers(1,&buffer);
glBindFramebuffer(GL_FRAMEBUFFER,buffer);

glFramebufferTexture(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,textures[0],0);

GLenum blub[] = {GL_COLOR_ATTACHMENT0};

glDrawBuffers(1,blub);

```

where textures\[0\] is a 3D texture for layered rendering. The texture is texture complete, using nearest for min and mag filtering, no mip mapping, clamp to edge for s,t and r. I can sample from it fine (I initialize the texture to a color based on the z coordinate inside the 3d texture, it's initialized fine as well). The size of the 3D texture right now is 32x32x32 texels.

The framebuffer is framebuffer complete (checked it using glCheckFramebufferStatus).

Then I create and fill a buffer with vertex data for the points like this:

```
vector<vec2> points;
points.push_back(vec2(0.0f,0.0f)); //should draw in the middle
points.push_back(vec2(0.5f,0.5f)); //3/4th in each direction
points.push_back(vec2(-0.5f,-0.5f)); //opposite of second point
points.push_back(vec2(-0.95f,-0.95f)); //first texel on the bottom left

glGenBuffers(1,&result);

glBindBuffer(GL_ARRAY_BUFFER,result);
glBufferData(GL_ARRAY_BUFFER,points.size()*2*sizeof(float),&points[0],GL_STATIC_DRAW);

```

where vec2 is the vec2 floating point vector class provided by GLM.

Then I render it by doing this:

```
glViewport(0,0,textureSizeX,textureSizeY);
glBindFramebuffer(buffer);
glUseProgram(shader);
glBindBuffer(GL_ARRAY_BUFFER,_pointbuffer);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,0,0);
glDrawArrays(GL_POINTS,0,4);

```

where shader is a shader constructed from vertex, geometry and fragment shaders. It compiles fine without warnings. Depth and stencil testing are disabled. textureSizeX and textureSizeY are the width and height of the 3D texture.

Vertex shader:

```
#version 430

layout(location =0) in vec2 pos;

void main()
{
    gl_Position = vec4(pos.xy,0,1);
}

```

Geometry shader:

```
#version 430

layout(points) in;
layout(points, max_vertices = 1) out;

void main()
{
    gl_Layer = 0;
    gl_Position = vec4(gl_in[0].gl_Position.xy,1,1);
    gl_PointSize = 1.0f;

    EmitVertex();
    EndPrimitive();
}

```

Fragment shader:

```
#version 430

out vec4 outcolor;

void main()
{
    outcolor = vec4(0,1,0,0);
}

```

However, only the first point is drawn, as expected in the middle of layer 0 of the 3D texture. I can move around the coordinates of the first point and get the expected results. The points after the first point are always ignored, however. What am I doing wrong?

Hardware is GTX 770 with driver version 331.82 (latest version). Tested it on GT 555M (Notebook GPU), same results. The OpenGL device context is version 4.3.

edit: Tried so far: When I extend the attribute input of the vertex data to a vec4, and change the argument in glVertexAttribPointer accordingly, as expected the z and w components of the vec4 contain the coordinates of the second point, so the positions seem to be in memory as expected.

Similarly, if I change the offset using glVertexAttribPointer (e.g. putting (void\*)(sizeof(vec2)\*3) as the last parameter), the respective point is drawn.

Just to test if something may be wrong with the rasterization in general, I tried emitting triangles instead of points in the geometry shader. This works as expected.

# Answer
I've since solved it, and since I tried all possible permutations of changes I could think off, I think it might simply be a driver bug.

I just changed the attribute location back to 0 in the shader and changed the respective arguments in the C++ side function calls as well. Afaik 5 should work just as well, but for some reason it doesn't.
> 1 votes

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


# Question
Title: Why am I seeing undesirable rendering results using VBOs like this?
I am trying to write a program that renders using VBO(vertex buffer objects). Everything works great except that when I run the program, It looks like the object is spazzing out. I think its due to the fact that I am trying to delete the buffers, but I could not fix the problem no matter what I have done. Can someone tell me what I am doing wrong with the piece of code? Appreciate it.

```
    GLuint VBOvertex;
    GLuint VBOTexCoord;
    GLuint VBONormal;

//////////////////////////VERTEX BUFFER
glGenBuffers(1, &VBOvertex);
glBindBuffer(GL_ARRAY_BUFFER,VBOvertex);
glBufferData(GL_ARRAY_BUFFER,sizeof(m->verticies)*3,m->verticies,GL_STATIC_DRAW);

///////////////////////////TextCoord BUFFER
glGenBuffers(1, &VBOTexCoord);
glBindBuffer(GL_ARRAY_BUFFER,VBOTexCoord);

glBufferData(GL_ARRAY_BUFFER,sizeof(m->TextCoord)*2,m->TextCoord,GL_STATIC_DRAW);
//////////////////////////////NORMAL BUFFER
glGenBuffers(1, &VBONormal);
glBindBuffer(GL_ARRAY_BUFFER,VBONormal);
glBufferData(GL_ARRAY_BUFFER,sizeof(m->Normal)*3,m->Normal,GL_STATIC_DRAW);

delete[]m->verticies;
m->verticies=NULL;
delete[]m->TextCoord;
m->TextCoord=NULL;
delete[]m->Normal;
m->Normal=NULL;

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);

glBindBuffer(GL_ARRAY_BUFFER,VBOvertex);
glVertexPointer(3,GL_FLOAT,0,0);

glBindBuffer(GL_ARRAY_BUFFER, VBOTexCoord);
glTexCoordPointer(2,GL_FLOAT,0,0);

glBindBuffer(GL_ARRAY_BUFFER, VBONormal);
glNormalPointer(GL_FLOAT,0,0);

glDrawArrays(GL_TRIANGLES, 0,m->nbrTris*3);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);

```

# Answer
1. You're using VBONormal to supply data to all 3 gl\*Pointer calls, you need to call the APIs in the correct order.
2. You are giving a pointer into CPU memory, but when a VBO is enabled, the pointer needs to be relative to the VBO.
3. What concept3d said about your indices is correct also, I'll leave it to you to fix that (but it *should* work the way you have it, just very slowly)

It should look more like:

```
...
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

//Bind
glBindBuffer(GL_ARRAY_BUFFER,VBOvertex);
glVertexPointer(3,GL_FLOAT,0,0);

glBindBuffer(GL_ARRAY_BUFFER, VBOTexCoord);
glTexCoordPointer(2,GL_FLOAT,0,0);

glBindBuffer(GL_ARRAY_BUFFER, VBONormal);
glNormalPointer(GL_FLOAT,0,0);
...

```

I think you didn't read the manual carefully ;)

---

EDIT: Looking over your code again I see another issue: glBufferData needs to know the **total** size in bytes, not the size per vertex, since it needs to copy all the data when you call it.

Should look something like this:

```
...
glBufferData(GL_ARRAY_BUFFER,
    m->nbrVertices*sizeof(float)*3,
    m->verticies,
    GL_STATIC_DRAW);
...

```
> 1 votes

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


# Question
Title: Basic Car Movement, Converting 2D Vectors to 3D problems
I'm trying to follow this guys method for steering a basic car. Link.

It's the first example I can sort of get my head around and I'm trying to convert it to a working 3D version.

To get some scope, I've rendered a cube in OpenGL which represents a car and I'm using GLM for matrix manipulation.

Even though I'm trying to get a 3D example working, I'm only using 2D controls; the X axis for left/right and Z axis for forwards/backwards.

For clarity, I have shown all the vectors as vec.x, vec.y, vec.z. note that not much happens with the vec.y as for the time being the car stays level on the X Z plane. (like top-down games but in 3D environment).

I'm getting some strange responses on screen and I can't see why. I can only assume I've misunderstood where some of the code belongs.

These are my variables etc:

```
glm::vec3 carLocation(0,0,0);   //location of car
float carHeading    = 0.0f;     //direction car facing
float carSpeed      = 0.5f;     //speed of car
float steeringAngle = 0.0f;     //angle of front wheel
float wheelBase;                //length of car
glm::vec3 frontWheel;           //vec 3 representing front wheel
glm::vec3 backWheel;            //vec 3 representing back wheel
glm::vec3 sincos_Calc;          //vec 3 representing sin/cos calculation

```

This is my function to render the car and manipulate it:

```
void renderMovingCube(){
glUseProgram(movingCubeShader.handle());
GLuint matrixLoc4MovingCube = glGetUniformLocation(movingCubeShader.handle(), "ProjectionMatrix");
glUniformMatrix4fv(matrixLoc4MovingCube, 1, GL_FALSE, &ProjectionMatrix[0][0]);

    glm::mat4 viewMatrixMovingCube;
    viewMatrixMovingCube = glm::lookAt(camOrigin, camLookingAt, camNormalXYZ);

        //set values
        wheelBase = 12;                     //car dim X;
        sincos_Calc.x = cos(carHeading);    //adjust X coord
        sincos_Calc.y = 0;                  //car stays on Y plane
        sincos_Calc.z = sin(carHeading);    //adjust Z coord

        //step 1
        frontWheel.x = (carLocation.x + (wheelBase/2)) * sincos_Calc.x;
        frontWheel.y = 0;
        frontWheel.z = (carLocation.z + (wheelBase/2)) * sincos_Calc.z;
        backWheel.x  = (carLocation.x - (wheelBase/2)) * sincos_Calc.x;
        backWheel.y  = 0;
        backWheel.z  = (carLocation.z - (wheelBase/2)) * sincos_Calc.z;

    //location of car
    ModelViewMatrix = glm::translate(viewMatrixMovingCube,carLocation);

    ModelViewMatrix = glm::translate(ModelViewMatrix,  glm::vec3(0,-48,0));
    ModelViewMatrix = glm::rotate(ModelViewMatrix, steeringAngle, glm::vec3(0,1,0));//manually turn

    glUniformMatrix4fv(glGetUniformLocation(movingCubeShader.handle(), "ModelViewMatrix"), 1, GL_FALSE, &ModelViewMatrix[0][0]); //pass matrix to shader
movingCube.render();        //car
glUseProgram(0);            //turn off the current shader
}

```

This is my key input:

```
void keyboard(){
if (FORWARD) //W key
{
    //step 2
    backWheel.x += carSpeed*sincos_Calc.x;
    backWheel.y += 0;
    backWheel.z += carSpeed*sincos_Calc.z;
    frontWheel.x += carSpeed*(cos(carHeading+steeringAngle));
    frontWheel.y += 0;
    frontWheel.z += carSpeed*(sin(carHeading+steeringAngle));

    //step 3
    carLocation.x = (frontWheel.x+backWheel.x)/2;
    carLocation.y = 0;
    carLocation.z = (frontWheel.z+backWheel.z)/2;
    carHeading = atan2((frontWheel.z-backWheel.z), (frontWheel.x-backWheel.x));

    cout<< glm::to_string(carLocation) << endl;
    BACKWARD = false;
}
if (ROT_LEFT){ //A key
    steeringAngle +=0.5f;
    ROT_LEFT = false;
}
if (ROT_RIGHT){ //D key
    steeringAngle -=0.5f;
    ROT_RIGHT = false;
}
}

```

I've been trying for days to get this to work and done so much googling and SO'ing to avoid posting this but I'm still have problems with it.

My aim is to have my cube moving forwards/backwards and steering/turing like a car, described in the link above.

Am I even remotely heading in the right direct? I'm not quite sure why Step 2 overwrites step 1, I feel this is why I'm going wrong...

Have I converted the vecs from vec2's to vec3's correctly? and Are my "steps" in the right locations? Thanks.

# Answer
First, You are doing the step 1 wrongly. You should add the (sin, cos) direction scaled by half whellBase instead of scalling the entire result. So, the first line of this step should be:

```
frontWheel.x = carLocation.x + wheelBase/2*sincos_Calc.x;

```

instead of

```
frontWheel.x = (carLocation.x + (wheelBase/2)) * sincos_Calc.x;

```

The same applies for `frontWheel.z` and `backWheel`.

Second, I don't know if your `glUniformMatrix4fv` calls will work properly. It seems by your code that you are using a multidimensional matrix, but OpenGL uses monodimensional matrices as transformations. See this tutorial.

Third, I think your `glm::rotate` should take into consideration the car heading too:

```
ModelViewMatrix = glm::rotate(ModelViewMatrix, carHeading + steeringAngle, glm::vec3(0,1,0));//manually turn

```

As a final tip, don't mix rendering, input and game update. Rendering and input should be encapsulated by their proper classes and the update should be encapsulated by a function of the game object at least.
> 1 votes

---
Tags: opengl, c++, physics, vector, linear-algebra
---


# Question
Title: How does Unity3D lower an imported .obj vertex count?
I have a question regarding how Unity3D handles importing of .obj files. I'm importing this teapot: http://groups.csail.mit.edu/graphics/classes/6.837/F03/models/teapot.obj

The number of vertices this teapot has is 3644. I know that Unity's Mesh class needs to replicate these vertices for each face shared by the same vertex. I tried this with a Cube imported from a .obj, and using Debug.Log() to print the number of vertexes I found out that there were 24 vertices in the mesh's vertex array.

However, with the teapot the original file had 3644 vertices, so in Unity the vertex count should be 18960. Instead, when I print the length of the mesh's vertex array, it prints 3260 (even less than the original file).

The final objective for this is that I'm trying to modify an OBJ Importer script from Unity's Wiki, so that the number of vertices resulting from this script are the same as Unity's native importer. Reference: http://wiki.unity3d.com/index.php?title=ObjImporter Note: I printed the vertex count using this importer and the result was 18960.

Does anyone have an idea of how this vertex reduction might be achieved?

# Answer
> 5 votes
There are several factors that contribute to how the geometry is saved and processed in different mediums (programs, file formats, APIs). I did implement several commercial geometry analysis programs, so I have some experience with it.

First I am sure this has nothing to do with Unity simplifying anything. But in case it did there are several decimation algorithms that can be implemented but I am *sure* this isn't the case, since a game engine isn't supposed to change the shape (geometrical properties of a mesh) but can usually modify its connectivity to match his optimal structure.

Some of these factors are:

**What makes a vertex unique?**

This can greatly vary depending on how the program, api or file format deals with a vertex. A vertex can be unique if it has a unique position, but in other cases it's unique if it has any unique attribute. For example if two vertices share the same position, but have different normals they should be "duplicated" in case of OpenGL, this is especially evident in the case of the cube you mentioned.

**Hard vs Smooth edges.**

Normals can dictate if an edge is considered hard or smooth, if a vertex contributes to hard edge, then it needs to be duplicate so the current rendering APIs can understand how to render(shade) this face correctly.

**Indices**

Many file formats permit a face vertex to have several indices for the vertex position/texCoords/normals, this isn't the case of current rendering APIs. A fine example of this is the Obj file, this will force Unity to rebuild the indices and often duplicate many attributes to match the vertex indices.

**Connectivity**

A lot of the vertices that are actually connected and are unique are saved multiple times, this has to do of how the original file writer processed and saved the mesh. Unity will reduce the number of duplicate vertices (remember if it has different attribute then it's not unique) so to make it more efficient for storage and processing without sacrificing the quality.

This has also to do of how many polygon sides the original file permits, Obj for instance permit N-side polygons, which something any sane game engine doesn't want, so it end up triangulating the mesh and recalculting many of its attributes which often change the number of vertices.

# Answer
> 2 votes
Obj formats are strange in particular because the positions, normals and texture coordinates are separated and each face can choose whatever index from each stream. When you refer to vertex count you think that the vertex positions and normals count is not the same and you can't really refer to the whole count.

During loading all these three attributes must be merged together so **one vertex position could end duplicated because the face associated to that vertex position is associated to two normals**. This can happen in reverse also so most loaders have a step to optimize the obj but in case of your cube the optimization will not work since the cube has hard edges and each vertex has a different normal(or texture coordinate). This is why you counted 6 vertex positions but unity duplicated those positions resulting in 24 vertices.

To load a mesh you can duplicate positions/normals or texture coordinates so optimizing this is not something simple. It boils down to choosing the minimum number of duplicates from those three streams.

---
Tags: unity, geometry, vertex, obj
---


# Question
Title: When will the computational powers be strong enough to let play big games like Battlefield, COD from cloud?
Is there any current service similar to Steam but without having to download any games? In other words, buy digital rights to play and play from the cloud?

How much bandwidth would be necessary to play it **purely** online, and how fast must the network be?

Do you think it will become a reality in near future (for example, in the next 10 years)?

# Answer
Cloud Gaming / Gaming on Demand / Game Streaming / Gaming as a Service (GaaS) is an up-and-coming set of technologies that, due primarily to advances in signal compression, do not require the sort of bandwidth one might expect in order to stream a framebuffer, every frame, to a remote client.

NVIDIA Grid is such a technology.

Here is a service provider for cloud gaming.

I'm sure you can find many more online.

Of course the benefit to this is that it is pretty much hack-proof. The downside is that unless you are in close network proximity to your service provider, lag is a fact of life (which won't bother most, by this stage, especially given extant lag-mitigation mechanisms common in games over the last decade).
> 1 votes

---
Tags: online, cloud-computing
---


# Question
Title: why are there draw rate and update rate in fixed time step game loop?
http://www.gameprogblog.com/generic-game-loop/

Java

```
boolean onLoop( Game game, GameState state, GameInput input, Graphics2D gr ) {
  long nanosElapsed = state.tick();
  updateTime += nanosElapsed;
  int updateCount = 0;
  while (updateTime >= updateRate && updateCount < maxUpdates) {
    game.input( input );
    input.clear();
    if (!game.isPlaying()) {
      return false;
    }
    state.update();
    game.update( state );
    if (!game.isPlaying()) {
      return false;
    }
    updateCount++;
    updateTime -= updateRate;
  }
  drawTime += nanosElapsed;
  int drawCount = 0;
  if (drawTime >= drawRate || updateCount > 0) {
    state.interpolate = getStateInterpolation();
    state.forward = state.interpolate * state.seconds;
    state.backward = state.forward - state.seconds;
    state.draw();
    game.draw( state, gr );
    drawCount++;
    drawTime -= (drawRate == 0 ? drawTime : drawRate);
  }
  if (sleep && drawCount == 0 && updateCount == 0) {
    long actualTime = updateTime + state.getElapsedSinceTick();
    long sleep = (updateRate - actualTime) / 1000000L;
    if (sleep > 1) {
      try {
        Thread.sleep( sleep - 1 );
      } catch (Exception e) { }
    }
  }
  return (drawCount > 0);
}

```

I am a beginner in game programming. I wanted to know when using fixed time step why do we have different update rates and draw rates. I have seen this in more than just the above code and if i plan to make a 30 fps game then what is a reasonable draw rate to have to match 30 fps update rate?. Can you explain in understandable terms? I appreciate your help.

# Answer
> 0 votes
http://gafferongames.com/game-physics/fix-your-timestep/

The short version is that there can be a huge variation in frame rate due to a myriad of factors, many outside of the game's control. These variations can cause a lot of bugs and other gameplay oddities, especially in physics. Using a fixed timestep for updates avoids bugs.

---
Tags: java, game-loop, fixed-timestep
---


# Question
Title: Circle-Rectangle collision velocity adjustment
I created my circle vs. rectangle method based on this algorithm:

https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection

Currently, I have a dynamic ball with velocities c1SpeedX (for X axis) and c1SpeedY (Y axis). The dynamic ball is supposed to bounce off of the static rectangle when a collision occurs.

The boolean method that I use to detect if the intersection happened is the following:

```
        public boolean intersects (Circle circle, Rectangle rectangle) {
            double dx = Math.abs(circle.getLayoutX() - rectangle.getLayoutX());
            double dy = Math.abs(circle.getLayoutY() - rectangle.getLayoutY());

            if (dx > rectangle.getWidth() / 2 + circle.getRadius()) {
                return false;
            }
            if (dy > rectangle.getHeight() / 2 + circle.getRadius()) {
                return false;
            }

            if (dx <= rectangle.getWidth() / 2) {
                return true;
            }
            if (dy <= rectangle.getHeight() / 2) {
                return true;
            }
            double cornerX = (dx - rectangle.getWidth() / 2) * (dx - rectangle.getWidth() / 2);
            double cornerY = (dy - rectangle.getHeight() / 2) * (dy - rectangle.getHeight() / 2);

            double cornerDistance = cornerX + cornerY;
            double radii = circle.getRadius() * circle.getRadius();

            return cornerDistance <= radii;

        }

```

Once a collision has happened, my natural response would be to invert the values of X and Y, so the ball bounces off of the rectangle. The problem is that it's incredibly inaccurate, and the ball often goes through the rectangle without detecting a collision.

```
if (intersects(circle1, rect1)) {
                    c1SpeedX = c1SpeedX * -1;
                    c1SpeedY = c1SpeedY * -1;
                }

```

So, how do I optimize my code to make the ball always **accurately** bounce off of the rectangle? Is it a velocity problem, or is something wrong with the intersects method?

Thanks.

# Answer
Hi and thanks for your questions.

If your collision is not detected there are 3 obvious problems that could happen.

First your ball is moving to fast or your collision detection time interval is to low. This causes the ball to appear once in front and after behind the rectangle. To solve this simply interpolate over the last translation of your object and check each time for a collision. This is anyway a good point because it improves the precision of your collision detection. More can be read online.

Second your algorithm of collision detection does not work correctly. To prove this you should first give your variables meaningful names this helps you and us to understand your code faster and probably.

```
static bool rectangleIntersectsCircle(Rectangle rectangle, Circle circle)
{
  Point closestPointToCircle = circle.midPoint();

  if( closestPointToCircle.x() > rectangle.right() ) closestPointToCircle.setX( rectangle.right() );
  else if( closestPointToCircle.x() < rectangle.left() ) closestPointToCircle.setX( rectangle.left() );

  if( closestPointToCircle.y() > rectangle.bottom() ) closestPointToCircle.setY( rectangle.bottom() );
  else if( closestPointToCircle.y() < rectangle.top() ) closestPointToCircle.setY( rectangle.top() );

  return point_distance( closestPointToCircle, circle.midPoint() ) <= circle.radiant();
}

```

I did not really look for mistakes in code because im not familiar with java and the method naming confused me. Whatever it is important to check each side unless you do not check the relative position of the objects before. Especially the corner test seems wrong to me because you did not test all of them.

The third problem I could think of is that maybe the coordinate system of the objects given to the intersect method are not the same that are used to render them.

The second question about velocity and smoothness is more about detecting the best fitting collision point and calculate the reflecting vector. Anyway this gives you only the direction. Calculating speed and velocity gets more complicated and is based on the physical properties of your objects material. If you explain more what kind of physical reaction you want I can try to explain more, better make a new question because these are 2 different topics.

I hope I could help you. If you have further questions just tell us.

Michael
> 3 votes

---
Tags: java, 2d, collision-detection, game-design, vector
---


title: Tile Collision & Sliding against tiles

text:
# Question
Title: Tile Collision & Sliding against tiles
I have a tile based map with a top down camera. My sprite stops moving when he collides with a wall in any of the four directions however I am trying to get the sprite to slide along the wall if more than one directional key is pressed after being stopped. Tiles are set to 32 x 32.

Here is my code;

```
        // Gets Tile Player Is Standing On
        var splatterTileX = (int)player.Position.X / Engine.TileWidth;
        var splatterTileY = (int)player.Position.Y / Engine.TileHeight;

        // Foreach Layer In World Splatter Map Layers
        foreach (var layer in WorldSplatterTileMapLayers)
        {
            // If Sprite Is Not On Any Edges
            if (splatterTileX < layer.Width - 1 && splatterTileX > 0 && splatterTileY < layer.Height - 1 && splatterTileY > 0)
            {
                tileN = layer.GetTile(splatterTileX, splatterTileY - 1);      // North
                tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East
                tileE = layer.GetTile(splatterTileX + 1, splatterTileY);      // East
                tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East
                tileS = layer.GetTile(splatterTileX, splatterTileY + 1);      // South
                tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West
                tileW = layer.GetTile(splatterTileX - 1, splatterTileY);      // West
                tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West
            }

            // If Sprite Is Not On Any X Edges And Is On -Y Edge
            if (splatterTileX < layer.Width - 1 && splatterTileX > 0 && splatterTileY == 0)
            {
                tileE = layer.GetTile(splatterTileX + 1, splatterTileY);      // East
                tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East
                tileS = layer.GetTile(splatterTileX, splatterTileY + 1);      // South
                tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West
                tileW = layer.GetTile(splatterTileX - 1, splatterTileY);      // West
            }
            // If Sprite Is On +X And -Y Edges
            if (splatterTileX == layer.Width - 1 && splatterTileY == 0)
            {
                tileS = layer.GetTile(splatterTileX, splatterTileY + 1);      // South
                tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West
                tileW = layer.GetTile(splatterTileX - 1, splatterTileY);      // West
            }
            // If Sprite Is On +X Edge And Y Is Not On Any Edge
            if (splatterTileX == layer.Width - 1 && splatterTileY < layer.Height - 1 && splatterTileY > 0)
            {
                tileS = layer.GetTile(splatterTileX, splatterTileY + 1);      // South
                tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West
                tileW = layer.GetTile(splatterTileX - 1, splatterTileY);      // West
                tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West
                tileN = layer.GetTile(splatterTileX, splatterTileY - 1);      // North
            }
            // If Sprite Is On +X And +Y Edges
            if (splatterTileX == layer.Width - 1 && splatterTileY == layer.Height - 1)
            {
                tileW = layer.GetTile(splatterTileX - 1, splatterTileY);      // West
                tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West
                tileN = layer.GetTile(splatterTileX, splatterTileY - 1);      // North
            }
            // If Sprite Is Not On Any X Edges And Is On +Y Edge
            if (splatterTileX < (layer.Width - 1) && splatterTileX > 0 && splatterTileY == layer.Height - 1)
            {
                tileW = layer.GetTile(splatterTileX - 1, splatterTileY);      // West
                tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West
                tileN = layer.GetTile(splatterTileX, splatterTileY - 1);      // North
                tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East
                tileE = layer.GetTile(splatterTileX + 1, splatterTileY);      // East
            }
            // If Sprite Is On -X And +Y Edges
            if (splatterTileX == 0 && splatterTileY == layer.Height - 1)
            {
                tileN = layer.GetTile(splatterTileX, splatterTileY - 1);      // North
                tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East
                tileE = layer.GetTile(splatterTileX + 1, splatterTileY);      // East
            }
            // If Sprite Is On -X Edge And Y Is Not On Any Edges
            if (splatterTileX == 0 && splatterTileY < (layer.Height - 1) && splatterTileY > 0)
            {
                tileN = layer.GetTile(splatterTileX, splatterTileY - 1);      // North
                tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East
                tileE = layer.GetTile(splatterTileX + 1, splatterTileY);      // East
                tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East
                tileS = layer.GetTile(splatterTileX, splatterTileY + 1);      // South
            }
            // If Sprite Is In The Top Left Corner
            if (splatterTileX == 0 && splatterTileY == 0)
            {
                tileE = layer.GetTile(splatterTileX + 1, splatterTileY);      // East
                tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East
                tileS = layer.GetTile(splatterTileX, splatterTileY + 1);      // South
            }
            // Creates A New Rectangle For TileN
            tileN.TileRectangle = new Rectangle(splatterTileX * Engine.TileWidth,
                                              (splatterTileY - 1) * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And N Tile
            var tileNCollision = player.Rectangle.Intersects(tileN.TileRectangle);

            // Creates A New Rectangle For TileNE
            tileNE.TileRectangle = new Rectangle((splatterTileX + 1) * Engine.TileWidth,
                                              (splatterTileY - 1) * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And NE Tile
            var tileNECollision = player.Rectangle.Intersects(tileNE.TileRectangle);

            // Creates A New Rectangle For TileE
            tileE.TileRectangle = new Rectangle((splatterTileX + 1) * Engine.TileWidth,
                                              splatterTileY * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And E Tile
            var tileECollision = player.Rectangle.Intersects(tileE.TileRectangle);

            // Creates A New Rectangle For TileSE
            tileSE.TileRectangle = new Rectangle((splatterTileX + 1) * Engine.TileWidth,
                                              (splatterTileY + 1) * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And SE Tile
            var tileSECollision = player.Rectangle.Intersects(tileSE.TileRectangle);

            // Creates A New Rectangle For TileS
            tileS.TileRectangle = new Rectangle(splatterTileX * Engine.TileWidth,
                                              (splatterTileY + 1) * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And S Tile
            var tileSCollision = player.Rectangle.Intersects(tileS.TileRectangle);

            // Creates A New Rectangle For TileSW
            tileSW.TileRectangle = new Rectangle((splatterTileX - 1) * Engine.TileWidth,
                                              (splatterTileY + 1) * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And SW Tile
            var tileSWCollision = player.Rectangle.Intersects(tileSW.TileRectangle);

            // Creates A New Rectangle For TileW
            tileW.TileRectangle = new Rectangle((splatterTileX - 1) * Engine.TileWidth,
                                              splatterTileY * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And Current Tile
            var tileWCollision = player.Rectangle.Intersects(tileW.TileRectangle);

            // Creates A New Rectangle For TileNW
            tileNW.TileRectangle = new Rectangle((splatterTileX - 1) * Engine.TileWidth,
                                              (splatterTileY - 1) * Engine.TileHeight,
                                              Engine.TileWidth,
                                              Engine.TileHeight);

            // Tile Collision Detection Between Player Rectangle And Current Tile
            var tileNWCollision = player.Rectangle.Intersects(tileNW.TileRectangle);

            // Allow Sprite To Occupy More Than One Tile
            if (tileNCollision && tileN.TileBlocked == false)
            {
                tileN.TileOccupied = true;
            }
            if (tileECollision && tileE.TileBlocked == false)
            {
                tileE.TileOccupied = true;
            }
            if (tileSCollision && tileS.TileBlocked == false)
            {
                tileS.TileOccupied = true;
            }
            if (tileWCollision && tileW.TileBlocked == false)
            {
                tileW.TileOccupied = true;
            }

            // Player Up
            if (keyState.IsKeyDown(Keys.W) ||
                (gamePadOneState.DPad.Up == ButtonState.Pressed))
            {
                player.CurrentAnimation = AnimationKey.Up;

                if (tileN.TileOccupied == false)
                {
                    if (tileNWCollision && tileNW.TileBlocked || tileNCollision && tileN.TileBlocked || tileNECollision && tileNE.TileBlocked)
                    {
                        playerMotion.Y = 0;
                    }
                    else
                        playerMotion.Y = -1;
                }
                else if (tileN.TileOccupied)
                {
                    if (tileNWCollision && tileNW.TileBlocked || tileNECollision && tileNE.TileBlocked)
                    {
                        playerMotion.Y = 0;
                    }
                    else
                        playerMotion.Y = -1;
                }
            }

            // Player Down
            if (keyState.IsKeyDown(Keys.S) ||
                (gamePadOneState.DPad.Down == ButtonState.Pressed))
            {
                player.CurrentAnimation = AnimationKey.Down;

                // Check Collision With Tiles
                if (tileS.TileOccupied == false)
                {
                    if (tileSWCollision && tileSW.TileBlocked || tileSCollision && tileS.TileBlocked || tileSECollision && tileSE.TileBlocked)
                    {
                        playerMotion.Y = 0;
                    }
                    else
                        playerMotion.Y = 1;
                }
                else if (tileS.TileOccupied)
                {
                    if (tileSWCollision && tileSW.TileBlocked || tileSECollision && tileSE.TileBlocked)
                    {
                        playerMotion.Y = 0;
                    }
                    else
                        playerMotion.Y = 1;
                }
            }

            // Player Left
            if (keyState.IsKeyDown(Keys.A) ||
                (gamePadOneState.DPad.Left == ButtonState.Pressed))
            {
                player.CurrentAnimation = AnimationKey.Left;

                if (tileW.TileOccupied == false)
                {
                    if (tileNWCollision && tileNW.TileBlocked || tileWCollision && tileW.TileBlocked || tileSWCollision && tileSW.TileBlocked)
                    {
                        playerMotion.X = 0;
                    }
                    else
                        playerMotion.X = -1;
                }
                else if (tileW.TileOccupied)
                {
                    if (tileNWCollision && tileNW.TileBlocked || tileSWCollision && tileSW.TileBlocked)
                    {
                        playerMotion.X = 0;
                    }
                    else
                        playerMotion.X = -1;
                }
            }

            // Player Right
            if (keyState.IsKeyDown(Keys.D) ||
                (gamePadOneState.DPad.Right == ButtonState.Pressed))
            {
                player.CurrentAnimation = AnimationKey.Right;

                if (tileE.TileOccupied == false)
                {
                    if (tileNECollision && tileNE.TileBlocked || tileECollision && tileE.TileBlocked || tileSECollision && tileSE.TileBlocked)
                    {
                        playerMotion.X = 0;
                    }
                    else
                        playerMotion.X = 1;
                }
                else if (tileE.TileOccupied)
                {
                    if (tileNECollision && tileNE.TileBlocked || tileSECollision && tileSE.TileBlocked)
                    {
                        playerMotion.X = 0;
                    }
                    else
                        playerMotion.X = 1;
                }
            }

```

I have my tile detection setup so the 8 tiles around the sprite are the only ones detected. The collision variable is true if the sprites rectangle intersects with one of the detected tiles. The sprites origin is centered at 16, 16 on the image so whenever this point goes over to the next tile it calls the surrounding tiles.

I am trying to have collision detection like in the game Secret of Mana.

If I remove the diagonal checks the sprite will pass through thoses tiles because whichever tile the sprites origin is on will be the detection center. So if the sprite is near the edge of the tile and then goes up it looks like half the sprite is walking through the wall.

Is there a way for the detection to occur for each tile the sprite's rectangle touches?

# Answer
> 0 votes
You're determining whether each N/W/S/E direction is possible using the NW/NE/SE/SW checks, which keeps you from moving along a wall.

So, in your "up and left being held down" hypothetical, if extended to have a horizontal wall directly above the player, your code would have tileNWCollision set to true. I'm assuming that tileNW.TileBlocked is set somewhere else and basically means "this tile can't be occupied by the player".

If you look in your Keys.A handling, you'll see that having tileNWCollision and tileNW.TileBlocked both true means playerMotion.X is set to 0. However, assuming the player is moving within the grid, there's no reason that a wall to the *northwest* should prevent them from moving *west*.

**EDIT:**

So: I think you might get more traction on your problem here by instead constructing "next position" rectangles based on the input and checking those for collision with blocking tiles.

E.g., when moving north, create the rectangle representing what your player *would* occupy if you let them move. If it's valid (no collision), let them move (set playerMotion.Y as appropriate).

For multi-input, try a diagonal/combined rectangle first, and if it fails just tie-break however you want for the individual inputs.

This approach should prevent any off-by-one/directionality errors, and should also prevent the "walking through the wall" issue.

Sorry that this still isn't directly answering your question. :) Hope it helps.

# Answer
> 0 votes
If your diagonal movement will put your player inside a wall then test for the diagonal and vertical part of the movement individually. This allows for sliding along walls. Tips here: http://xnafan.net/2013/04/simple-platformer-game-in-xna-tutorial-part-four-simple-collision-detection/

Kind regards - Jakob

# Answer
> -2 votes
Maybe this thread could helps you: How can I use Rectangle.Intersect() to resolve collisions in XNA?

It describes how to resolve collisions in XNA. Thre is a video and source code. It helped me, when I had the same problem.

Direct Link to Source: http://pastie.org/3152377#103 Direct Link to Video: http://www.youtube.com/watch?v=5-D0PGdoDDY

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


# Question
Title: How can I handle shadowing of a planet's rings by the planet itself?
I assume the most straightforward way to draw planetary rings (such as those around Saturn) is to use a texture that is transparent everywhere except for the rings, and then place the planet in the middle of the texture and that's it.

The problem with this approach is that I don't know how to shadow the area of the rings texture that is behind the planet (which isn't lit by the sun). At the moment I have a rings texture that is permanently lit and a planet that darkens in the areas where it's not lit by the sun. The planet revolves around the sun, so the lit/shadowed areas are constantly changing.

Any suggestions on how to apply shadow on the rings?

# Answer
> 3 votes
Josh's answer is the "how to do it properly" answer.

My answer is the "the simplest thing that could possibly work" answer: Just draw the shadow straight into the ring texture, and now your ring appears to have received a shadow from the planet.

If your planet moves around the sun, then spin the ring so that the side with the "shadow" is always away from the sun, relative to the planet's current position.

This is going to be *heaps* easier than implementing shadow mapping, and will render faster, and will probably even look better due to increased texture resolution (compared against the resolution of the depth buffer you'll need for the shadow mapping).

# Answer
> 3 votes
Presumably you model the planet as a sphere. You can model the rings as a large quad that intersects the planet sphere (as you described) or as an actual ringed geometry object (with a similar kind of texture).

In both cases, if the planet is considered an occluding object in any kind of shadow mapping (or other shadow-handling technique that takes into account actual occluder geometry and light source position, that is, not simple "blob shadows"), the ring geometry can receive the results of the shadow mapping algorithm and appear in shadow behind the planet.

Shadow mapping is quite common, and while beyond the specific scope of your question, you can fairly easily find tutorials online for OpenGL, D3D, XNA and so on to get you started. The topic also comes up quite a bit on this site itself.

---
Tags: textures, opengl-es2
---


# Question
Title: What would a "2nd person" viewpoint consist of?
Traditional narratives have one of three viewpoints:

* First person (`I fought the monster`)
* Second person (`You fought the monster`)
* Third person (`He/She/It fought the monster`)

First and Third person viewpoints are very prevalent in video games, but I got to wondering what a Second person viewpoint would be like.

* First person (`'I' am the character, seeing through 'my' eyes`)
* Second person (???)
* Third person (`He/She/It is the character, seen through a third party's eyes`)

The only thing I can think of is a game where the viewpoint is a character you're *not* directly controlling, who is usually (always?) looking at the character you are. But how would that differ from a Third person perspective with a very limited camera?

# Answer
**First person** is the viewpoint of the subject. It's the *primary* viewpoint.

* If I fight the monster, then first-person is my perspective.

**Second person** is the viewpoint of the party interacting with the subject. It's the *secondary* viewpoint.

* If I fight the monster, then second-person is the perspective of the monster.

**Third person** is the viewpoint of a (possibly theoretical) party observing the interaction. It's neither the primary nor secondary viewpoint, but rather a third, disassociated viewpoint.

* If I fight the monster, then third-person is the perspective is neither mine nor the monster's but rather some outside observer.

*First person* is common in in 3D immersive games, particularly where seeing the action from the perspective of the character improves gameplay.

*Second person* is most typically seen in "instant replays" and other temporary cut-away scenes where seeing the action from the perspective of the target adds value.

*Third person* is the most common perspective, as it provides a view that encompasses more of the scene than either the subject or target alone can see. This includes side-view, over-the-shoulder view, top-view and many others.
> 14 votes

# Answer
When you see your character from afar, standing in front of a chest, you can think of him in three different ways:

1. I am standing in front of the chest.
2. My character is standing in front of the chest.
3. The character is standing in front of the chest.

Notice that it's not trivial (or probably possible, in my personal case) to think of him as an "you" as said by someone else. However, if someone else saw your character, their options would be as follows:

1. **You are standing in front of the chest.**
2. Your character is standing in front of the chest.
3. The character is standing in front of the chest.

A lot simpler now. That's because it's unnatural to view the world from someone else's perspective (sort of human nature I guess, we evaluate everything around us according to ourselves). In short, we can talk about ourselves and other things from our point of view. We can't talk about ourselves and other things from someone else's point of view.

There are certain ways to guide the player to adopt one of these points of view. For example, the first person camera helps the player think he's the actual character in the game. Same for narrators 'speaking' directly to the player.

The third person narration (as seen in Bastion and others) places the player far away from the character so that he is able to see a larger picture of everything involving and surrounding his avatar.

I do not believe it's possible to find such a trick to help with the 2nd person perspective, for the reason mentioned above.
> 3 votes

# Answer
As I personally would describe the different views:

* First person: You looking at the world from your own eyes. Your own point of view. Much like you naturally do in reality.
* Second person: You are looking at the world from the eyes of something else in the world. Or from the view of some other object. eg. You're watching your character through a security camera as he is walking down a hall.
* Third person: You are looking upon the world from the perspective of a nonexistent object. eg. Floating along behind yourself as you walk down the hall.
> 2 votes

# Answer
Second person would be from the view of what the character is interacting with. I actually came across a game today that demonstrates this: http://www.kongregate.com/games/himojii/second-person-shooter-zato
> 2 votes

---
Tags: view, third-person-view
---


# Question
Title: Faking 2d light using shader (Unity, Shaderlab)
Since the concept was difficult to explain in words for someone who's not quite familiar with shader, I described it in pictures.

I'm currently using Unity and it seems Shaderlab is the best choice to accomplish this.

To shader masters, this seems like quite a simple trick, but as beginner, I've been struggling to find right keywords and tutorials to accomplish this.

I wish someone could explain the concept behind this shader trick.

Thank you in advance.

# Answer
> 1 votes
The technique is called masking. Alpha is used as a mask to calculate how much of the original pixel's color gets in to the final image.

---
Tags: 2d, unity, shaders, lighting, masking
---


# Question
Title: Show the GUI button when mouse hover to the object
i already have this player on my screen. And i want, whenever the mouse hover at the object, the GUI button show itself (like tooltip). I tried below code, but the button is not showed up when i hover at the object. Here is my code:

```
void OnMouseEnter()

    {

        Rect buttonRect = new Rect(250, Screen.height - buttonHeight, textInfoPlayerButtonWidth, textInfoPlayerButtonHeight);

        if (GameManager.instance.currentPlayerIndex == 0) (the object)

        {

            if (GUI.Button(buttonRect, "This is player 1"))

            {

            }

        }

    }

```

I want to be like this:

But i want it to be show that GUI hovering button on that character, not when the character selected.

Thank you

# Answer
You can only call GUI functions inside `void OnGUI()`. So, make a boolean to indicate when the mouse is hovering on a character and flag that bool as true. Then in the `OnGUI` you have that tooltip wrapped:

```
void OnGUI()
{
    if(showCharToolTip)
    {
                if (GUI.Button(buttonRect, "This is player 1"))
                {
                }
    }
}

```
> 1 votes

---
Tags: c#, unity, turn-based
---


title: View to normal calculation in GLSL

text:
# Question
Title: View to normal calculation in GLSL
Sorry for the terrible title, but I really cant think of anything better.. Suggestions welcome.

I am trying to do something like showcased in this video:

http://www.youtube.com/watch?v=CaTI2d0tQME

So basically smoothly change the opacity when looked face-on.

This is my vertex shader so far, the fragment shader is simple as it just multiplies the lightColor with the texture:

```
#version 430 core

uniform mat4 MV;
uniform mat4 MVP;

layout(location = 0) attribute vec3 vertexPosition;
layout(location = 1) attribute vec2 vertexUV;
layout(location = 2) attribute vec3 vertexNormal;

layout(location = 3) attribute mat4 bufferMatrix; // For per-instance translation

varying  vec2 UV;
varying  vec4 lightColor;
flat varying int InstanceID;

void main(){
    vec4 mcPosition = MV * bufferMatrix * vec4(vertexPosition, 1.0);
    mcPosition = mcPosition / length(mcPosition);

    vec3 mcNormal = vertexNormal;

    vec3 ecNormal = vec3(MV * bufferMatrix * vec4(mcNormal, 0.0));
    ecNormal = ecNormal / length(ecNormal);

    float dotProduct = dot(vec4(mcNormal, 1.0), mcPosition);

    lightColor = vec4(dotProduct);

    gl_Position = MVP * bufferMatrix * vec4(vertexPosition, 1.0);
    UV = vertexUV;
    InstanceID = gl_InstanceID;
}

```

The base is copied code from a 'phong' shader - that works!.. I have tried everything I could think of, as well as searched google for quite some time.

I think I realize what I need to do mathematically, which is getting the dot-product of the vertex-normal on to the view-to-vertex vector. That is mathematically speaking, another is to do it in GLSL with matrices etc.

I am bad at debugging GLSL code, but right now the lightColor is always 0, no matter where I look at the model from.

**Quick Bonus Question:** What is the technique in the video actually called - if anything?

# Answer
The easiest think to do is to pass as a uniform the position of the camera in World-Space and calculate the direction from the vertex to the camera and then calculate the dot product between that direction and the vertex normal. The code would be something similar to

```
#version 430 core

uniform mat4 M;
uniform mat4 M_InvTransp;
uniform mat4 MVP;
uniform vec4 cameraPosition;

layout(location = 0) attribute vec3 vertexPosition;
layout(location = 1) attribute vec2 vertexUV;
layout(location = 2) attribute vec3 vertexNormal;

layout(location = 3) attribute mat4 bufferMatrix; // For per-instance translation

varying  vec2 UV;
varying  vec4 lightColor;
flat varying int InstanceID;

void main(){
    vec4 positionWCS = bufferMatrix * M * vec4(vertexPosition, 1.0);
    vec4 vertexToCamera = cameraPosition - positionWCS;
    vec3 direction = normalize(vertexToCamera.xyz);
    vec4 normalWCS = M_InvTransp * vec4(vertexNormal, 0.0);
    normalWCS.xyz = normalize(normalWCS.xyz);

    // if the face is facing the camera the dotProduct would be 1.0 so to make
    // the face trasparent multiply the texture with 1.0 - dotProduct
    float dotProduct = dot(normalWCS.xyz, direction);
    lightColor = vec4(1.0-dotProduct);

    gl_Position = MVP * bufferMatrix * vec4(vertexPosition, 1.0);
    UV = vertexUV;
    InstanceID = gl_InstanceID;
}

```

You should multiply the normal with the inverse - transpose Model matrix since if your Model Matrix is not an orthonormal matrix you would get incorrect results if you multiply him with the normal. Also the code will work only if your bufferMatrix contains only translation information and not rotation or scaling.
Keep in mind that a direction in a 3D space is defined by X,Y,Z components, so it is better to have the W component as zero when you normalize or calculating the length of the normal ( or not use it at all as in the code above ), otherwise you will get incorrect results.
> 1 votes

---
Tags: opengl, glsl, vector
---


# Question
Title: Universal Tween Engine - simulating time T instantaneously
I have a circuit in Universal Tween Engine in libgdx and I want to make several entities follow this path

, each behind the other, like body pieces of a snake. The problem is that I need to find the initial position for each piece. I could obtain this effect by setting every piece to one point and setting incremental delay times for each one, and when the largest delay ends, I have something like this, with the last entity at the origin point

The problem with this is that the full formed "snake" must be like this when the level starts, that means, time = 0. How can I achieve this instantaneously?

# Answer
Your problem is that you are using `t` **and** moving the time forward, in a parametric equation `t` represents any varying quantity and that doesn't strictly mean you should move the time forward. This can be simply achieved by writing an interpolation in a loop and increment `t` just at initialization time.

```
// call this at initialization time
int stepsCount = 10; // Change depending on the object count, assuming 10 objects here
float step = 1.0f/(float)stepsCount;
float t = 0.0f;
for (int i=0; i < stepsCount; i++, t+=step)
{
   // depending on your interpolation equation, just pass t as a param
   objectPos[i] = Interpolate( initPos, finatP, t);
}

```

This will set the position for each object depending on t, the first object when `t=0` will be at initPos, and when `t=1` the final object will be at the finalPos. In case you don't want the objects to span the whole interval, we need to scale the `step` accordingly.

```
// This is one way to do it
float step = 1.0f/(float)stepsCount;
step *= scaleFactor;

```

`scaleFactor = 0.5` will take half the interval. In case you want to determine the scaleFactor base on some position, you need to calculate it by taking the inverse interpolation, in other words you need to get the `parametric quantity` that represents that position on the line/curve.
> 1 votes

---
Tags: libgdx, tweening
---


# Question
Title: How to spawn an object on collision in box2d + love2d?
I'm trying spawn collidable debris from a ship when it explodes in love2d/box2d, however, World:isLocked() is true when collision callbacks are called:

> This will return true inside the callbacks from World:setCallbacks. (source)

So creating a new body throws an error. Are there any workarounds for this?

# Answer
The usual way to solve this is to create the objects once the physics-simulation has completed.

In your collision callback you would push all the objects you want to create into a list-like data-structure. Once your physics-simulation-step is complete (eg. *after* `world:update`), create the objects/bodies that have been pushed to the list (thereby removing them from the list, so that they don't get created multiple times).
> 1 votes

---
Tags: box2d, love2d
---


# Question
Title: How to determine if a 3D voxel-based room is sealed, efficiently
I've been having some issues with efficiently determining if large rooms are sealed in a voxel-based 3D rooms. I'm at a point where I have tried my hardest to solve the problem without asking for help, but not tried enough to give up, so I'm asking for help.

To clarify, sealed being that there are no holes in the room. There are oxygen sealers, which check if the room is sealed, and seal depending on the oxygen input level.

**Right now, this is how I'm doing it:**

* Starting at the block above the sealer tile (the vent is on the sealer's top face), recursively loop through in all 6 adjacent directions
* If the adjacent tile is a full, non-vacuum tile, continue through the loop
* If the adjacent tile is not full, or is a vacuum tile, check if it's adjacent blocks are, recursively.
* Each time a tile is checked, decrement a counter
* If the count hits zero, if the last block is adjacent to a vacuum tile, return that the area is unsealed
* If the count hits zero and the last block is not a vacuum tile, or the recursive loop ends (no vacuum tiles left) before the counter is zero, the area is sealed

If the area is not sealed, run the loop again with some changes:

* Checking adjacent blocks for "breathable air" tile instead of a vacuum tile
* Instead of using a decrementing counter, continue until no adjacent "breathable air" tiles are found.
* Once loop is finished, set each checked block to a vacuum tile.

Here's the code I'm using: http://pastebin.com/NimyKncC

**The problem:**

I'm running this check every 3 seconds, sometimes a sealer will have to loop through hundreds of blocks, and a large world with many oxygen sealers, these multiple recursive loops every few seconds can be very hard on the CPU.

I was wondering if anyone with more experience with optimization can give me a hand, or at least point me in the right direction. Thanks a bunch.

# Answer
The best solution will rely on multiple factors, like expected size of room.

1. Only do this checks, when something is actually changing.

Approach 1:

You could use an A\* to find a path from the vent to the tile above the vent / the vent itself or to a tile which is known as vacuum. If path is found, room is unsealed. This is not so different from your current approach but should be faster. Once found, make a "flood fill" to set the tiles as vacuum.

Approach 2:

Maybe your outer structure is less complex - considering, that there is a surface where under are the rooms, you do not need to move in all 6 directions, so you should be travel along the surface, mark every tile as vacuum which you travel.
> 3 votes

# Answer
When you do your recursive search, do you make sure you're not checking the same voxel multiple times? I couldn't tell from the way you described your algorithm, but you should have some kind of flag to indicate whether you've recursively expanded a voxel already, so you don't do it more than once.

And as Byte56 said, you should also only check for leaks when things change. That could greatly minimize the amount of work you do, depending on how frequently changes occur. You may even be able to cache information between successive calls to the algorithm, which can trivialize the amount of computation you do after the first call.

Edit:

I looked at some of your code. It seems like you're using a LinkedList to indicate whether a voxel has been checked already, as in my first paragraph. You may have better results if you use something other than a LinkedList for this. Perhaps try a HashSet or something? This should reduce the complexity of your check method from O(n) to O(1).
> 0 votes

---
Tags: java, voxels, recursion
---


# Question
Title: (Where) Can I learn to create art for my 2D games?
I'm currently bad at drawing. If I want to create something looking acceptable, it usually takes me hours and hours to fiddle around just to get the basic looks right.

I think that I'm not completely skill-less, I just lack simple drawing techniques..

* Am I a hopeless case?
* Where is a good place to start out in drawing for 2D games? I'd like to be able to create acceptably good backgrounds, terrains / tilemaps, characters and weapons

# Answer
Programming generally involves thought processes located in the left-hemisphere of the brain that handle logic, linear sequencing, and predictability. Drawing utilizes thought processes dealing with space, patterns (visual or otherwise), shapes, color, etc located in the right.

You probably got some instruction on the thought processes required to create a program. You will probably need some instruction on the the same for creating artwork.

I recommend first Drawing on the Right Side of the Brain by Betty Edwards to learn what the thought processes used by artists are; how they work; and importantly, how they *feels*. If you ever recognize being in the *flow* where your ability to code just continues effortlessly you have a sense of the way thinking can feel. The spatial and coordination thought processes required for drawing are not often used by programmers who develop using typical conventional practices and languages, and you can feel the difference when they're employed.

The second text I recommend is Kimon Nicolaides' The Natural Way to Draw. Different drawing techniques, exercises and intents will also help develop your innate ability to draw. And everyone has the ability to draw *well* once they understand how to draw.
> 6 votes

# Answer
You could try starting with **pixel art** by taking some graph paper and never violating the golden rule of "one colour per square." The alternative to using graph paper is a graphics editing application like Adobe Photoshop and it's "zoom" feature.

With practice, you can keep reducing the total number of different colours used and still make really nice images.

I've included two contrasting examples of pixel art below, the first one being a very simple one of some cherries, and the second one being an amazingly complex one (to see it in detail, you may need to right-click on it and choose "Open"). For more examples of pixel art, use Google's Image Search: http://images.google.com/images?q=%22pixel+art%22
> 4 votes

# Answer
My biggest piece of advice for this is that *acceptable* art isn't good enough to create a successful game.

That said, if you *can* create something that looks right to an honest 3rd party after hours of fiddling then you're not a hopeless case, you just need practice.

There are three things I suggest you do for practice:

* Find a local art school, if you can, and take a basic drawing class to learn basic techniques
* Practice drawing real scenery and objects **to scale and in full**
    + Try to practice on larger paper (11"x17" or larger), and fill the page
* Find pieces from artists you like and try to replicate them

The more you practice with real scenes, the less time it will take you to create acceptable results. There's no easy way out of this, unfortunately. Furthermore, the more art styles you can absorb, the more stylistic tools you will have to apply to your game.

In terms of specific tools for 2D game art, you can't go wrong with Adobe Photoshop, or the GIMP if you're on a budget. Generally you can either scan a real-life drawing and work with that as a basis, use a graphics tablet system to draw directly into Photoshop, or a combination of the two.
> 3 votes

# Answer
A great place to start learning is by modifying existing artwork rather than starting from scratch. Find something that's sort of what you want, and modify it to be what you want.
> 1 votes

# Answer
**Check out two sources**

http://ctrlpaint.com/ http://www.proko.com/

The first has a vast video library with great info on digital painting. You will learn the process and the tools.

The second has great info on human anatomy and drawing portraits and figures.

But, the main problem is: **you wont get good enough without unreasonable amouts of tiem and hard work**

If you have a job or university to go to, AND you are making your own games, you already have enough work on your hands. Learning to make art is **hard work** and lots of it. The sites I recommended often tell you that you need to be patient, that you need to draw everyday for 1-2 hours at the minimum, and you will have to work for months for substantial improvement.

Im playing around with varous forms of art as a side hobby, and after a year or so, my work is nowhere near worth putting into a game.

**The problem with learning art**, from a programmers point of view, is that you cant understand it just by reading and seeing it done. If you see some code, have it explained to you, and you can reference it while making your own attempt at the subject, you can get good at it very fast and produce reasonable results quickly. In art, you can intelectually understand the process, but it is not enough to go through it yourself. You have to teach you brain a subconcious understanding of form and lighting, and you have to acquire needed control over what you draw. This can be only done through work work work.

Working in 3D is the same, just harder, because drawing in 2D is almost a prerequisite for 3D work.

And **even if** you could produce a piece of acceptable quality having little training and experience, it wont be worth the time investment. In the time you make the piece you could write code for someone to earn enough cash to hire an artist.

**Learning art is fun, but only if its a goal itself.** You see it as a means of acquiring art for your games, "you're gonna have a bad time".
> 1 votes

---
Tags: 2d, sprites, art
---


# Question
Title: How do I implement collision detection with a sprite walking up a rocky-terrain hill?
I'm working in SDL and have bounding rectangles for collisions set up for each frame of the sprite's animation. However, I recently stumbled upon the issue of putting together collisions for characters walking up and down hills/slopes with irregularly curved or rocky terrain - what's a good way to do collisions for that type of situation? Per-pixel? Loading up the points of the incline and doing player-line collision checking? Should I use bounding rectangles in general or circle collision detection?

# Answer
You should read this guide Implementing Slopes

It is quite detailed and even though I haven't programmed slopes yet it has a lot of useful information and tell you not only ways of doing it, but you'll also find out how they were made on games you know well, so that's always a plus :)
> 1 votes

# Answer
If you want to apply real physics, you have to use physical engine. You can make your own physical engine but it implies a huge physical and programming knowledge. I would recommend you to use Box2D which is a good 2D physical engine written in C++. There are lot of tutorials about Box2D from which you can learn it easy and quickly. Here is also the official manual for it.
> 0 votes

---
Tags: collision-detection, sdl
---


title: Does OpenTK work in Windows 8?

text:
# Question
Title: Does OpenTK work in Windows 8?
While looking up OpenTK, I found a couple of references to threads that talk about Windows 8 support:

Is there a definitive answer to this?

# Answer
> 3 votes
Yes.

I'm doing some creative coding on OpenTK's current version on Windows 8, and I can confirm it works just fine.

---
Tags: opentk
---


# Question
Title: Implementing skeletal animation and GPU skinning (DOOM MD5)
**DISCLAIMER**
This question has been completely rewritten to narrow the scope of the question in light of previous suggestions and answers, but the same problem still persists.

Currently I'm trying to implement skeletal animation (GPU skinning) in my project.

So far I have achieved single joint translation and rotation, and multi-jointed translation. The problem arises when I try to rotate a multi-jointed skeleton.

At the moment I'm following quite a few sources in trying to implement skeletal animation. The MD5 spec, a blog post with source code and I've also seen many other tutorials.

Currently when I try and load the popular "Bob Lamp" model, I get this result.

Some information about my implementation:

* My maths is ordered with "vector to the left"
* The vectors and rotations of animation frames are being converted into matrices
* I pre-multiply the inverse bind pose and pose matrices

Here is my shader code.

```
#version 330 core

smooth out vec2 vVaryingTexCoords;
smooth out vec3 vVaryingNormals;
smooth out vec4 vWeightColor;

uniform mat4 MV;
uniform mat4 MVP;
uniform mat4 Pallete[55];

layout(location = 0) in vec3 vPos;
layout(location = 1) in vec2 vTexCoords;
layout(location = 2) in vec3 vNormals;
layout(location = 3) in int vSkeleton[4];
layout(location = 4) in vec3 vWeight;

void main()
{
    vec4 wpos2 = vec4(0.0);
    vec4 norm2 = vec4(0.0);
    vec4 wpos = vec4(vPos, 1.0);
    vec4 norm = vec4(vNormals, 0.0);
    vec4 weight = vec4(vWeight, (1.0f-(vWeight[0] + vWeight[1] + vWeight[2])));

    mat4 BoneTransform = mat4(0.0);
    for(int i = 0; i < 4; i++) {
        float fW = weight[i];

        if(fW > 0) {
            int jI = vSkeleton[i];
            vec4 tmpPos = wpos * (Pallete[jI]);
            wpos2 += fW * tmpPos;
        }
    }

    wpos2 /= wpos2.w;

    vWeightColor = weight;
    vVaryingTexCoords = vTexCoords;
    vVaryingNormals = normalize(vec3(vec4(vNormals, 0.0) * MV));
    gl_Position = wpos2 * MVP;
}

```

Another peculiar thing to mention is that multi-jointed animation works when the vertices are inline with the bones. As soon as the vertices move away from the bones, they deform incorrectly.

**UPDATE**
In response to @MickLH

My shader code now has `wpos2 /= wpos2.w` after the for loop. This is the result.

# Answer
> 1 votes
Your layout is illegal, vSkeleton\[4\] needs 4 indices since it is a 4-part array.

```
layout(location = 3) in int vSkeleton[4];
layout(location = 4) in vec3 vWeight;

```

should be:

```
layout(location = 3) in int vSkeleton[4];
layout(location = 7) in vec3 vWeight;

```

or better yet you should use glGetUniformLocation and let the GLSL compiler assign them for your:

```
in int vSkeleton[4];
in vec3 vWeight;

```

# Answer
> 1 votes
I'm not sure if this will solve your problem, but at least I can point some lines in your code, that I don't belive are correct.

First of all, you need to decide how you're going to multiply your matrices and vectors, i.e. are you going to use the left-side or right-side convention. In your shader code you have this line:

```
wpos = BoneTransform * wpos;

```

which suggests "vectors on the right", but then you have this:

```
gl_Position = wpos * MVP;

```

so it simply does not match. So, you either need to change the first on or the second one. But does it matter which one? Since you're calling your matrix `MVP` I will assume that this is equal to

```
ModelViewMatrix * ProjectionMatrix

```

and in that case you should probably use the "vectors on the left" convention. It's not very common but that's totally fine to me. So it may look like the only thing you need to fix is `wpos = wpos * BoneTransform`. Indeed, the formula

```
BoneTransform += (invBindPose[vSkeleton[i]] * Pallete[vSkeleton[i]]) * weight[i];

```

is good enough for left-side vector multiplication, at least if the `Pallete` matrices are computed the right way, but are they?

In fact, this is determined by the `MD5mech` file format itself. I've look throught their documentation but I'm not entirely sure which convention they're actually using. BTW, because of this ambiguity, it's always better to use `4x4` matrices than quaternion + vector pair. In your situation this is a matter of checking wheter you should use `pqi` instead of `pq` in the formula

```
Math3::quat::RotateVector3(rpos, pq, jv);

```

or not. Also another line

```
Math3::quat nq = pq * jq;

```

could be `nq = jq * pq` as well, so in fact you have at most 4 cases to check. Probably the easiest way to go is to expermient, but I would encourage you to look in the source code of the `Math3` library to determine if their `RotateVector3` routine behaves as described in the `MD5mesh` docs.

Also have in mind that there are at least two conventions to store quaternions in memory, which differ in the order of quaternion's coordinates. The natural one is `w,x,y,z` but I've observed that some engines/libraries tends to place the `w` coordinate at the end of the sequence. That is usually fine, unless you're forced to convert from `vec4` to quaternion or vice-versa. From my experiance it can be a real pain to look for errors of this type, so be carefull with that.

@akaltar Please note, that `*=` is used for composing transformations. Here we only want to compute a baricentric combination of some affine transformations, so in the formula for `BoneTransform` the use of `+=` is totally fine.

# Answer
> 0 votes
**1.** `normalize(weight);` is wrong as it does not make the components add up to one, it makes the length of the vector one which is not what you want. But as you do not use it's return value this line doesn't do anything. This line is probably not required from what I understand of your setup.

**2.** `BoneTransform +=` makes no sense. Adding matrixes together does not concatenate the transforms, you need to multiply them. But this isn't correct for another reason:

You may not apply bone weights to the transformations, you have to apply them to the transformed vertex:

```
for(int i = 0; i < 4; i++) {
    if(vSkeleton[i] != -1) {
        if(i == 0) {
            BoneTransform = ((invBindPose[vSkeleton[i]] * Pallete[vSkeleton[i]]) * weight[i]);
            // BoneTransform = ((Pallete[vSkeleton[i]] * invBindPose[vSkeleton[i]]) * weight[i]);
        } else {
            BoneTransform += ((invBindPose[vSkeleton[i]] * Pallete[vSkeleton[i]]) * weight[i]);
            // BoneTransform += ((Pallete[vSkeleton[i]] * invBindPose[vSkeleton[i]]) * weight[i]);
        }
    }
}

wpos = BoneTransform * wpos;

```

Has to look more like this:

```
wpos = 0.0;
for(int i = 0; i < 4; i++)
{
    if(vSkeleton[i] != -1)
    {
        BoneTransform = invBindPose[vSkeleton[i]] * Pallete[vSkeleton[i]];
        wpos += ( BoneTransform * vec4(vPos, 1.0) ) * weight[i];
    }
}

```

This is one reason why hlsl's mul function is better thant glsl's * operator. You may not switch around the operands when doing (matrix * vector) * scalar.

I'm not sure if I caught all the problems. There could still be problems on the cpu side and how your pass parameters. Let me know how it goes

**3.** PERFORMANCE: You should remove the binding pose from the bone transformation on the cpu. This has to be done for each vertex on the gpu and only once for each bone when done on the cpu.

---
Tags: c++, opengl, animation, glsl, skeletal-animation
---


# Question
Title: Finding a way to display objects efficiently
I am making a 2D simple Breakout game, and I would like to know of an efficient way to display all the blocks on the screen. I was thinking of dividing the whole screen into little squares that can be occupied by a block or a wall (or most objects). Is this the best way of doing it? Sorry if my question is kinda noob-ish, I just started learning to develop games.

# Answer
Before all else, you should make sure you need efficiency before you go about trying to implement it. Although it's possible you (non-)architecture yourself into an irrecoverable situation and have to essentially start over, that's not really a problem. You will waste more time pondering the best way to implement something than implementing it once, learning some lessons, and re-implementing. A big refactor is ok.

Onto the direct answer:

For a 2D XNA game, you will get a great deal of efficiency simply by using `Spritebatch` correctly. It will manage everything involved in minimizing draw calls, etc., so long as you use it as intended. Create a sprite sheet and draw subsections of it, call `Begin()` only once, don't use the immediate mode, and don't change textures while drawing everything. If you follow those guidelines (and research if they're unclear), you won't suffer drawing-related performance problems.

If you need to do something more exotic for any purpose, you can generate your complete set of 2D quads and draw them all at once from a single buffer. That's also fast.
> 1 votes

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


# Question
Title: Show the tooltip when mouse over at the object unity3d
i wanted to show the tooltip like this when the mouse over at the object, here is the example image:

and

i already tried this below code, but the message on the debug.log didn't showed up when i am hovering my mouse to the object, the object i give the name same like this:

```
void Update()
{

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    RaycastHit hit;

    if (Physics.Raycast(ray,out hit) && hit.collider.gameObject.name == "Yify")
    {

        Debug.Log("Yify");

    }

}

```

And here is my object (i use List to multiple the objects and each object i gave the name), (The object's name "Yify" is on the right side, dark green color):

Please help. Thank you!

Update:

i already got the script that hold movement and attack logic like the image that shown below sir @Korchkidu:

# Answer
> 1 votes
You can add colliders to your objects. Then, each time the mouse "enters" the collider, it calls `void OnMouseEnter()`. When the mouse exits, it calls `void OnMouseExit()`. So just create a script like:

```
using UnityEngine;
using System.Collections;

public class TestHover : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {

    }

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

    }

    void OnMouseEnter()
    {
        Debug.Log("Entering");
    }

    void OnMouseExit()
    {
        Debug.Log("Exiting");
    }
}

```

Finally, drag and drop this script onto your objects and it should work.

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


# Question
Title: Programming and drawing to deal with different screen sizes and resolutions
I started making an XNA game years ago and picked it up recently.

I'm looking later to convert it to use Monogame so that it can be deployed on various mobile devices and OS, though I have a sinking feeling that a lot of the sprites and code will be broken by the changing screen sizes when I move outside of the emulator.

The game is currently hard coded to to 800x480 and the level placements and sprite sizes were all done to fit that at the time.

So question:

What do I need to ensure this works and displays properly on a variety of screens and devices?

# Answer
Just scale all of your textures to the ratio of your original 800x480 to the size of their screen.

e.g. if their screen is 1600 x 900

1600 / 800 = 2

900 / 480 = 1.875

scale everything's X by 2 and Y by 1.875, and multiply all positions by the scale.
> 1 votes

---
Tags: xna, 2d, monogame
---


title: Make fast thing look slow (Box2D)

text:
# Question
Title: Make fast thing look slow (Box2D)
I'm working on a game that you control a trebuchet to throw balls to the opponent.

It's like a game called 'Medieval Siege'. When the trebuchet is swinging its arm, player need to seize the best moment to press button and release the ball. Then the ball will fly at the tangent angle. My problem right now is that the trebuchet arm swing too fast for player to seize the right moment. Meanwhile it has to be this fast otherwise it can't throw far enough. And there is a tiny string connecting the ball and trebuchet arm, if the arm swing too slow, the ball is just hanging on the string when the arm move.

I solve the problem by toggling step size, whenever the arm is swing, I change step size from 1/60 to 1/200. And once player release the ball, it's back to 1/60.

This works pretty good except my game is for multiplayer with networking. So changing step may cause problem.

Another solution I can think of is to allow it swing slow, but when player release the ball, I manually add velocity onto the ball while keeping its direction. I don't really like this solution cause it looks fake and I still have the problem that the ball is just hanging on the string, unless I make string very very short..

Please shed some light on this, thanks!

---

EDIT

Thanks for everyone's input, I solve the problem by making the arm swing slow and when player release the ball, grab ball's velocity and times two. It looks exactly the same as changing step size. There's just one extra thing I need to do. Because the arm is swinging really slow, the ball is just hanging on the arm end instead of swinging. I solved this by applying a force equal to the gravitational force on the ball during and only during the swing period. Then it no longer hang there but swing together with arm.

@MrCranky 's answer is detailed and looks doable, so I'd accept it. :)

# Answer
> 3 votes
Instinctively I'd say that we're missing a substantial part of the context needed to answer, which is "why does the multiplayer aspect prevent you from changing the timestep?"

If you are trying to share a physics simulation over a network connection, well, that's usually a pretty hard thing to do. The simulations diverge very easily, and especially with network connections that can lose packets, it's very hard to keep things together.

The simple and most robust answer to your question is to use a variable timestep. When you approach the moment of decision, instead of updating your physics simulation by one second for every real-world second that passes, update it by half a second, or another suitable number. As it's an integration effect, you'll probably be able to get away with simply snapping the update rate down to the lower rate during the decision window, but you can also interpolate quickly downwards to the lower rate. Either way, you are essentially playing back the physics simulation in slow motion. It should behave perfectly accurately, just slow enough that the player can make their decision. I wouldn't consider any other means of fudging the physics to make it work, they'll most likely all work out horrible and not feel 'right'. Keep the physics pristine, and counter the decision window problem outside of the simulation.

So we come back to the networking implementation. Without further information, I'd guess you have two choices. Firstly, if you're operating in lockstep with the other networked party. So when one player has to slow down to make their decision, slow down both players equally. This will probably feel annoying and weird for the player who isn't firing, because it'll confuse their own reaction times.

For the second, imagine two trebuchets firing at each other. The trebuchet takes 10 seconds to throw, and the firing window starts at T+5s. P1 starts the firing cycle at T+0s, and at T+5s slows their local physics simulation down by 50%. It'll take them 15s to play through the whole cycle. So at T+5s, P1 tells P2 to start playing back the 10s launch cycle ***at full speed***. So P1 sees the trebuchet cycle take 15s, P2 sees it take 10s, but both players see the cycle finish at T+15s. When P1 actually releases, they tell P2 when in the notional cycle they released. So if P1 releases at T+10s, that's actually at 7.5s through the 10s launch cycle. P2 can then show the release at T+12.5s (7.5s into its local playback of the cycle), and both players simulations should have launched the projectile at the same physical point in the cycle.

So in this second approach, you're no longer simulating in lockstep. You're running two independent simulations, but tracking player inputs instead. If both are told that the player released at 7.5s into the launch cycle, they should both agree on where the projectile will land. In practice though, that's likely to diverge very fast, and you're going to need to synchronise simulation states somehow.

# Answer
> 0 votes
Why not just copy/adapt what already exists and works in similar cases?

# Answer
> 0 votes
If your trebuchet is moving too fast, the obvious solution would be to scale time to make it slower. That is, for every second of real time, make only e.g. 0.1 seconds pass in your physics simulation. Now, from the player's viewpoint, the ball will be moving 10 times slower.

Actually, there's another way you can achieve the same effect: instead of scaling time, just scale all your physics constants that are in units including time. For example, gravitational acceleration has units of speed / time = distance / time², so if gravity is the only constant in your game, scaling it down by a factor of 100 = 10² achieves the same effect as slowing down time by a factor of 10.

Of course, if your physics model includes other constants with units of time (or speed = distance / time, or acceleration = distance / time², etc.), you'll have to scale those too if you want to keep the trajectories the same.

Note that there's a limit to how far you can practically go with this: if you slow time down by, say, a factor of 100, your trebuchet will be really easy to control, but your players are also likely to get bored waiting for the balls to slowly float down after firing them. If that's an issue, you may need to resort to more advanced tricks like those suggested in other answers, such as using really slow time scaling while the trebuchet is firing, but switching to a faster time scale once the ball has been launched.

---
Tags: physics, box2d, physics-engine
---