# Question
Title: OpenGL light appears to move with camera and changes with object rotation
I have a working open gl es 2.0 3d engine (my own) that I've used in several iOS apps. I recently noticed that on a mutli-symmetrical object the lighting didn't look the same at each rotation. For example, I would think this 6 sided object's illumination (think throwing star) should appear exactly the same at 0 deg and 60, 120, 180, 240 and 300. Apparently in my other games I haven't done the same types of rotations that I'm doing in this app. So I never noticed this issue.

Digging deeper and trying to debug the issue I found two symptoms. Each might have it's own source problem.

For testing I created a solid color polyhedron. I also simplified the shader and removed shadow mapping and set the normal map to 0,0,1 (in the texture 127,127,255). Also in the code below I'm only displaying the diffuse component to try to debug things, but have included my full shading code.

**Problem 1** is that when the object rotates the lighting changes. In the screenshot the light and the camera are right above the object. Therefore at 0 deg and 180 deg the illumination on each face should appear the same. But 180 deg is brighter. In between it ramps.

FYI: The shadow in all these screenshots is a representation of where the light is coming from. The shadow map is being rendered on the paper only.

**Problem 2** is that when the camera is moved the light appears to move with the camera. After some testing I know why this one is happening (below).

Here's all the code. First the vertex shader:

```
precision highp float;

uniform mat4 u_modelViewProjectionMatrix;
uniform vec3 u_lightPosition;
uniform mat3 u_normalMatrix;
uniform mat4 u_matrix2;

uniform vec3 u_cameraPosition;

attribute vec3 a_vertexPosition;
attribute lowp vec2 a_vertexTexCoord0;
attribute lowp vec3 a_vertexNormal;
attribute lowp vec3 a_vertexTangent;

varying lowp vec2 v_fragmentTexCoord0;
varying lowp vec2 v_fragmentTexCoord3;

varying vec3 v_eyeVec;
varying vec3 v_lightVec;
varying vec3 v_position;

void main(void)
{
  v_fragmentTexCoord0 = a_vertexTexCoord0;
  v_fragmentTexCoord3 = a_vertexTexCoord0 - vec2(0.0, 0.5);  // normal is down half

  gl_Position = u_modelViewProjectionMatrix * vec4(a_vertexPosition,1.0);

  lowp vec3 normal = normalize(u_normalMatrix * a_vertexNormal);
  lowp vec3 tangent = normalize(u_normalMatrix * a_vertexTangent);
  lowp vec3 bitangent = cross(normal,tangent);
  mat3 TBNMatrix = mat3(tangent, bitangent, normal);

  //mat3 TBNM2 = mat3(a_vertexTangent, cross(a_vertexNormal,a_vertexTangent), a_vertexNormal);

  //----------------- Compute Eye vector ---------------
  v_eyeVec =  u_cameraPosition - a_vertexPosition.xyz;
  v_eyeVec *= TBNMatrix;

  //----------------- Compute Light vector ---------------
  v_lightVec = u_lightPosition - a_vertexPosition.xyz;
  v_lightVec *= TBNMatrix;
}

```

Fragment Shader:

```
precision highp float;

uniform sampler2D u_textureSampler;
uniform sampler2D u_textureSampler2;

uniform lowp vec4 u_lightColorAmbient;
uniform lowp vec4 u_lightColorDiffuse;
uniform lowp vec4 u_lightColorSpecular;     // the specular is now a map
uniform float u_shininess;

varying vec3 v_eyeVec;
varying vec3 v_lightVec;
varying lowp vec2 v_fragmentTexCoord0;
varying lowp vec2 v_fragmentTexCoord3;

void main(void)
{

  lowp vec4 baseColor = texture2D(u_textureSampler,v_fragmentTexCoord0);
  lowp vec4 normColor = texture2D(u_textureSampler, v_fragmentTexCoord3);
  lowp vec3 norm = normColor.rgb * 2.0 - 1.0;

  // how shiny is: specular map range (0-1) represents 100 through u_shininess. 1.0 = u_shininess, 0.0 = 100...
  float specularMap = 100.0 - (100.0-u_shininess)*normColor.a;
  // baseColor.a is the specularFactor of how much shininess to apply, to dull things down

  vec3 lightVector = normalize(v_lightVec);
  float lamberFactor = max(0.0, dot(norm, lightVector));

  vec3 diffuseComponent  = vec3(0.0,0.0,0.0);
  vec3 specularComponent = vec3(0.0,0.0,0.0);

  if (lamberFactor > 0.0)
  {
     vec3 halfVector = normalize(v_lightVec + v_eyeVec);
     float specularPower = min(1.0, max(0.0,pow(dot(norm, halfVector),specularMap)));  //baseColor.a is a spec factor texture

     diffuseComponent  = u_lightColorDiffuse.rgb  * baseColor.rgb * lamberFactor;
     specularComponent = u_lightColorSpecular.rgb * baseColor.a * specularPower;
  }

  vec3 ambientComponent = u_lightColorAmbient.rgb  * baseColor.rgb;

  // normally I would do
  // gl_FragColor = vec4(ambientComponent + (diffuseComponent + specularComponent) ,1.0);

  gl_FragColor = vec4(diffuseComponent ,1.0);
}

```

iOS code is passing these uniforms:

```
u_lightPosition = vec3Make(lightPos.x-thisItem->currentPos.x, lightPos.y-thisItem->currentPos.y, lightPos.z-thisItem->currentPos.z);
u_cameraPosition = vec3Make(cameraPos.x-thisItem->currentPos.x, cameraPos.y-thisItem->currentPos.y, cameraPos.z-thisItem->currentPos.z);

u_normalMatrix = getMat3FromMat4(mModelView);

```

**Tests**

Problem 2 hypothesis - the camera moving shouldn't effect the lighting but it does because the normal is being multiplied by the normal matrix. I understood that the normal matrix is the same as the modelView when using uniform scaling. But the camera move is in the view matrix. So by replacing the above with:

```
u_normalMatrix = getMat3FromMat4(thisItem->objMatrix);

```

..the light no longer moves with the camera and that problem appears to go away. But that's not what I've read is the right way to do it. And it doesn't solve problem #1. It also seems like the specular light would need the modelView to be right and not just the model matrix.

**UPDATE:** To clarify things here a little more regarding coordinate systems. All objects, the camera, and the light are stored in world coordinates. The Z axis has numbers getting smaller as they go away from camera. In this particular case the camera is at 160.0 and the paper is at 100.2861 which is a calculated depth for a 1:1 pixel unity. The light is about 131, between the camera and the paper. The object is about 8 units in diameter.

When I draw objects, currently the object matrix starts at identity and gets scaled, rotated and transformed to it's world coordinate location. The mView is created using a `lookAtMatrix(cameraPos, camLookAt, camUpVector, mView);` function. which creates an inverted matrix of it's position and location in world coordinates. As you can see above the light position is provided to the shader in model space but without regard to the camera position or rotation. The camera location is also provided to the shader in model space without regard to it's rotation.

I could move the camera to 0,0,0 and in this app because of the setup math everything would automatically push farther away to appear the same. I don't know if it's better to always have the camera there or not.

In all my other games the camera is always parallel to the scene, and in this app it will be also. But I want to solve this so I have a working system for moving and rotating the camera anywhere.

Regarding problem #1. It's almost as if the normals are getting bent weird by the TBN when the object rotates. That's the more important of the two issues for me at the moment.

**UPDATE 2:** The test was a clue but wasn't correct. Rather than removing the view matrix from the normal matrix I needed to add it to the light position to get it in camera/eye space. That way when the camera rotates it gets applied to the light. Then as the answer suggests, I also needed to use modelView in the shader to get a version of the vertex in that space as well. Then with the vertex, camera, and light in eye space I calculate the eye and light vectors.

At the moment I'm still having issue #1 above where I get different lighting results on a rotated symmetrical object. Help on that issue is still appreciated.

**FINAL UPDATE:** After much testing with setting `gl_FragColor` to various variables. I finally figured out that it was because I was normalizing the light vector before getting the dot product to determine the lamber factor. So here this:

```
  vec3 lightVector = normalize(v_lightVec);
  float lamberFactor = max(0.0, dot(norm, lightVector));

```

needed to be replaced with just:

```
  float lamberFactor = max(0.0, dot(norm, v_lightVec));

```

That solved it.

# Answer
From what I read from the shaders the light is in world-space and the light calculation is done on the object in part in untransformed object-space.

You need to compute your lighting with both light & model in world-space or both in camera space.

Whenever moving the camera messes up the lighting it means some of the data is calculated in a different space from the rest.

```
(a_vertexPosition.xyz)

```

is in object space (before the object is placed in the 3D world).

```
(a_vertexPosition.xyz * modelmatrix)

```

is in world space.

```
((a_vertexPosition.xyz * modelmatrix) * viewmatrix)

```

is in view (camera) space.

```
(((a_vertexPosition.xyz * modelmatrix) * viewmatrix) * projectionmatrix)

```

is in screen space (just before perspective).

```
vec4 temp = ((a_vertexPosition.xyz * modelmatrix) * viewmatrix) * projectionmatrix;
temp /= temp.w;

```

is in projected screen space. The GPU does this division by w just before the pixel shader. Sometimes you need to calculate this in the vertex shader to do 2D effects.

To calculate the lighting properly you probably need to use (a\_vertexPosition.xyz * modelmatrix) instead of plain a\_vertexPosition.xyz for calculating the light and camera vectors.
> 6 votes

---
Tags: opengl, 3d, matrix, opengl-es2, lighting
---


# Question
Title: Algorithms for positioning rectangles evenly spaced with unknown connecting lines
I'm new to game development, but I'm trying to figure out a good algorithm for positioning rectangles (of any width and height) in a given surface area, and connecting them with any variation of lines. Two rectangles will never have more than one line connecting them.

Where would I begin working on a problem like this? This is only a 2 dimensional surface. I read about graph theory, and it seems like this is a close representation of that. The rectangles would be considered a node, and the lines connecting them would be considered an edge in graph theory.

# Answer
> 1 votes
It sounds like you are looking at an unusual problem for games: given a bunch of rectangles with connecting edges, lay them out so that no rectangles or edges (*I'm guessing*) overlap. Usually the layout happens during map generation, which means it's trivial.

The general problem, of laying out a planar graph with a set of goals (minimise overlaps, edge lengths as even as possible) is a major field of study within Graph Drawing. People write papers on this stuff, and that may be cool, but might be a bit heavy for someone new to game development.

Therefore I suggest you **take an existing graph layout algorithm**, and modify it to **include the rectangle overlap criterion**. Depending on how well you want to do it, it might be trivial, or you might need to dive into the bowels of the algorithm.

Keep in mind that you are by no means guaranteed no overlaps; recall the three utilities puzzle that has no solution (but never fails to confound the internet).

Here's one way you could do it; one of the simplest graph layout algorithms to understand are force-directed ones - they simulate the graph as nodes that repel each other and edges that are spring-like and try to become as short as possible. There's even an open source javascript version called **springy.js** here (GitHub, demo):

You could do one of two things with this:

* Add edges with lengths long enough to guarantee the rectangles don't overlap. You may end up with a very sparse layout if you have elongated rectangles, however.
* In the `tick` function, add a function that applies a large repelling force if you detect that rectangles overlap.

Unfortunately, classic force-directed graph layout algos don't resolve edge overlaps well. Fortunately due to its dynamic nature, it's sensitive to initial conditions, so you can run the algorithm repeatedly until you get a nice result.

---
Tags: javascript, algorithm, html5, graph
---


title: How to set "near" value properly?

text:
# Question
Title: How to set "near" value properly?
Usually, the camera's `near` value is set to sth like `0.1f`. However, this (assuming `1.0f = 1 metre`) makes everything that's closer than `10 cm` from the camera invisible. On the other hand, when working with big open terrains too small `near` value results in this (yes, that's a sandy coast and water :P):

instead of this:

(Apparently, when the difference in distance between too objects is too small, you get artifacts. Something to do with precision, I guess, and apparently the precision is dependent on the `near` camera value.)

My question is - is it possible to set `near` value to something like `0.001f` and **not** get the above artifacts?

# Answer
If you need to go nuts you can render the scene twice with two cameras, first with a camera set to near=100.0f far=10000.0f and then use a different depth buffer and render on top of the color buffer with another camera with near=0.01f and far=100.0f (unless you need to smoosh your character's nose into a wall closer than 1cm, that should be close enough)

You can switch model and environment LODs between the two passes and skip a whole bunch of objects in the far pass.

With this you can also render the far camera at half-resolution, and blur everything as a cheap depth of field effect by sampling it between the pixels, optionally add a little depth overlap (put near at 75m for the far camera) and blend the two frame buffers for pixels of the near camera that falls into the 75m to 100m range.

You may have to sample both depth buffers to figure out the real depth of any pixels for your post effects.

Cheers,
> 2 votes

# Answer
The artifacts are happening because the resolution of your depth buffer. The near and far values are not only clipping values but also set the resolution of the depth buffer.

Think of the depth buffer as an encoded image, where instead of storing color in RGB you are storing a depth value in the memory. Each fragment in the buffer will have a range from near to far. There are only a set number of steps in that range. If the near and far are too far apart, say near is .01 and far is 10000.0, the steps will be larger (unit wise). If the near and far are closer together, say 1.0 and 100.0, the steps will be smaller (unit wise). So to increase the resolution of the steps and to get more differentiation between objects rendered at different depths, decrease the range between near and far.

Side note - In reality this is a little bit misleading. Because the projection matrix will convert the depth to a range of -1 to +1. So the actual range in clip space is always the same of -1 to +1. And the precision of how many steps there are and if those steps are linear or logarithmic... let's just say I don't know that.

But practically speaking, there is a limit to the number of steps. So reducing the range between the near and far values will make more use of those steps by lowering the amount between one step and the next.

In the scene above if your focus is on the water and that is 100 units away from camera, maybe you don't need the near to be any closer than 50 away from camera. And if you can't see beyond the ground maybe you don't need the far to be farther away that 150. Of course it depends on your whole scene.

In one of my games to gain depth buffer resolution I take the focus point (my main space ship) and I set the near to -125 and the far to +125, clipping the near at 1.0.

And Stephane's answer sounds like a good way of handling it if you need more depth range than what you can get from the built in depth buffer.
> 1 votes

---
Tags: camera, frustum
---


# Question
Title: How to pick a 3D object with known mouse coordinates if the camera is rotated 60 degrees?
I am making a simple game engine for a simple RTS game and would like to be able to pick a cube and move it around with the mouse coordinates. The problem is that my camera is rotated 60 degrees just like any RTS game and I am not sure how to use gluUnProject..

Thanks in advance!!

# Answer
> 4 votes
Fundamentally, "what part of the world is under my cursor" is actually a problem of **collision detection** -- in terms of code, there's no difference between checking what's under the cursor, and checking what part of the world was hit by a fired bullet.

So, if we think of checking what's under our mouse cursor as 'firing a bullet', we're clearly firing it from the camera. And if you imagine that your screen is (for example) floating a meter in front of the camera, the bullet is being aimed to pass through a specific pixel on the virtual screen -- the pixel where the cursor is being drawn on the real screen.

If we know those two positions in the game world -- the camera position and the pixel position -- then finding out what's under that pixel is a trivial problem.

Now, we already know where the camera is in our game world, so that part isn't a problem. The only tricky part is figuring out where in our game world that virtual screen pixel is.

To get that game-world screen pixel position, I do this (pseudocode follows):

```
// first, get the cursor's window position, in pixels.
Vector2D pixelPos2D = WindowMousePosition();

// convert pixelPos2D from the range  [(0,0) .. (width,height)] to
// the range [(-1,-1) .. (1,1)]
pos2D.x = pos2D.x / (0.5f * WindowWidth()) - 1.0f;
pos2D.y = pos2D.y / (0.5f * WindowHeight()) - 1.0f;

// now work out how big our screen is, in world coordinates,
// if it's one meter in front of the camera.
float vertFOV = CameraVerticalFieldOfView();
float halfVertFOV = 0.5f * vertFOV;
float screenHalfHeight = tanf(halfVertFOV);
float screenHalfWidth = screenHalfHeight * WindowAspectRatio();

// screenHalfHeight and screenHalfWidth tell us (half) the actual in-game
// size of our screen, assuming that it's placed one meter in front of
// the camera.
//
// So relative to the camera, our pixel must be located at:
Vector3D pixelPos3D( pos2D.x * screenHalfWidth, pos2D.y * screenHalfHeight, 1.f );

// now, we need our pixel's position relative to the world, instead of
// relative to the camera, so we need to apply our camera's 3D
// transformation to it.
Vector3D pixelWorldPos3D = camera->GetLocalToWorldMatrix() * pixelPos3D;
// (or however your maths library performs matrix multiplication)

```

(Note that in this code, I assume that our camera looks forward along its positive Z axis, and that its X and Y axes match your window's X and Y axes. If your camera looks in some other direction, or has swapped its X or Y directions compared against your window's coordinate system, you'll need to make minor modifications)

And that's pretty much it. Now you know where your camera is, now you know where that virtual "pixel" is, and so now you can fire a pretend 'bullet' along that line using whatever method you already use for collision detection. It will tell you exactly what you hit, and exactly where.

There are other ways to do this as well. As noted in the question's comments, `gluUnProject()` is a common approach. Folks often will recommend reading back a pixel of the z-buffer (generally from the previous frame) to determine the z-buffer depth at the pixel to be queried, and then feeding the 2D pixel position plus that depth value into gluUnProject(), you can get where that point was in world-space. Down-sides of this approach are that at the time of calling gluUnProject(), you need to know the modelview matrix, the projection matrix, and the viewport settings. Plus, of course, needing to read back a pixel of the z-buffer, which almost certainly will cause an OpenGL pipeline stall. Plus, you need to be very careful in your code execution; it's easy for your z-buffer to be a frame or two old, which can result in serious inaccuracies when the camera or objects in the world are moving quickly.

Alternately, as Lars points out, if you do know those various matrices and viewport settings, then you can call gluUnProject() with an arbitrary non-zero 'winZ' value, and it will give you the world position of the specified pixel, at that distance forward from the camera. Using a winZ value of '1' should give the same final position that is calculated by my pseudocode, above, so you could use that as a less-code-required way to generate the direction for your virtual 'bullet' to fire, if you know the other information which it needs.

---
Tags: c++, opengl, 3d, sdl
---


# Question
Title: Event handling for Pressing only 4 keys on desktop
I want to poll only 4 keys i.e. Keys.LEFT, Keys.RIGHT, Keys.Up and Keys.Down in libGDX strictly. That means, I want to call render method, only when above 4 keys are pressed.

I followed below link and implemented InputProcessor (see code below), extending InputAdapter for keyDown only.

https://github.com/libgdx/libgdx/wiki/Event-handling

```
Gdx.input.setInputProcessor(new InputAdapter () {
            @Override
               public boolean keyDown (int keycode) {
                if(keycode==Keys.LEFT)
                {
                    System.out.println("left");
                    }
                if(keycode==Keys.RIGHT)
                {
                    System.out.println("right");
                }
                if(keycode==Keys.DOWN)
                {
                    System.out.println("DOWN");
                }
                if(keycode==Keys.UP)
                {
                    System.out.println("UP");
                }
                return true;
               }
        });

```

But i am not getting the result as expected.

After running application on desktop, whenever I move mouse pointer over game screen or pressing other keys , its FPS is changing . That means render method is being called. **Why?**

Here is my full code for testing. See the output at bottom.

```
package com.GDXTests.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.FPSLogger;

public class FPSTest extends ApplicationAdapter {
    private Texture tex;
    private SpriteBatch batch;
    private OrthographicCamera camera;
    public FPSLogger fpslog;

    @Override
    public void create ()
    {
    // Loading Texture
         tex=new Texture(Gdx.files.external("desktop/bit0.jpg"));
         camera = new OrthographicCamera();
         camera.setToOrtho(false, 256, 256);
         batch = new SpriteBatch();
          //initializing logger
         fpslog=new FPSLogger();
          //disabling the continuous rendering
         Gdx.graphics.setContinuousRendering(false);
         Gdx.graphics.requestRendering();
    }
    @Override
    public void render () {

        //logging fps
        fpslog.log();
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
         // tell the camera to update its matrices.
          camera.update();
          // tell the SpriteBatch to render in the
          // coordinate system specified by the camera.
          batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(tex,2,3);
        batch.end();

        Gdx.input.setInputProcessor(new InputAdapter () {
            @Override
               public boolean keyDown (int keycode) {
                if(keycode==Keys.LEFT)
                {
                    System.out.println("left");
                }
                if(keycode==Keys.RIGHT)
                {
                    System.out.println("right");
                }
                if(keycode==Keys.DOWN)
                {
                    System.out.println("DOWN");
                }
                if(keycode==Keys.UP)
                {
                    System.out.println("UP");
                }
                return true;
               }
        });
    }
     @Override
       public void dispose() {
          // dispose of all the native resources
         tex.dispose();
         batch.dispose();
       }
       @Override
       public void resize(int width, int height) {
       }
       @Override
       public void pause() {
       }
       @Override
       public void resume() {
       }
}

```

Here is the output of logger:

```
right
FPSLogger: fps: 2
left
UP
FPSLogger: fps: 5
DOWN
left
FPSLogger: fps: 3
right
UP
DOWN
FPSLogger: fps: 6       // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 2       // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 61      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 24      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 52      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 14      // move mouse pointer over screen, not pressing any keys
FPSLogger: fps: 21      // move mouse pointer over screen, not pressing any keys
UP
FPSLogger: fps: 15
DOWN
FPSLogger: fps: 2
left
right
FPSLogger: fps: 4
right
FPSLogger: fps: 3
right
FPSLogger: fps: 3

```

**I want something like this**

```
right
FPSLogger: fps: 1
left
FPSLogger: fps: 1
DOWN
FPSLogger: fps: 1
UP
FPSLogger: fps: 1

```

**Thanks in Advance!**

# Answer
> 2 votes
as written in their wiki:

> If continuous rendering is set to false, the render() method will be called only when the following things happen.
>
> An input event is triggered Gdx.graphics.requestRendering() is called Gdx.app.postRunnable() is called

in LibGDX **every input event** (mouse move, button pressed), **the render function will be called**

so, mouse movement is an Input Event, whether you do something with it or not.

same for the buttons pressed, no matter if you call '**requestRendering**' in the event or not, the screen will render.

---
Tags: libgdx, rendering, events
---


# Question
Title: In-development technologies for improvements in video game graphics and design
Video games have evolved through the ever changing technologies in the past two decades. The advances in search algorithms improved the early AI systems, the introduction of 3D, introduction of modular engines, improvement of graphics, methods for gameplay, improvement in UX design, networking and recently, Virtual Reality etc. are some of the canonical examples.

My concern is, nowadays, the technological changes seem less apparent...

Many developers claim that the video game visuals and graphics have reached their epitome, and the game mechanics and genres have stagnated. Is it correct?

# Answer
> 1 votes
Factors contributing to the *apparent* stagnation in the advancement of video game development.

**The uncanny valley**: As video game fidelity approaches photo-realistic rendering, humans begin to have an adverse reaction to characters that appear almost perfectly human but have some flaws. This is known as the uncanny valley and is fairly well documented. This is why - although technology can technically render a better image - it often isn't implemented intentionally.

**Refinement**: Re-factoring of existing modules and increased processor speeds result in the creation of games which - although mechanically similar - are experientially different.

**Exploration of genre**: Game developers have been expanding the number of genres that development of games can be pursued. The label 'interactive experiences' is being applied to games which don't fall into the usual 'game' definition.

**Socio-economic conditions**: Investors are less willing to invest in ideas which are not 'proven' - which is why we get repeats of 'blockbusters' particularly in times of economic hardship. Also social and political pressures influence the exploration of certain themes or genres (e.g. The Interview) and as theme and genre heavily influence game mechanics and plot - they often suffer as a result.

**Skill drain**: Furthering themes of economic downturn and rising cost of education - less developers are pursuing game development and those that do tend to stick to 'safe' ideas for the sake of job security.

For some examples to the contrary - evaluate Indie games.

---
Tags: game-design
---


# Question
Title: libGDX using Stage and Actor produces different camera angles on desktop and Android Phone
libGDX using Stage and Actor produces different camera angles on desktop and Android Phone.

Here are pictures demonstrating the problem: http://brandonyuh.minus.com/mFpdTSgN17VUq

On the desktop version, the image takes up most all the screen. On the Android phone it only takes up a bit of the screen.

Here's the code (not my actual project but I isolated the problem):

```
package com.me.mygdxgame2;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.scenes.scene2d.*;
public class MyGdxGame2 implements ApplicationListener {
    private Stage stage;
    public void create() {
        stage = new Stage();
        stage.addActor(new ActorHi());
    }
    public void render() {
        Gdx.gl.glClearColor(0, 1, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }
    public void dispose() {}
    public void resize(int width, int height) {}
    public void pause() {}
    public void resume() {}
    public class ActorHi extends Actor {
        private Sprite sprite;
        public ActorHi() {
            Texture texture = new Texture(Gdx.files.internal("data/hi.png"));
            texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
            sprite = new Sprite(new TextureRegion(texture, 0, 0, 128, 128));
            sprite.setBounds(0, 0, 300.0f, 300.0f);
        }
        public void draw(SpriteBatch batch, float parentAlpha) {
            sprite.draw(batch);
        }
    }
}

```

Why does this happen?

# Answer
either you set a camera with the same width and height for all screens and use:

```
stage.getViewport().setCamera()

```

or just use this command:

```
stage.setViewport(new StretchViewport(width, height));

```
> 0 votes

---
Tags: java, android, sprites, camera, libgdx
---


# Question
Title: (LibGdx) Get mouse position in ENTIRE game
I'm trying to get the mouse position IN GAME. By that I mean not the position on the screen, but inside the window. I've been using `Gdx.input.getX()`, but that's not INGAME. How do I do this?

# Answer
You need to **unproject** mouse position in your camera projection matrix.

```
    Vector3 mouse_position = new Vector3(0,0,0);
    OrthographicCamera cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.position.x = Gdx.graphics.getWidth()/2;
    cam.position.y = Gdx.graphics.getHeight()/2;

       ( ... )

    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(cam.combined);
        cam.update();

            mouse_position.set(Gdx.input.getX(), Gdx.input.getY(), 0);
            cam.unproject(mouse_position);

```
> 0 votes

# Answer
if i get this right, you are trying to get the "game world" pos from screen pos,

as mentioned in their wiki-

```
// x and y are your screen coordinates
 // (e.g. where a click/touch happened)
 Vector3 worldCoordinates = new Vector3(x, y, 0);
 camera.unproject(worldCoordinates);

```
> 2 votes

# Answer
The simplest way would be to substract the viewport's X and Y values to the mouse's coordinates.

```
worldX = mouseX - viewX;
worldY = mouseY - viewY;

```

This way, you won't get the mouse's coordinates relative to the window but relative to the game world.
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: How to rotate an object so that it is aligned with a vector?
I have the following Scenario: Two moving objects (A and B in the picture) need to appear "connected" by a third one (C in the picture). I set the position of the connecting object C as "halfway" between A and B, but how do I rotate it in such a way that it is alined with the vector that connects them (i.e. the result of A - B)? I've tried with `D3DXMatrixLookAtRH(&rotate, &eye, &look, &UP_VECTOR)` where `eye = (0,0,0)`,`look = A's position - B's position` and using the `rotate` matrix as a rotation matrix for C but the result doesn't look as what I expect.

# Answer
> 2 votes
D3DXMatrixLookAtRh is a function for making a view matrix (scene camera analogy) which happens to be the inverse of a world matrix for an object located and rotated the same as the view matrix.

So invert the result of your matrix and use the halfway point for eye, and give the function a look at position instead of a direction it is looking.

pseudo code:

```
//aPos == position of object A
//bPos == position of object B
//cPos == position of object C
cPos = bPos + (.5 * (aPos - bPos));

D3DXMatrix* invRotate;

D3DXMatrixLookAtRh(&invRotate, &cPos, &aPos, UP_VECTOR);

D3DXMatrixInverse(&rotate, null, &invRotate);
//rotate is now the world matrix for object C

```

---
Tags: c++, 3d, directx
---


title: Drop in quality of rendering of texture

text:
# Question
Title: Drop in quality of rendering of texture
Platform: Android OpenGL ES 2.0

I'm drawing a texture on to a square using OpenGL ES2.0. The texture scrolls infinitely in vertical direction.

The rendering quality drops very rapidly after a few frames and the texture quality is deteriorated.

Screenshot #1

Screenshot #2

How to correct this issue?

# Answer
Dose not increment UV coordinates unconditionally, but reset them after sometime.

UV coordinates (even if you use integer coordinates) are converted into floating point inside GPU registers and so are subject to typical loss of precision of floating points.

Instead of doing

```
U+=deltaU;
V+=deltaV;

```

do

```
U+=deltaU;
while(U>1.0f)
    U-=1.f;

V+=deltaV;
while(V>1.0f)
    V-=1.f;

```

(this assumes you are using standard UV so coordinates between 0 and 1.. if not just replace 1.0f with your MAXUV values
> 0 votes

---
Tags: android, rendering, opengl-es2
---


# Question
Title: Decoupling assets, instances and the rendering module
I am trying to redesign a home-grown hobby engine. It became apparent that it was far too tightly coupled and so I'm trying to redesign it in a more modular way. Unfortunately, I'm baffled by the practicalities of implementing some of the advice I've been reading, specifically by how little knowledge the rendering module is "supposed" to have of the rest of the solution. In my existing tightly coupled design I have a triangle of sorts between assets, instances and the renderer, and every time I try to break a link in it I feel I am losing something important. **How do I break the following couplings without losing functionality or creating greater problems for myself?**.

**A) Between assets and the rendering module.** Supposedly, the rendering module shouldn't have any knowledge of assets (or just about anything else). This is something I can accept in principle, but any attempt I make in practice, e.g. to feed geometry to the renderer, seems to follow one of two paths:

1. Creating a file format- and graphic API- agnostic intermediate representation. This has the disadvantage that I must open a file, load it's contents into memory, convert them into the intermediate representation and then convert that into a vertex buffer. This seems wasteful on the face of it, but is even worse if the file format and graphic API happen to have complementary representations - the modularity would mean I cannot take advantage of this.
2. Construct the vertex buffer outside of the rendering module and pass that in directly, *trading one module's reliance on the existence of a particular interface for another module's reliance on, and detailed knowledge of, a particular **implementation***. This feels like madness to me.

**B) Between instances and assets.** This is basically to keep unnecessary state changes to a minimum. In my tightly coupled design there is a bidirectional link between instances and assets. Not every scene will make use of every asset, but for any given scene I know what instances are present. Whenever a specific "dirty" flag is set I run through the instances, make a list of required assets and make sure I don't load resources or bind buffers I don't need. Similarly, I don't want to be binding and unbinding buffers to draw a cat, then a dog, then another cat. This time I loop through the assets, then the instances. If I break the link in either direction I lose something. If I refactor the link out into a separate class, it feels like a lie to say I've decoupled them - I now have a third class that is every bit as dependent on two others as these would have been on each other.

**C) Between instances and the rendering module.** Connected to the point above. Instances contain data that the rendering module needs to render the geometry in the right place, in the right animation state, etc. If I can't pass my instances (or scene object) into the renderer then I have to supply the required information in some implementation agnostic format one instance at a time, setPosition, setRotation, etc. But as I mentioned in B) I want to be drawing all of my cat instances at once, before I start drawing the dogs. To make this work I have to either:

1. Buffer the instance data inside the rendering module somehow and then sort the resulting list. Of course, the logical way to store this information would be in a structure of some kind... except... that structure looks suspiciously (exactly) like the instance I (for some reason) couldn't just pass to my renderer. I now have two essentially identical instance classes on either side of a module divide - *this can't be what decoupling is all about, surely?*. Not to mention whatever the sort might cost (and the games I'm most interested in making are fairly deep simulations, very heavy on the CPU already).
2. Sort by asset outside of the renderer. Sure, this seems easy enough. But this is an optimisation that *depends upon the implementation* within the rendering module itself. *This can't be what decoupling means either.* If the renderer (about which I am to make no assumptions) happens to be a fall-back, immediate-mode OpenGL renderer intended for older hardware, then this might actually cost me more than it saves.

---

So this is where I am. I want to be clear, **I am not doubting the advice**, I am just at a complete loss to come up with a practical (and sane) implementation. A message/event system seems like a good fit for most communication between other modules, and I've used similar patterns to produce modular solutions in my real-work programming (physics analysis). But the sheer volume and flow of data needed by the renderer would seem to require something else. Which links would you break? And how would you claw back the lost functionality? Are there good "third options" to issues A and C?

# Answer
This not claim to be a complete answer, but trust me I were in you, I tried to make a rendering engine with similiar choices etc. Decoupling is possible until you start incurring the cost of integrating togheter the decoupled components. If at logical level, there's coupling you just can't get rid of it in the code unless you can think a way to decouple it at high level.

Many real software systems exists and are hell to change because are highly coupled, but there's no one assuring to you a less coupled solution exists. Maybe you can refactor here and there but if you have a goal that requires a certain solution, fighting to change that solution is likely to change the problem (I'm not saying your particular problem does not have a solution).

Also this is the kind of questions that is unlikely to receive an answer because everyone has his super secret rendering engine best of all and don't want to share details about underlying architecture. I'm of the opinion that something nice could born only when some people start sharing ideas and do some group brainstorming about it. Groups may be eons better than individuals. Also some of the solutions you discarded because are "bad" are in reality not so bad, I tried them and are widely used by notable frameworks and rendering engines.

* Make a list of functional features you need (what you need really at least to show something).
* Make a design from that without any regard to optimization.
* You at least have something working and likely to be more maintainable (and so optimizable, if required)
* Then search for bottlenecks (after testin with real use cases!)
* Eventually optimize.
* Happy nights.

The point is that over optimizing for performance is likely to miss the most importan optimization point: human.

As side point, if component A is coupled with component B, there exist the chance that the coupling can be moved into a component C (again, this not always happens, but try to look for that)
> 2 votes

# Answer
I won't respond to each of your particular points, because I think that you're completely on track in your current thinking. You're right to be confused about how best to escape the couplings that you mention, but what you've got to realize is that, fundamentally, some couplings are inescapable.

When module A depends on data from module B, we say that module A is coupled to module B. Now, in some cases, this coupling can be truly removed so that by a restructuring of module A's logic, it no longer depends on data from module B. At some point, however, module A can not be refined any further--it depends on SOMETHING, or else it can't do anything at all. So, some things are inexorably coupled, lest they do nothing at all.

Given things that are inexorably coupled, when an author suggests "decoupling" they really mean "indirection." As you've stumbled upon here:

> I now have a third class that is every bit as dependent on two others as these would have been on each other.

You're exactly right, but you've *factored out* the dependency. The dependency resides in module C instead of modules A and/or B. The dependency is an unavoidable fact, but you've made it more flexible/pluggable via the indirection.
> 2 votes

---
Tags: c++, architecture, rendering
---


# Question
Title: How do you handle 'move to mouse', if the player is already at the mouse?
I'm making a top-down-2D game. When my player moves, the cursor does not move with it. In my game, the player moves by facing the cursor and then walking toward it. This means that eventually, the player will reach the cursor and then glitch out.

How do I handle player movement when they reach the mouse?

# Answer
Many top down 2D games have the camera centered on the player. This makes the mouse always 'move away' from the player. The 'glitch out' you mention can be handled by adding a dead zone immediately around the player. If the mouse is clicked within this deadzone, the move and rotate commands are not activated.

The move and rotate behavior is not intended to operate under such short distances. It'll often overshoot the target and this is where the 'glitch' is introduced. The algorithm essentially oscillates on the target never being able to reach it. The alternative to fixing this is to have some kind of maximum velocity based on distance to the target. Take a look at steering arrival behaviors to learn more about this problem:

Avoiding orbiting in pursuit steering behavior

Arrive steering behavior
> 16 votes

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


# Question
Title: Lighting shadow casting sprites with box2Dlights
I currently have something like this using box2Dlights

Ideally, I would like objects casting shadows to be lit, so the object is lit but there is still a shadow cast around it. Right now the object is covered by shadow. I am aware of the soft and softnesslength settings in box2dlights but this is not really what I'm looking for. Softness seems to light up a certain radius from the player rather than just lighting objects. It ends up kind of weird looking: So for example in the above picture, I would want the entire grey box to be lit, and none of the area to the left/right/behind it to be lit.

Any thoughts would be appreciated. Thanks

# Answer
> 0 votes
the RayHandler render creates a black and white mask and mask the alpha channel with it, so some parts are darker

what you can do is detect that an object should now lighten (maybe with the use of `RayHandler.pointAtLight(x,y)`, or calculate the radious of the light )

and edit the mask so the whole area of the object is totally white(or as light as the edge of it)

my guess would be to edit the RayHandlers Render method. you can see there that it clears the mask to be black and adds the white areas where the lights are.

```
// line 312:
for (Light light : lightList) {
    light.render();
}

```

so just add your white rectangles there and they will be lit.

and of course to set the Softness to a low or zero value.

---
Tags: libgdx, box2d, lighting
---


# Question
Title: How can I highlight and move to adjacent tiles in an isometric grid?
I trying to create a turn-based strategy game where you move a game object from one tile of a grid to another tile near it. I have created the grid using sprites and game objects but can't sort out the movement part.

How can I highlight adjacent tiles given the 'current' tile, and then allow a game object to move to any of those highlighted tiles?

# Answer
From your screenshot it looks like you've made your grid by placing a bunch of specific sprites or prefabs or whatnot. This will make it difficult to address your needs for adjacency, because each tile is totally distinct.

Instead, consider storing the tiles of your map in an array somewhere. This will allow you to use array indexing to determine tiles adjacent to any other tile, which will let you modify the tile accordingly to highlight it, and know where to move a game object if the tile is clicked on.

For example, you can store a 2D grid of tile sprites like this:

```
TileSprite[] tiles = new TileSprite[width * height];

```

This creates `width * height` tile sprite objects, which you can then initialize accordingly to fill up your map (e.g., `tiles[0] = new TileSprite("grass.png")` and so on, or whatever is appropriate).

Even though the above is a linear array of tiles you can conceptualize it as a grid. If width and height are both 4, for example, the array (`X` represents a sprite in the array) looks like this

```
0 1 2 3 4 5 6 7 8 9 ...
X X X X X X X X X X X X X X X X

```

but you can also think of it like this

```
X X X X
X X X X
X X X X
X X X X

```

and thus to get the tile at position `(x, y)` you apply the following indexing math:

```
var tile = tiles[y * width + x];

```

This allows you to get the *adjacent* tiles to `(x, y)` by adding or subtracting one from both `x` and `y`.
> 1 votes

# Answer
To highlight adjacent tiles from current tile, use a modified floodfill with a depth parameter to get all the nearest tiles within X depth/distance.

To allow a GO to move on any of those adjacent tiles, said floodfill should return a list of tiles, check if clicked tiled is in the list, if so, move GO.

A possible implementation of said floodfill (in Python) from here:

```
visited = set()
add start to visited
fringes = [[start]]
for each 1 < k ≤ movement:
    fringes[k] = []
    for each cube in fringes[k-1]:
        for each 0 ≤ dir < 6:
            neighbor = cube.add(Cube.direction(dir))
            if neighbor not in visited, not blocked:
                add neighbor to visited
                fringes[k].append(neighbor)

```
> 0 votes

---
Tags: unity, 2d, path-finding, grid, turn-based
---


# Question
Title: How could I constrain player movement to the surface of a 3D object using Unity?
I'm trying to create an effect similar to that of Mario Galaxy or Geometry Wars 3 where as the player walks around the "planet" gravity seems to adjust and they don't fall off the edge of the object as they would if the gravity was fixed in a single direction.

<sub>(source: gameskinny.com)</sub>

I managed to implement something close to what I'm looking for using an approach where the object that should have the gravity attracts other rigid bodies towards it, but by using the built in physics engine for Unity, applying movement with AddForce and the likes, I just couldn't get the movement to feel right. I couldn't get the player to move fast enough without the player starting to fly off the surface of the object and I couldn't find a good balance of applied force and gravity to accommodate for this. My current implementation is an adaptation of what was found here

I feel like the solution would probably still use physics to get the player grounded onto the object if they were to leave the surface, but once the player has been grounded there would be a way to snap the player to the surface and turn off physics and control the player through other means but I'm really not sure.

What kind of approach should I take to snap the player to the surface of objects? Note that the solution should work in 3D space (as opposed to 2D) and should be able to be implemented using the free version of Unity.

# Answer
I managed to accomplish what I needed, primarily with the assistance of this blog post for the surface snapping piece of the puzzle and came up with my own ideas for player movement and camera.

## Snapping Player to the Surface of an Object

The basic setup consists of a large sphere (the world) and a smaller sphere (the player) both with sphere colliders attached to them.

The bulk of the work being done was in the following two methods:

```
private void UpdatePlayerTransform(Vector3 movementDirection)
{
    RaycastHit hitInfo;

    if (GetRaycastDownAtNewPosition(movementDirection, out hitInfo))
    {
        Quaternion targetRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
        Quaternion finalRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, float.PositiveInfinity);

        transform.rotation = finalRotation;
        transform.position = hitInfo.point + hitInfo.normal * .5f;
    }
}

private bool GetRaycastDownAtNewPosition(Vector3 movementDirection, out RaycastHit hitInfo)
{
    Vector3 newPosition = transform.position;
    Ray ray = new Ray(transform.position + movementDirection * Speed, -transform.up);

    if (Physics.Raycast(ray, out hitInfo, float.PositiveInfinity, WorldLayerMask))
    {
        return true;
    }

    return false;
}

```

The `Vector3 movementDirection` parameter is just as it sounds, the direction we are going to be moving our player in this frame, and calculating that vector, while ended up relatively simple in this example, was a bit tricky for me to figure out at first. More on that later, but just keep in mind that it's a normalized vector in the direction the player is moving this frame.

Stepping through, the first thing we do is check if a ray, originating at the hypothetical future position directed towards the players down vector (-transform.up) hits the world using WorldLayerMask which is a public LayerMask property of the script. If you want more complex collisions or multiple layers you will have to build your own layer mask. If the raycast successfully hits something the hitInfo is used to retrieve the normal and hit point to calculate the new position and rotation of the player which should be right on the object. Offsetting the player's position may be required depending on size and origin of the player object in question.

Finally, this has really only been tested and likely only works well on simple objects such as spheres. As the blog post I based my solution off of suggests, you will likely want to perform multiple raycasts and average them for your position and rotation to get a much nicer transition when moving over more complex terrain. There may also be other pitfalls I've not thought of at this point.

## Camera and Movement

Once the player was sticking to the surface of the object the next task to tackle was movement. I had originally started out with movement relative to the player but I started running into issues at the poles of the sphere where directions suddenly changed making my player rapidly change direction over and over not letting me ever pass the poles. What I wound up doing was making my players movement relative to the camera.

What worked well for my needs was to have a camera that strictly followed the player based solely on the players position. As a result, even though the camera was technically rotating, pressing up always moved the player towards the top of the screen, down towards the bottom, and so on with left and right.

To do this, the following was executed on the camera where the target object was the player:

```
private void FixedUpdate()
{
    // Calculate and set camera position
    Vector3 desiredPosition = this.target.TransformPoint(0, this.height, -this.distance);
    this.transform.position = Vector3.Lerp(this.transform.position, desiredPosition, Time.deltaTime * this.damping);

    // Calculate and set camera rotation
    Quaternion desiredRotation = Quaternion.LookRotation(this.target.position - this.transform.position, this.target.up);
    this.transform.rotation = Quaternion.Slerp(this.transform.rotation, desiredRotation, Time.deltaTime * this.rotationDamping);
}

```

Finally, to move the player, we leveraged the transform of the main camera so that with our controls up moves up, down moves down, etc. And it is here we call UpdatePlayerTransform which will get our position snapped to the world object.

```
void Update ()
{
    Vector3 movementDirection = Vector3.zero;
    if (Input.GetAxisRaw("Vertical") > 0)
    {
        movementDirection += cameraTransform.up;
    }
    else if (Input.GetAxisRaw("Vertical") < 0)
    {
        movementDirection += -cameraTransform.up;
    }

    if (Input.GetAxisRaw("Horizontal") > 0)
    {
        movementDirection += cameraTransform.right;
    }
    else if (Input.GetAxisRaw("Horizontal") < 0)
    {
        movementDirection += -cameraTransform.right;
    }

    movementDirection.Normalize();

    UpdatePlayerTransform(movementDirection);
}

```

To implement a more interesting camera but the controls to be about the same as what we have here you could easily implement a camera that isn't rendered or just another dummy object to base movement off of and then use the more interesting camera to render what you want the game to look like. This will allow nice camera transitions as you go around objects without breaking the controls.
> 8 votes

# Answer
I think this idea will work:

Keep a CPU-side copy of the planet mesh. Having mesh vertices also means you have normal vectors for each point on the planet. Then completely disable gravity for all entities, instead applying a force in exactly opposite direction of a normal vector.

Now, based on which point should that normal vector of the planet be calculated?

The easiest answer (which I'm pretty sure will work okay) is to approximate similarly to Newton's method: When objects first spawn, you know all their initial positions on the planet. Use that initial position to determine each object's `up` vector. Obviously gravity will be in the opposite direction (towards `down`). In the next frame, before applying gravity, cast a ray from the object's new position towards it's old `down` vector. Use that ray's intersection with the planet as the new reference for determining the `up` vector. The rare case of the ray hitting nothing means something went horribly wrong and you should move your object back to where it was in the previous frame.

Also note that using this method, the further player origin is from the planet, the worse the approximation becomes. Hence it's better to use somewhere around each player's feet as their origin. I'm guessing, but I think using feet as origin also will result in easier handling and navigation of player.

---

A last note: For better results, you can even do the following: keep track of the player's movement in each frame (e.g. using `current_position - last_position`). Then clamp that `movement_vector` so that it's length towards object's `up` is zero. Let's call this new vector `reference_movement`. Move the previous `reference_point` by `reference_movement` and use this new point as ray tracing origin. After (and if) the ray hits the planet, move `reference_point` to that hit point. Finally, calculate the new `up` vector, from this new `reference_point`.

Some pseudo code to sum it up:

```
update_up_vector(player:object, planet:mesh)
{
    up_vector        = normalize(planet.up);
    reference_point  = ray_trace (object.old_position, -up_vector, planet);
    movement         = object.position - object.old_position;
    movement_clamped = movement - up_vector * dot (movement, up_vector);

    reference_point  += movement_clamped;
    reference_point  = ray_trace (reference_point, -up_vector, planet);
    player.up        = normal_vector(mesh, reference_point);
}

```
> 3 votes

# Answer
This post could be helpful. Its gist is, you don't use the character controllers, but make your own using the physics engine. Then you use the normals detected underneath the player to orient them to the surface of the mesh.

Here's a nice overview of the technique. There are plenty more resources with web search terms like "unity walk on 3d objects mario galaxy".

There is also a demo project from unity 3.x that had a walking engine, with a soldier and a dog and in one of the scenes. It demonstrated walking on 3d objects *Galaxy*-style. It's called the *locomotion system* by runevision.
> 2 votes

# Answer
## Rotation

Checkout the answer on this question on answers.unity3d.com (actually asked by myself). Quote:

> The first task is to get a vector that defines up. From your drawing, you can do it in one of two ways. You can treat the planet as a sphere and use (object.position - planet.position). The second way is to use Collider.Raycast() and use the 'hit.normal' it returns.

Here is the code that he suggested me:

```
var up : Vector3 = transform.position - planet.position;
transform.rotation = Quaternion.FromToRotation(transform.up, up) * transform.rotation;

```

Call that every update, and you should get it working. (note that the code is in *UnityScript*).
The same code in *C#*:

```
Vector3 up = transform.position - planet.position;
transform.rotation = Quaternion.FromToRotation(transform.up, up) * transform.rotation;

```

---

## Gravity

For the gravity, you can use my "planet physics technique", which I described in my question, but it isn't really optimized. It was just something I got on my mind.
I suggest you creating your own system for the gravity.

Here is a Youtube tutorial by Sebastian Lague. That is a very well-working solution.

**EDIT:** In unity, go to **Edit** \> **Project Settings** \> **Physics** and set the all values for **Gravity** to 0 (Or remove the *Rigidbody* from all objects), to prevent the built-in gravity (which just pulls the player down) to conflict with the custom solution. (turn it off)
> 2 votes

---
Tags: unity, physics, control
---


title: 2D Collision : detection and design

text:
# Question
Title: 2D Collision : detection and design
So, listening to this very smart piece of advice, I've already completed a basic Tetris game. Moving on, I started a small breakout. But suddenly : a nightmare came. Collisions.

Since I've been struggling with this a lot, I read a bunch of article of the web. Being a beginner, I thought that, in the first approach, I would only use Rectangle to detect collisions.

Right.

Now I still have some problems.

First of all, all the articles I stumbled upon on the Internet told me how to detect collisions, e.g. checking if objects A and B collided with each other. But it is not what I really need. In order to respond properly, I need to tell my objects if the collision happened on the X or Y axis and then setting the new velocity according to some rules. The problem is that there are so many possibilities when making the distinction between types of collisions that I don't think I've taken the right path.

The second point (which, I believe, is really tied with the first) is the pattern in which the detection and the resolution of a collision happen. Right now, I have a CollidableObject classes and a CollisionDetector classes which knows about these objects. Each frame, the detector is looking for collision (or at least for me, is trying) and when he finds one, it alerts each collided object, saying "Hey you ! You've have collided with Z on the X axis, change that velocity now." and the object abides.

The main issue right now is that I can detect the collision axis and therefore, when saying "Hey you ! You collided !", I cannot respond properly. In which direction should my velocity change ?

I've been thinking a lot about this lately, trying to figure it out on my own, but I haven't find something that I liked so I am asking here now.

Thank you for your answers !

(Note : I don't know if this is relevant, but I'm coding in C++ using SDL)

# Answer
> 0 votes
The most basic response to a collision like this is, "Reverse velocity in the direction of the collision". If you bump something up top, change the upwards velocity to a downwards velocity. Leave the side-to-side velocity just the same.

If your objects can move more than 1 "game cell" per frame, then you may also need to backtrack to the point of the collision, and apply however far you went into the barrier, as having bounced and moved away from the barrier.

This is the main difference from basic Tetris, where your game objects move only in "whole cell" steps, and no fixups like that are needed.

Sometimes you need to do this multiple times. For example, if the ball goes fast into a corner collision, it can bounce off both walls within the single update.

Hope that helps!

---
Tags: collision-detection, collision-resolution, design-patterns
---


title: Turn .obj files in to .mdl for Gmod

text:
# Question
Title: Turn .obj files in to .mdl for Gmod
want to import models that i made in to garrys mod but i cant figure out how to convert them in to .mdl files. I dont have any moding experience with the source engine. I tried to find a program to convert them but with no luck. My models are textured (`.png` files for the textures and the `.mtl` for the mapsing) Any wany to do it?

# Answer
> 1 votes
You will need to convert the obj file to smd, and have your normal textures converted to vtf. There is a program to do this called OBJ2SMD. It turns your obj and png into smd and vtf by just dragging and dropping the model and texture into the program window. But it only lets you use ONE texture on the whole model. Here is the link:

http://bob.gneu.org/software-releases/obj-2-smd-converter/

After your model is converted to smd and vtf, find a model compiler. Then insert your model into your gmod game.

---
Tags: source-engine
---


title: Making sprite rotate smoothly

text:
# Question
Title: Making sprite rotate smoothly
I have a sprite that I want to rotate smoothly and face the opposite direction:

This is my render function:

```
public void render() {
    // Game Loop

    Gdx.gl.glClearColor(0.7f, 0.7f, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    spriteBatch.begin();

    if(bug.getX() >= (int)(Gdx.graphics.getWidth() - 100) && bug.getY() >= (int)(Gdx.graphics.getHeight() - 100)){
        bug.rotate(rotDeg);
        turn = !turn;
    }
    else if(bug.getX() <= 0 && bug.getY() <= 0){
        bug.rotate(rotDeg);
        turn = !turn;
    }

    if(!turn){
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.draw(spriteBatch);
    spriteBatch.end();
}

```

What my code does is that when it reaches the destination (top right corner, or bottom left corner), it immediatly turns facing the opposite direction. How would I make this turn smoothly?

# Answer
> 1 votes
You may want to look into tweening, which is what's used to smooth out animations using various smoothing functions. If you don't wish to implement anything yourself, you may want to look into: http://code.google.com/p/java-universal-tween-engine/.

# Answer
> 0 votes
Given an angle you wish to rotate to `angleTo`, and the current angle `angle`, you can apply an easing function to `angle` as follows (assuming all angles are in degrees):

```
// see http://stackoverflow.com/a/7869457/1446919
double angleDifference = (angleTo - angle + 180) % (360) - 180;

double ease = 0.1;
angle += angleDifference * ease;

// Ensures angle reaches angleTo when the difference is very small
if (Math.abs(angleDifference) < 1) {
    angle = angleTo;
}

```

So in your implementation, you can check when the bug is out of bounds, set `angleTo` and the `turn` flag to true until `angle` reaches `angleTo`, then unset the `turn` flag:

```
if (!turn) {
    if((bug.getX() >= (int)(Gdx.graphics.getWidth() - 100) && bug.getY() >= (int)(Gdx.graphics.getHeight() - 100))
    || (bug.getX() <= 0 && bug.getY() <= 0)) {
        turn = true;
        angleTo = bug.getAngle() + 180;
    }
} else {
    double angleDifference = (angleTo - angle + 180) % (360) - 180;
    bug.rotate(angleDifference * ease);
    if (Math.abs(angleDifference) < 1) {
        turn = false;
    }
}

```

# Answer
> 0 votes
if you want to rotate slowly to a given angle, you need to calculate the delta angle, from the current angle to the destination angle. can be done easly with like this-

```
Vector2 dest = new Vector2(0,1); // angle to reach
Vector2 curr = new Vector2(0,-1); // whatever the current Bug angle is

float deltaAngle = dest.angle(curr);

//the `angle` method will return a number between -180 and 180.

float speed = 180; // degrees passed per second. play with it to reach the rotation speed you want

speed *= deltaTime; // parameter from Render method for consistant speed

// if the distance is too small just set the position
if (dest.epsilonEquals(curr,speed * MathUtils.degreesToRadians))
{
    // reached the destination angle. do whatever
    curr = dest;
}
else
{
    if(deltaAngle > 0)
    {
        speed *= -1; // rotate the other way around if its shorter that way
    }

    curr.add(speed).nor();
}

```

---
Tags: java, libgdx
---


title: LibGDX Touch Delay

text:
# Question
Title: LibGDX Touch Delay
So I'm trying to make a game in which you have to tap things fast, but the thing is - after you touch something (the area I chose), it takes like 2 more seconds to register another touch. Now, I think the problem is that I have too much things going on under the update method of some several classes at the same time, which causes this problem.

So to sum it up, there's a texture region that I want to detect if the user touches, and I do that using a method called "contains" (you'll see that in a second). But as I said above, I think that the delay is caused by too many things going on every second, and I'm looking for a way to get around that.

**That's the input handling method:**

```
public void handleInput() {
    if (Gdx.input.justTouched()) {
        mouse.x = Gdx.input.getX();
        mouse.y = Gdx.input.getY();
        cam.unproject(mouse);

        for (int x = 0; x < tiles.length; x++) {
            for (int y = 0; y < tiles[0].length; y++) {
                if (tiles[x][y].contains(mouse.x, mouse.y)) {
                    if (tiles[x][y].getLit() == true) {
                        tiles[x][y].setLit(false);
                        time = 0;
                        shouldGen = true;
                        shouldLoop = true;
                    }
                }
            }
        }
    }
}

```

**And that's the Tile class:**

```
public class Tile extends Box {

public static final int SIZE = 50;

public static final int TYPE_BLANK = 0;
public static final int TYPE_1 = 1;
public static final int TYPE_2 = 2;
public static final int TYPE_3 = 3;
public static final int TYPE_4 = 4;
public static final int TYPE_5 = 5;

private int type;
private boolean lit;

private ColorsHandler colorsHandler;
private TextureRegion blank, blue, green, orange, pink, red;

public Tile(int x, int y) {
    this.x = x;
    this.y = y;
    this.width = SIZE;
    this.height = SIZE;

    type = TYPE_BLANK;
    lit = false;

    colorsHandler = new ColorsHandler();
    blank = colorsHandler.getAtlas().findRegion("blank");
    blue = colorsHandler.getAtlas().findRegion("blue");
    green = colorsHandler.getAtlas().findRegion("green");
    orange = colorsHandler.getAtlas().findRegion("orange");
    pink = colorsHandler.getAtlas().findRegion("pink");
    red = colorsHandler.getAtlas().findRegion("red");
}

public int getType() {
    return type;
}

public void setType(int type) {
    this.type = type;
}

public boolean getLit() {
    return lit;
}

public void setLit(boolean lit) {
    this.lit = lit;
    this.type = TYPE_BLANK;
}

public void setPosition(float x, float y) {
    this.x = x;
    this.y = y;
}

public void render(SpriteBatch sb) {
    if (type == TYPE_BLANK) { // Blank
        sb.draw(blank, x, y);
    } else if (type == TYPE_1) { // Blue
        sb.draw(blue, x, y);
    } else if (type == TYPE_2) { // Green
        sb.draw(green, x, y);
    } else if (type == TYPE_3) { // Orange
        sb.draw(orange, x, y);
    } else if (type == TYPE_4) { // Pink
        sb.draw(pink, x, y);
    } else if (type == TYPE_5) { // Red
        sb.draw(red, x, y);
    } else {
        type = TYPE_BLANK;
    }
}

```

}

**That's the Box class which has the "contains" method in it:**

```
public class Box {

protected float x;
protected float y;
protected float width;
protected float height;

public boolean contains(float x, float y) {
    return x > this.x - width / 2 &&
            x < this.x + width / 2 &&
            y > this.y - height / 2 &&
            y < this.y + height / 2;
}

```

}

**That's an "update" method which might cause lag:**

```
public void update(float dt) {
    handleInput();

    int randx = 0;
    int randy = 0;

    time += dt;

    if (shouldLoop) {
        if (difficulty == 1) {
            if (time < 5.0f) {
                randx = MathUtils.random(tiles.length - 1);
                randy = MathUtils.random(tiles.length - 1);
                if (tiles[randx][randy].getLit() == false && shouldGen == true) {
                    tiles[randx][randy].setLit(true);
                    tiles[randx][randy].setType(Tile.TYPE_1);
                    shouldGen = false;
                }
            } else {
                time = 0;
                shouldLoop = false;
            }
        } else if (difficulty == 2) {

        } else if (difficulty == 3) {

        } else if (difficulty == 4) {

        } else if (difficulty == 5) {

        } else {
            difficulty = 1;
        }

        numLoops++;
        if (numLoops == 5) {
            if (difficulty < 5) {
                difficulty++;
            }
            numLoops = 0;
        }
    }
}

```

I also use Texture Regions in a ".pack" file to render out 64 boxes (50px by 50px rectangles) every frame - that might cause the delay (?)

If you'd like to see more of the code in case you have any ideas, just ask for it.

Thank you!

# Answer
does your FPS drop when pressing?

if so, if you are using Eclipse you should try using the DDMS perspective. see what part of your code takes most of the cpu time.

if the slow part is passing on every box to check 'contains', dont do it. just calculate what box is in the position pressed.

i dont know if your game shows boxes in a grid or not, but for grids it simple. just figured out what cell is in the position pressed. otherwise you might want to look into Spatial Partition
> 0 votes

---
Tags: java, android, libgdx, touch, lag
---


# Question
Title: How can I constrain motion to a path formed from multiple splines?
I want to develop a system to constraint a character movement to a certain path, defined a-priori by the level designer to give some sort of 2D/2.5D look.

Right now I have a list of splines that make a path, I also can project a arbitary point to a specific spline. So what I do is this:

* Iterate over all the splines in a path
* Find the closest point on all the splines that make a path
* And return the point with the minimum distance (thats my current point)

Now one issue that this leaves me with is: how do I find if I am actually out of the current path?

How would you implement this sort of system? I feel my way is not even close to a robust system.

For those of you wondering, lets say I am trying to implement something like Sonic Generations' 2D Segments (just the movement constraints). And by a path I mean like this. Its full 3D environment, but Sonic follows a predefined path.

# Answer
Update:

---

Even if you do use splines, doing spline computations during the game is wasteful. Normally one would break the spline in advance into a series of even segments (specifically positions on the spline with similar distances between them) \[p\_0, p\_1, p\_2 ..p\_n\] and use this to guide the players' character motion. The logic is still very much 2d in nature.. move right, increase your characters `x` value and advance towards `p[i+1]`

specifically:

```
position = x / distanceBetweenPoints;
m = Math.floor(position);
t = position - m;

position3d = p[m] * (1 - t) + p[m+1] * t;

```

Where

* `p[m]` is the point you have passed
* `p[m+1]` is the next point
* The fraction `t` represents the % of progress you made from `p[m]` to `p[m+1]`

There is no way or reason to escape the fact that if your character is stuck on a spline, the gameplay mechanics during that portion of your game are completely 2d (if not 1d assuming they can't jump).

One more thing to mention, to compute some `p[m]` assuming you have `p[m-1]` starting with `p[0]` which is the first point on the spline, you could do the following:

```
distanceBetweenPoints = someDesiredValue; //  Use the value you want
                   //(smaller value = higher fidelity = more points)

epsilon = 0.0001; some small value
stepSize = epsilon;
nextPoint = previousPoint + stepSize; // The points are a t value betweeb 0 and 1

// As long as the distance isn't right (too small)
while (distance(previousPoint, nextPoint) < distanceBetweenPoints && nextPoint < 1)
{
    stepSize *= 2;
    nextPoint += stepSize;
}

// TODO: Check for edge case where nextPoint == 1
// Distance is bigger now

While (Math.abs(distance(previousPoint, nextPoint) - distanceBetweenPoints) > epsilon)
{
    dist = distance(previousPoint, nextPoint);
    stepSize /= 2;
    if (dist > distanceBetweenPoints) nextPoint -= stepSize;
    else nextPoint += stepSize;
}
// nextPoint is just about right

p[i++] = spline(nextPoint);
previousPoint = nextPoint;

//repeat...

```

Old answer:

---

Outside of loops and constructs that cause the player character to shift position in the depth axis, what you wish to achieve can be done by implementing the game in 2d first with programmer art. Playtest the 2d game to tweak the game and level mechanics. Then use the 2d level as reference to construct a full blown 3d level that lives across the x, y plane and matches the original 2d design across that plain. The meshes can still have some depth for platforms and walls of course but that depth needs to be sliced in the middle by the 2d plane that defines the level spatially.

The gameplay will be completely 2d as before (other than some minor tweaks like the loop where the player character may need to be in two different depths in the same area). The only difference being that you will now use the xy values to position a player character model and use a camera to render the scene instead of simply using sprites.

The is no reason to use a spline or a path cause that will allow for no vertical motion. You definitely need a plane to allow the character to move freely, up and down and left to right.
> 1 votes

# Answer
Here's how I do it in my games:

1. Keep track of a "current path target" that is constrained to lie along the path.
2. At the start, the "path target" is the very first point in the path.
3. As the character moves along the path, update the target as follows: The target is the closest point to the character projected forward in time by a parameter *t*, representing a "lookahead".

* To do this, project the character's position onto the nearest spline and call it *p*. The time from the start of the spline to this point is *t\_0*, the target position is that point along the spline which lies at time *t\_0 + t*.
4. The character seeks the target.
5. When the target reaches the end of the path, it gets clamped there.
6. The character is done with the path when:
    * the character is near the target and
    * the target is at the end of the path.

What this will do is cause the character to move along the path at a more or less fixed rate corresponding to the parameter *t*. When the character reaches the end of the path, they stop. Note that you will implicitly need to know the *timing* of your path as well as the position to do this correctly.
> 3 votes

# Answer
Most of the linked video seems to be just 2D logic with 3D rendering. There is also some occasional 2.5D parts like here, where the player follows a predefined path but can adjust the horizontal offset in addition to the vertical one.

I don't think either of those need projecting points to paths. Instead the player is either jumping in a 2D world in the first case or directly following a path with a controllable offset in the second case. You can then control how large offsets are allowed. This way you don't even have the question "*how do I find if I am actually out of the current path?*", because you are always on the path.
> 1 votes

---
Tags: splines
---


title: Find asset labels at runtime

text:
# Question
Title: Find asset labels at runtime
Unity allows me to add multiple labels to my assets in the editor (the little blue luggage tag in the corner of the inspector). I can use the Asset Database to find all assets with a certain tag from the editor, but can I do the same thing at runtime? Maybe if the assets are in the resources folder?

# Answer
> 2 votes
Unfortunately, you can’t access the labels during runtime.

As you said methods like AssetDatabase.GetLabels and AssetDatabase.FindAssets are part of the namespace UnityEditor, which can’t be used in runtime.

**But what you could do** is: Write a editor script that export that all the labels information into a file and then in runtime read in that file, then you have a mapping of asset name to list of labels

```
// mapping labels by name
Dictionary<string, List<string>> labelsByName = ...;

// loaded texture
Texture2D texture = ...;

// get labels of the texture
List<string> labels = labelsByName[texture.name];

```

---
Tags: unity, assets, asset-management
---


# Question
Title: Typing text animation (dialogue) libGDX or in general
Can anyone think of an efficient way to animate the typing dialogue text as found in pokemon? I have a vague idea of using string.length, and having a new letter drawn every .2 seconds or so, but rather than using a timer event, i was wondering if there is a better way to do this. for example an animation, but i can't find anything like that in libGDX. Any ideas?

# Answer
If you're accumulating the amount of time that has passed since the dialog box appeared in a variable, then you can divide that by the total length of time you want it to take for all the text to appear. That will give you the percentage of the string should have appeared by now. Multiply that with the string length and round down to find out actually how many characters of the string need to be drawn that frame.

```
int charCountThisFrame = (int)((elapsedTime / dialogDuration) * text.length);

```

Alternatively, if you want to use "text speed" instead of a duration (like you see in the option menu of Pokemon and other RPGs), don't use elapsed time. Instead, multiply the speed with the amount of time that has passed since the last game update (sometimes called the time step or delta time) and add that to a variable every update.

```
float stringCompleteness = 0;
// Then, do this every update
stringCompleteness += textSpeed * deltaTime;
// and this when you draw
int charCountThisFrame = (int)stringCompleteness;
// Don't go over the length of the string!
if (charCountThisFrame > text.length)
{
    charCountThisFrame = text.length;
}

```

Text speed refers to how many characters should appear per unit of time.
> 3 votes

---
Tags: java, libgdx, animation, text
---


title: Errors compiling XNA project Windows 8?

text:
# Question
Title: Errors compiling XNA project Windows 8?
I'm using **Visual Studio 2012** have just installed **Windows 8** on my computer and tried to compile a game Im working on in XNA. When the game tried to build, I got the following errors:

* *Error 12 Could not copy the file "C:\Users\Computer\Documents\Visual Studio 2012\Projects\WindowsGame1\WindowsGame1\WindowsGame1\bin\x86\Debug\Content\SkyDome\skycirrus01.xnb" because it was not found.*
* *Error 13 Could not copy the file "C:\Users\Computer\Documents\Visual Studio 2012\Projects\WindowsGame1\WindowsGame1\WindowsGame1\bin\x86\Debug\Content\Fonts\Arial.xnb" because it was not found.*
* *Error 14 Could not copy the file "C:\Users\Computer\Documents\Visual Studio 2012\Projects\WindowsGame1\WindowsGame1\WindowsGame1\bin\x86\Debug\Content\Fonts\ISOCP2.xnb" because it was not found.*

**skycirrus01.xnb** is actually a **.fbx.** **Arial.xmb** and **ISOCP2.xmb** are my spritefonts within my project.

Prior to installing Windows 8 **(store bought)** my project compiled. Does anyone know how to convert these to .xnb files? I'm assuming that will make them compatible.

# Answer
> 1 votes
I've got it to work now. I compiled it again and now my game is working. I'm assuming that the first compile of an XNA project will automatically fail after Windows 8 is installed. But recompiling your project again will fix it.

So the answer to if XNA works with Windows 8 installed is **YES** (but not as a Metro App).

# Answer
> 0 votes
If you still struggle with this problem like me (I had this happen on moving to a new Windows 7 desktop), it can potentially be caused by Visual Studio mismatching the XML format of the content project when adding a new resource. If you go to the directory `[Game]\[Game]Content\`, you should see a `[Game]Content.contentproj` file. This can be opened with any basic text editor (notepad will do just fine). You will likely see a lot of lines that look something like:

```
<ItemGroup>
  <Compile Include="Images\Story\Level7.png">
    <Name>Level7</Name>
    <Importer>TextureImporter</Importer>
    <Processor>TextureProcessor</Processor>
  </Compile>
</ItemGroup>

```

Then, at the end, you might see where you tried to add the new content. It will look different, like this:

```
<ItemGroup>
  <None Include="Images\Story\Level8.png" />
</ItemGroup>

```

Visual Studio may have written this line, but it sure doesn't know how to read it. The game will give you a `ContentLoadException: File not found` error when attempting to load the resource. Simply change the .contentproj file so that the new content loading sections matches the old sections and voila! When you reload it in Visual Studio, your content should load just fine.

---
Tags: xna, windows-8
---


title: Resizing a tiledmap when using phaser

text:
# Question
Title: Resizing a tiledmap when using phaser
```
var cw = window.innerWidth;
        var ch = window.innerHeight;
        var game = new Phaser.Game(cw, ch, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });

        function preload() {
            game.load.tilemap('Background', 'https://gist.githubusercontent.com/anonymous/c61b37df015a0b2af1d7/raw/172bf9c2d4c20c56699eacce263525409caaf743/54996634e4b0a35d00c9b516.json', null, Phaser.Tilemap.TILED_JSON);
            game.load.image('tiles', 'http://i.imgur.com/gmWQIFK.png');
            game.load.image('player', 'http://i.imgur.com/tCCrLyh.png');
        }

        var map;
        var layer;
        var player;
        var _keyboard;
        var playerJumping;
        function create() {
            player = game.add.sprite(0, ch - 32, 'player');
            game.world.setBounds(0, 0, cw, ch);
            game.physics.startSystem(Phaser.Physics.ARCADE);
            game.physics.arcade.gravity.y = 300;
            game.physics.enable(player, Phaser.Physics.ARCADE);
            player.body.collideWorldBounds = true;
            game.stage.backgroundColor = '#787878';
            map = game.add.tilemap('Background');
            map.addTilesetImage('smb_tiles', 'tiles');
            layer = map.createLayer('Tile Layer 1');
            layer.resizeWorld();

            _keyboard = game.input.keyboard.createCursorKeys();
            game.camera.follow(player);
        }
        function update()
        {
            player.body.x += 2;
            if (_keyboard.up.isDown && player.body.onFloor()) {
                playerJumping = true;
                player.body.velocity.y = -2;

            }
            else {
                playerJumping = false;
            }
        }
```

```
<script src="http://yourjavascript.com/222115941388/phaser-min.js"></script>
<div id="game"></div>
```

As you can see the tiled Map start at a height of `320px` bcs originally the map have this height and if I change the game height to `320px` everything works fine , but my question is if i want to make the tiledMap responsive to innerHeight and width for the screen how can i do this so the tiled map start at the bottom of the screen and not at the `320px`

you can see how the tiled map layer is starting in the middle of the screen . is there by any chance something i can do to make it start at the bottom of the screen

# Answer
> 0 votes
In Javascript, you can set an HTMLElement's position on the screen by setting the HTMLElement.style.left and HTMLElement.style.top and HTMLElement.style.position: http://www.w3schools.com/css/css\_positioning.asp.

You probably need to create a div element first and position it to where you want, then set the parent parameter in Phaser.Game to the div element.

---
Tags: javascript, phaser
---


# Question
Title: How much assembly is really used in modern game code?
On average, how often is assembly used in modern game code?

Specifically on platforms that already have good C++ compilers, like x86, PPC, or ARM--because I assume games on embedded systems make extensive use of assembly.

# Answer
The answer depends a bit on what you mean by "game", and on "used". I'll assume "used" means "written during the course of the specific game project".

In my experience and anecdotal data from people I've talked to:

* in browser based games? None.
* in typical PC games? None. (But you might see some in low level libraries.)
* in iOS and Android games? None.
* "AAA" PC games and console games? Maybe a little, perhaps 0.05% of the code base. (With a bit more in the libraries.)

Knowledge of assembly language is not expected for work in the games industry, but depending on the type of games you make, it might come in advantageous.

There used to be an argument that the compiler does a better job at optimising C code than a human would with hand-written assembly. Usually that's true, sometimes it's false. But these days a combination of ever-growing CPU complexity and the need to scale 'out' (ie. to separate processors) means that optimisation efforts are usually spent elsewhere.

In recent years the only time I've seen assembly in game code was `__asm int 3` statements to force breakpoints, and my only personal use of assembly was in looking at the disassembly of a function to diagnose unusual crash bugs.
> 29 votes

# Answer
The bulk of high performance code in modern console games is written using a sort of middle ground between assembly and C++: compiler intrinsics. These constructs look and parse like C++ functions, but are actually translated into single machine instructions. So, for example, my "clamp each value of vector V to be \>= a and \<= b" function looks like

```
// for each v.x, ensure v.x >= a.x && v.x <= b.x
inline __m128 ClampSIMD( const __m128 &v, const __m128 & a, const __m128 & b )
{
    return _mm_max_ps( a, _mm_min_ps( v, b ) );
}

```

In functions like these I'm still thinking in terms of the specific machine instructions, but I have the convenience of writing them in C so that I don't need to worry about register coloring and scheduling and load ops and other boring details.

You still need to be aware of what instructions the CPU supports, especially because modern compilers are terrible at vectorizing code, compared to how well a smart human can do the job. Also sometimes subtle details of how you arrange your code can have huge implications for performance that aren't obvious without understanding what the machine is doing.

Although we may not code in assembly, we still *debug* in assembly a lot. Optimizing compilers aggressively reorganize code in ways that debuggers can't keep up with, so often when debugging a "release mode" build the best thing to do is pop open the disassembler and trace through the code that way. This GDC talk on "Forensic Debugging" of crashes illustrates many of the whys and hows of debugging at that level.
> 26 votes

# Answer
The problems that used to require hand rolled assembly are getting fewer in number. What you "might" gain in speed you lose in readability and the ability to debug. It should also be done only as one of the very last optimisation steps on sections of code as in most cases speed problems aren't something that can't be made better with assembly. These days CPU's have gotten much faster while memory speeds have not, often it's more important to control how data flows through the CPU than anything else.

With modern compilers they also find it hard to optimise around assembly code as they have to deal with whatever registers you've touched and they can't usually re-order instructions in your hand crafted code. To reduce the need for assembly, there is also now intrinsics which help to get access to low level concepts, but in a way that is compiler friendly and allow them to work with you rather than against.

With that said, the SPU on the PS3 is one area where people are still having to use assembly to get the most out of the processor, with manual instruction pipelining for example as explained here.
> 7 votes

# Answer
The fact is that we live in a multi platform world, and parts of our game code have to be tailored to the local platform - well not have to, but there are benefits if we take advantage of local hardware stuff!

This is not about games or game logic, it's about hardware locality for optimal performance of the code upon which game logic hinges, we can indeed wrap code sections, for example using macros, such that there is one source code, which executes well on the platform it was built against.
> -1 votes

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


# Question
Title: Unity - Sprite with collider2d hits a rigidbody - Searching for a way to make the rigidbody not to react
When a sprite with a box collider 2d hits the game object (rigid body),

the collision detection is fired and I get the event.

However, the sprite moves the rigidbody and I have trouble restoring it back.

I tried to create a collision detection without ridigbody but without success.

Is there a way so that the ridigbody is never moved?

Hint: I can't make it static, since the rigidbody becomes immovable.

# Answer
On the GameObjects, you could mark the `Is Trigger` box in the inspector, or from a script, do: `collider.isTrigger = true`. This will yield events in a similar way, but use the `OnTrigger` methods instead of the `OnCollision` methods, as described here.
> 3 votes

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


title: How to create particle system by script

text:
# Question
Title: How to create particle system by script
I have created a gameObject called "Sphere". After 5 secs the gameobject starts rotating. Along with the rotation I need to emit partical from the object. How can I do this?

# Answer
> 1 votes
You need to add your particle system to your gameObject. then you can activate it by something like this:

```
    // this is in the initial declaration
    particleEmitter pe;

    // this is in the Start() function
    pe = gameObject.GetComponent<ParticleSystem>().particleEmitter;

    // this go's inside your counter function and needs to get called
    // when you activate to rotation
    pe.emit = true;

```

you need to turn of the emission component of the particle system in the editor

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


title: How to show my XNA game in form C#

text:
# Question
Title: How to show my XNA game in form C#
I have a game in XNA, I want to connect this game with WindowForm to show for example the distance and the position.

I tried to apply many tutorials that talking about this. but here is my problem :

It's empty!! How can I show my game.

I think my problem is here :

using Microsoft.Xna.Framework;

```
namespace MissileProject.CustomForms
{
    public class MissileDisplay : WinFormsGraphicsDevice.GraphicsDeviceControl
    {
        protected override void Initialize()
        {

        }

        protected override void Draw()
        {
           GraphicsDevice.Clear(Color.CornflowerBlue);
        }
    }
}

```

Any help or advice please ?

# Answer
> 1 votes
Put simply, you only have the bare bones of a WinForms XNA based game. Your going to have to port your games code across from your XNA game project into your WinForms project. You'll have to create the MainLoop, and use it to call your MissileDisplay's Update and Invalidate Methods to simulate XNA's Update, and to call the GraphicsDeviceControl's Draw methods

If you need help with this, I found this 5 step guide very helpful. I was able to get 4 different displays for a proto level editor running at the same time.

# Answer
> 1 votes
Based on your code, I can tell you're using the example that Microsoft provides for linking WinForms to XNA (for others: part one, part two).

I would say to look at the provided control that displays the spinning triangle. Specifically this bit:

```
protected override void Initialize()
{
    // ...
    // Hook the idle event to constantly redraw our animation.
    Application.Idle += delegate { Invalidate(); };
}

```

This allows you to leverage the fact that events are not constantly being triggered in WinForms and will draw your game whenever those events are not being handled (just like you would normally do in a C++ application).

As you can tell from the example, you will also need to handle time by yourself using a `Stopwatch`. You can probably hack together a small `GameTime` class for yourself if you want and incorporate it.

---
Tags: xna, c#, 2d, game-design, windows-forms
---


# Question
Title: How to calculate a direction vector for camera?
I have a vector that describes change in movement, and I have a 3d-vector, m\_rot, that describes a rotation given to an object. I want to calculate a direction vector using both this data. How to achieve that?

I tried to multiply the components of a direction vector onto sin and cos of m\_rot values, but that gave me nothing.

```
direction.x = direction.x * ::cosf(m_rot.x);
direction.y = direction.y * ::sinf(m_rot.y);
this->camera_world_pos += direction;

```

But after that my camera still walks into a simple directions, and not a direction that it looks at.

# Answer
It sounds like what you're looking for is either a transformation matrix, or a quaternion.

**Transformation Matrix**

I will just run down how to do this using a transformation matrix, since its probably the easier of the two to understand. A transformation matrix in 3D is a 4x4 matrix defined as follows:

```
H = [xx, yx, zx, tx;
     xy, yy, zy, ty;
     xz, yz, zz, tz;
      0,  0,  0,  1];

```

Basically, it defines a coordinate frame with respect to another coordinate frame. In the transformation matrix, the column vector `[xx, xy, xz]` represents the *x*-axis of the coordinate frame, `[yx, yy, yz]` is the *y*-axis, and `[zx, zy, zz]` is the *z*-axis. The vector `[tx, ty, tz]` is the origin of the coordinate frame.

**View Matrix**

What you want to do is assign a transformation matrix `H_camera` to your character or camera. You will want to set it up such that the *z* axis of the transformation represents the direction the camera is looking. The *y* axis represents the "up" direction of the camera, and the *x* axis is the "left" direction, given by *y x z*. The vector `[tx, ty, tz]` will be the position of the camera in the world. In other words, it will look like this:

```
H_camera = [   |                |               |                 |
              left_vector ... up_vector ... forward_vector ... translation
               |                |               |                 |
               0                0               0                 1      ];

```

Say you want the character to move *forward* along the direction of the camera. Well, that's easy. You just extract `forward_vector` from `H_camera` and set that as the player's velocity. Similarly, you can add scalings of `up_vector` and `left_vector` to move the player up and to the left relative to his viewpoint.

**Changing the View Matrix**

Now, to make the camera move around, you just have to change the `translation` vector. To *rotate* the camera, you can do one of several things. You can either:

1. **Multiply the view matrix by a rotation matrix:** Create a rotation matrix around the X, Y, or Z axis and multiply the view matrix with it. Pre-multiplying a view matrix by a rotation matrix means "rotate in the global coordinate frame", post-multiplying a view matrix by a rotation matrix means "rotate in the local coordinate frame". A rotation matrix is a special kind of transformation matrix that has no translation, only rotation. For instance, a rotation around the *Z* axis looks like this:

`R_z = [cos(t), -sin(t), 0, 0;
 sin(t), cos(t), 0, 0;
 0, 0, 0, 1];`

Or

2. **Construct the view matrix by having it "look" at a point in space:** Another useful tool to have is to be able to construct the view matrix by looking at a point in space. Given an origin of the camera `t_camera`, a point to look at `t_look`, and an up vector `up`, we can say:

`forward_camera = (t_look - t_camera).normalized();`

`left_camera = up.cross(forward_camera).normalized();`

`up_camera = forward_camera.cross(left_camera).normalized();`

`translation_camera = t_look;`
> 10 votes

---
Tags: mathematics, trigonometry
---