# Question
Title: In Unity, how can I check if an input was made x seconds/frames ago?
I'm using the Rewired input plugin, and it comes with an input buffer. I enabled the buffer for my directional keys and airdash button so that the player doesn't have to hit both keys on the same frame in order to dash.

However, this means that if you press both keys and hold them down for more than a frame, the airdash code gets run again. I tried to stop this by comparing `Time.time` at the beginning of `Update()` to `Time.time` at the beginning of the coroutine, but this seems inconsistent and it doesn't feel like the right way to do it.

How would you check for the player's input time and compare it to the time since some previous input?

Here's a sample of the dash code within `FixedUpdate()`

```
        //Dash

        if (grounded)
        {
            dashCount = 0;
            dashTime = 0;
        }

        if (dashCount < 2)
        {
            //print(currentTime - dashTime);
            if (currentTime - dashTime < 0.1 || dashCount == 0)
            {
                //Double Tap Dash
                if (player.GetButtonDoublePressDown("Left"))
                {
                    StartCoroutine(Dash("left"));
                }

                //Button Dash
                if (player.GetButtonDown("Dash") && player.GetButtonDown("Left"))
                {
                    StartCoroutine(Dash("left"));
                }
            }

        }

        print(dashCount);

```

and here's a sample of the coroutine:

```
    //Dash
    IEnumerator Dash(string axis) {

        dashCount++;

        dashTime = Time.time;

        if (axis == "left")
        {
            if (inDash == true)
            {
                anim.SetBool("dashUp", false);
                anim.SetBool("dashDown", false);
                anim.SetBool("Hover", false);
            }
            canControl = false;
            inDash = true;
            anim.SetBool("dashHorizontal", true);
            anim.SetBool("inDash", true);
            rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0);
            rigidbody2D.AddForce(-dashForceHorizontal, ForceMode2D.Impulse);
            rigidbody2D.velocity = Vector2.ClampMagnitude(rigidbody2D.velocity, maxVelocity);
            rigidbody2D.gravityScale = 0;

            yield return new WaitForSeconds(0.2f);

            rigidbody2D.gravityScale = 2;
            rigidbody2D.drag = 25f;
            yield return new WaitForSeconds(0.2f);

            if (grounded == true)
            {
                yield return new WaitForSeconds(0.1f);
            }

            rigidbody2D.drag = 0f;
            canControl = true;
            anim.SetBool("dashHorizontal", false);
            anim.SetBool("inDash", false);

            inDash = false;

            yield break;
        }
  }

```

# Answer
Let's assume we have button `A` and button `B` and you want to be able to press both of them but not in the same frame.

The general way of accomplishing this is the following:

`on button A key press
 if button B is currently pressed
 execute action
end` `on button B key press
 if button A is currently pressed
 execute action
end`

combining the two logics you can get

`on button A or button B key press
 if both button A and button B are currently pressed
 execute action
end`

Now, if you want to make sure the users can press the two buttons in different frames but not more than 2 seconds apart we can slightly alter the above code as follow:

`on button A or button B key press
 if we can handle the action
 execute action
 else
 mark that we can handle the action and
 //eventually additional logic, if required
 start a couroutine that will mark disable the action handling in 2 seconds
 end`

This is a generic way that can be used to solve your issue. You will of course need to customize it for your own problem.
> 3 votes

---
Tags: unity, input, frame-buffer
---


# Question
Title: Can’t Load .fbx from blender to Monogame correctly
I am using `pipeline.exe` tool, to convert an .fbx file I made using Blender (using the default Blender 2.73a export settings) to .xnb, and then `manually copy and paste it` in my content directory (Is this one of the correct ways to convert it properly ?).

After watching this video https://www.youtube.com/watch?v=u7tLYMPC828 I saw that you have to convert the .fbx file that you create using blender, to a **new .fbx** file, using a tool called `fbx converter 2013`, and then use that file in the `pipeline.exe` tool, to produce the **final .xnb** file. Without doing that, I can't even see my model when drawn on the screen.

With the steps I described above, I managed to see the .xnb file on my screen but it was not exactly the original model I had made. For example:

As you can see the real model I got (after the convertion with the `fbx converter 2013`) is much longer, whereas the one on the left (the one I draw in my game), is like **packed in a small square**.

If you are using blender, please let me know how do you import the .fbx to your Monogame project. (Or you can suggest to me another software you are using to make models and tell me your method of importing models to Monogame)

This is how I am drawing my model:

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);

    Vector3 modelPosition = new Vector3(-25, 0, 0);
    float modelRotation = 0;
    float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in Brick.Meshes)
    {
        Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 50.0f);
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = Matrix.CreateRotationZ(modelRotation)*
                Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }
    base.Draw(gameTime);
}

```

Edit: I also tried exporting to .X from blender and when i converted to .xnb, loaded the model and drew it, nothing shows up.

# Answer
> 0 votes
Ok, I finally realized what the problem was... my drawing code was incorrect. I tried https://msdn.microsoft.com/en-us/library/bb197293(v=xnagamestudio.31).aspx code from msdn website and it all worked out. I am stupid. Also, downloading https://msxna.codeplex.com/releases/view/117230 and installing all the files in the correct order (following the instructions .txt) fixed the monogame content project error I was having where I couldn't create the project (`error missing project subtype 6D335F3A-9D43-41b4-9D22-F6F17C4BE596`), obviously because I hadn't installed things properly.

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


title: Wheel Joint Implementation in AndEngine

text:
# Question
Title: Wheel Joint Implementation in AndEngine
I am currently developing car game in AndEngine. In which I was using revolute joint for car wheel and chassis attachment. But my friend suggest me that use wheel joint for that purpose for better behavior of the car. In AndEnginen I didn't found the wheel joint implementation. So what I have to do for wheel joint implementation.

I think I have to manually update the box2d library for this purpose but I don't know how many things get updated. Please suggest me some guidance on achieving better car behavior in AndEngine.

# Answer
I am using box2d version \>2.3.0 where it supports wheel joint and also updated in the andengine source,

source:Andengine Example code like,

```
import com.badlogic.gdx.physics.box2d.joints.WheelJointDef

WheelJointDef f = new WheelJointDef();
f.initialize(bodyA, bodyB, anchorBody, axis);//axis for suspension feature(Vector2)
f.enableMotor=true;
f.frequencyHz=2; //this indicates ration for suspension, set the value as needed in the game.
getPhysicsWorld().createJoint(f);

```

Search Wheel joint on this link : box2d manual
> 0 votes

---
Tags: box2d, andengine
---


title: Box2D setGravity() in Andengine?

text:
# Question
Title: Box2D setGravity() in Andengine?
Im currently using the Andengine GLES20 branch. I know that the new Box2D method setGravity() isn't implemented yet.

Has anyone managed yet to get it to work with Andengine or to write a method which does the same? I really need this new feature of Box2D.

Thank you in advance.

# Answer
> 1 votes
get latest source : https://github.com/nicolasgramlich/AndEngine

It has the method

```
mPhysicsWorld = new PhysicsWorld(new Vector2(0, 0), false);
mPhysicsWorld.setGravity(pGravity);

```

where pGravity is Vector2 object for x and y values for your gravity. like Vector2(0,5).

---
Tags: box2d, andengine
---


# Question
Title: Ray->triangle collision math seems to not work?
First time asking, pardon any mistakes I make :)

I am programming a game from scratch, and the collision detection is giving me issues. I have AABB in place to check proximity, and if that reacts, the two models are checked by having each vertex in the moving model be a line going from the vertex' current position to its intended position. That line then gets checked against each triangle polygon in the 'obstacle' model.

My (current...) problem is that the math seems to react wrongly in the early part of that ray-triangle check (code below). I try simply to see if the two ends of the ray (vertex origin and vertex destination) are on opposite sides of the polygon plane (if they are not, the ray could not possibly be going through the polygon). I do this by getting a (not yet normalized) normal from the polygon via cross product. Then I dot the ray ends' positions with that. If it's one positive and one negative dot product, they should be on either side. Problem is, that never happens, even when i run models right through each other in tests. Never a 'positive & negative' result.

Can anyone spot my mistake(s)??

Code:

```
double Dot(Vec3 *a, Vec3 *b)
{
    double d = a->v[0] * b->v[0] + a->v[1] * b->v[1] + a->v[2] * b->v[2];
    return d;
}

Vec3 CrossProduct(Vec3 *a, Vec3 *b)
{
    Vec3 v;
    v.set(
        a->v[1]*b->v[2] - a->v[2]*b->v[1],
        a->v[2]*b->v[0] - a->v[0]*b->v[2],
        a->v[0]*b->v[1] - a->v[1]*b->v[0]
    );
    return v;
}

bool Collide(Vec3 *a, Vec3 *b, int target, int p)
{
    // a and b are the ray points in global space
    // target is the index number of the obstacle model
    /// p is the triangle polygon being checked (in a loop not included here)
    Vec3 poly_vert[3] = {entities[target].vertex[entities[target].poly[p].vertex[0]].pos
                    ,entities[target].vertex[entities[target].poly[p].vertex[1]].pos
                   ,entities[target].vertex[entities[target].poly[p].vertex[2]].pos};
    // poly_vert is the three vertices of the triangle polygon
    // Subtractions so poly_vert[0] essentially becomes the 0,0,0 center of the universe
    Subtract(&poly_vert[2],&poly_vert[0]);// Essentially, the vector from
                                             polyvertex 0 to polyvertex 2
    Subtract(&poly_vert[1],&poly_vert[0]);// Essentially, the vector from
                                             polyvertex 0 to polyvertex 2
    Subtract(a,&poly_vert[0]);
    Subtract(a,&entities[target].pos);// Make it relative to the obstacle model
    Subtract(b,&poly_vert[0]);
    Subtract(b,&entities[target].pos);// Make it relative to the obstacle model

    Vec3 poly_cross;
    poly_cross = CrossProduct(&poly_vert[1],&poly_vert[2]);
    double da = Dot(a,&poly_cross);
    double db = Dot(b,&poly_cross);

    if (da*db >= 0){return false;}
    return true;
}

```

# Answer
> 1 votes
I think these two lines are not needed:

```
Subtract(a,&entities[target].pos);// Make it relative to the obstacle model
...
Subtract(b,&entities[target].pos);// Make it relative to the obstacle model

```

I don't see why are you adding them. I think that if you remove them it should work as intended.

EDIT:

when you calculate the normal to the triangle (poly\_cross), this vector is also the normal to the plane containing this triangle (you have to normalize it). So, as dot product of the plane normal and some point is the distance to the origin of a parallel plane passing through this point, what you can do is:

```
Vec3 n = poly_cross.normalized(); // you have to create this function

Vec3 poly_vertex = Add( poly_vert[ 0 ], entities[ target ].pos ); // I am using a new function Add to add two vector2 here

double D = dot( n, poly_vertex );
double D1 = dot( n, a );
double D2 = dot( n, b );

```

where D, D1 and D2 are distances to the origin of parallel planes passing through triangle vertex and a and b points.

So after that just check the sign of:

D1 - D

D2 - D

if both are same sign then a and b are in the same side of the triangle

---
Tags: c++, collision-detection, mathematics
---


# Question
Title: How to save file in assets so it can be properly loaded in Android Studio?
I am following a guide on creating a replica of Flappy Bird. - http://www.kilobolt.com/day-6-adding-graphics---welcome-to-the-necropolis.html

The step I am having trouble is loading the texture from the assets directory. There are the author's instructions on how to do this.

And the code that he uses to actually load the texture

```
        texture = new Texture(Gdx.files.internal("data/texture.png"));

```

My file structure looks like this(I am using Android Studio 1.0 while the author is using eclipse)

I had to manually create the data directory inside the assets folder. However when I try to run the application, I get these exceptions

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: data/texture.png
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: data\texture.png (Internal)

```

Does anyone know what the issue is? The texture.png is clearly inside the data directory of assets. I also made sure to clean the project right after copying the .png file into the data directory as the author mentioned.(so resources can be properly loaded). Is the issue just that were using two different IDES, so that different method calls have to be made?

# Answer
On your run configuration make sure you have set your "Working directory" to your asset folder. Example:

This only applies for the desktop run config.
> 1 votes

---
Tags: libgdx, textures, assets
---


# Question
Title: Java LWJGL - Monster follow script not working properly
I have written a script to be set off whenever a player is within a distance of the monster. The script checks if the x position is greater than or less than the players x, and same for the z. (y is automatically set to terrain) The checkWalkX and checkWalkZ functions work with my monsters walk function, which specifies a new position on a timer and walks to that position. But when I use the same kind of idea for the following, it doesnt work correctly.

```
public int checkWalkX(Vector3f position) {
    if (Math.floor(this.getX()) != Math.floor(position.x)) {
        if(this.getX() > position.x) return 1; //Greater
        if(this.getX() < position.x) return 2; //Less
    }
    return 0;
}
public int checkWalkZ(Vector3f position) {
    if (Math.floor(this.getZ()) != Math.floor(position.z)) {
        if(this.getZ() > position.z) return 1; //Greater
        if(this.getZ() < position.z) return 2; //Less
    }
    return 0;
}

public void follow(Player player) {
    walking = false;
    following = true;

    if(checkWalkX(player.getPosition()) == 1) this.setX(this.getX() - mobSpeed);
    else if(checkWalkX(player.getPosition()) == 2) this.setX(this.getX() + mobSpeed);

    if(checkWalkZ(player.getPosition()) == 1) this.setZ(this.getZ() - mobSpeed);
    else if(checkWalkZ(player.getPosition()) == 2) this.setZ(this.getZ() + mobSpeed);

    if(Math.floor(checkWalkX(walkToPosition)) == 0 && Math.floor(checkWalkZ(walkToPosition)) == 0) following = false;
}

```

For some reason when I run this script, the monster will only move within a distance of 2ish. He moves the right ways kinda, but he doesnt follow me. Would anyone know why this is?

# Answer
I want you to think about a refactoring of your code. Since you already have a vector structure (Vector3f - I guess its from lwjgl) why not use it?

```
// Calculate the vector pointing from the mob toward the position with
// a length of their distance.
// This is equal to: wayTowardPlayer = playerPosition - mobPosition
Vector3f wayTowardPlayer = new Vector3f();
Vector3f.sub(player.getPosition(), this.position, wayTowardPlayer);

// Check if both are not at the same position, yet.
if (wayTowardPlayer.lengthSquared() > 0) {

    // Here you also could:
    // - Clamp your vector to let the mob not walk more than some pixels,
    //    regardless of its distance to the player.
    // - Scale it by e.g. 0.5 let the mob walk only half the way toward player.
    // - Clamp it to [-1,0,+1] so it reflects the direction you want to move
    //   and then multiply it with a velocity and passed time since last update
    //   to let it move smoothly toward the player over time without jumping.

    // Add the calculated vector to the mobs postion.
    // If you didn't manipulate it as described before it's position then
    // is that of the player.
    // This is equal to: mobPosition = playerPosition + wayTowardPlayer
    add(this.position, wayTowardPlayer, this.position);
}

```

I also recommend you to quit with using lwjgl `Vector3f` since it only has static members for addition and substraction. What about using those classes from libgdx? Libgdx uses LWJGL for desktop rendering as well and has a lot of tools integrated that makes programming easier. It also allows to easy build portable apps for different plattforms, e.g. Android. In my games I always seperate game logic from graphics.

With libgdxs vector classes the last addition would simply be:

```
this.position.add(wayTowardPlayer);

```
> 0 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: How to discern boxes and spheres when importing from fbx
I can import scene from FBX file into my engine, and i want spheres, boxes and capsules to be imported as colliders. So, how i can check if imported instance is one of them? Thanks.

# Answer
You could assign a specially named material to your colliders to identify them as such and use UV or color values to retrieve the orientation & scale.

The same special material trick is often used for navmesh.

For example:

* a box collider could have its corners colored with RGB=XYZ with 0 or 1 depending on which end.
* a capsule collider could have all its vertices to color 0,0,0 except two opposite vertices of the "caps" of the cylinder part, one end set to blue, one to red, average is center of end points, half distance is radius, length is given by both end centers.
* for a sphere collider you can set two opposite vertices to a specific color, get the center from the average & radius from half the distance.

This way you can find the orientation and size of all colliders.
> 1 votes

---
Tags: physics-engine, fbx, importing
---


# Question
Title: What are some ways of making a game engine centered around the idea of drawing vector lines and polygons only?
I've always loved the look of games that just use simple lines and polygons for graphics. Rez is one of my favorite games, visually. I'm a programmer and designer first and foremost, and I'm horrible at creating Actual Art, and the idea of making a game like Rez, using mostly line and polygon drawing, really appeals to me. Sort of like how a lot of programmers like to make roguelikes with minimal or ASCII art, I really like the idea of making a game just using trigonometry to draw lines in cool ways.

I've been making a game for a school project using my school's proprietary game engine. Instead of using its 3D model drawing capabilities and 2D sprite drawing capabilities, I've instead opted to make it using only the engine's "debug draw" functionality. I went so far as to create a library of functions that allow me to create "VecSprites", or collections of lines that act in the same way as sprites, both in 2D and 3D contexts. (For 3D, I do my own matrix math to calculate perspective and stuff, forgoing the engine's own 3D rendering capabilities entirely). Here is a video of my current project in action.

Going forward though, I want to set out to create my own game engine that will allow me to make these sorts of games on my own, without using someone else's game engine. I have plenty of experience with game engine architecture, but I don't know too much about actually drawing stuff to the screen. (Whenever I made a from-scratch game project for school, someone else was in charge of the DirectX or OpenGL side of things.) I have, however, done research into the different methods of rasterizing lines and curves and such to the screen.

What I'm wondering is, if I want to set out to make my own game engine specifically for drawing only primitive lines and circles (and then extend it with classes and such to allow for functionality such as grouping lines together into shapes), where is my best bet for getting started?

In the past, I've fooled around with Cairo, only to be disappointed by the fact that, currently, it is not really meant for rendering graphics in real-time on the GPU. Two years ago I made a simple game project using it, and it worked great until I ran it at 1080p, and, as it turns out, pushing 1920x1080x4 bytes to the GPU sixty times a second isn't exactly what modern computers were meant to do.

So where do I begin? I want to draw primitive lines and polygons on PCs, specifically Windows and possibly Linux, as fast as possible. I wouldn't mind having to go through the effort of creating my own systems for drawing anti-aliased lines, filled polygons, and so forth; I just want to know what my options are for doing such things.

Do I draw lines and polygons using low-level OpenGL calls, and go from there? Is it possible to pass a bunch of data containing the shapes I want do draw to a shader, and then have the shader do it? (I'm only minimally familiar with how shaders work.)

I know this question is kind of broad, but I really want to set out on this adventure to try and make this thing, and I just don't really know where to begin, at least as far as the drawing side of things is concerned.

# Answer
If you only need 2D you can use OpenVG which is essentially the 2D counterpart of OpenGL.

official site: https://www.khronos.org/openvg/

wikipedia: http://en.wikipedia.org/wiki/OpenVG

If you need 3D ribbons / lines integrating with a 3D scene you'll have to do line expansion yourself and draw them using a 3D API such as OpenGL or Direct3D.

Geometry shaders can do point and line expansion into thick quads/triangles on the GPU, there are many examples & tutorials on the web for this.

Search the web for "lines using geometry shaders".

One good discussion with examples: https://forum.libcinder.org/topic/smooth-thick-lines-using-geometry-shader
> 1 votes

---
Tags: opengl, graphics-programming, vector-art
---


# Question
Title: Why do tutorials use different approaches to OpenGL rendering?
http://www.sdltutorials.com/sdl-opengl-tutorial-basics

http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/

These two tutorials use completely different approaches to get nearly the same result. The first uses things like `glBegin(GL_QUADS)`. The second one uses stuff like `vertexBufferObjects`, shaders based on GLEW. But the result is the same: you get basic shapes.

Why do these differences exist?

The first approach seems much easier to understand. What's the advantage of the complicated second approach?

# Answer
> 78 votes
OpenGL has four different major versions, not counting the versions for mobile devices and embedded systems (OpenGL|ES) and the Web via JavaScript (WebGL). Just like Direct3D 11 has a different way of doing things than Direct3D 8, so does OpenGL 3 have a different way of doing things than OpenGL 1. The big difference is that OpenGL versions are mostly just add-ons to the older versions (but not entirely).

On top of the different editions and versions of OpenGL, the main OpenGL also added the concept of profiles. Namely the Compatibility Profile (which enables support for APIs from older versions) and the Core Profile (which disables those old APIs). Things like `glBegin` simply don't work when you use the Core Profile but will when you use the Compatibility Profile (which is the default).

As one further major complication, some implementations of OpenGL (like Apple's, among others) will only enable newer OpenGL features when you're using the Core Profile. This means that you *must* stop using older APIs in order to use newer APIs.

You then end up with several very confusing scenarios for tutorials:

1. The tutorial is old and only uses deprecated APIs.
2. The tutorial is new and well-written and only uses Core-compatible APIs.
3. The tutorial is new but makes the mistake of assuming that you're working with a driver that enables all APIs in Compatibility mode, and freely mixes both new and old APIs.
4. The tutorial is for a different edition of OpenGL like OpenGL|ES that doesn't support any of the old APIs at all, in any version.

Things like `glBegin` are part of what's sometimes called the immediate mode API. This is also super confusing because there's no such thing as a retained mode in OpenGL and "immediate mode" already had a different definition in graphics. It's much better to just refer to those as OpenGL 1.x APIs as they've been obsolete since OpenGL 2.1.

OpenGL's 1.x API would immediately submit vertices to the graphics pipeline back in the old days. This worked well when the speed of the hardware that rendered vertices was roughly on par with the speed of the CPU generating the vertex data. OpenGL back then just offloaded the triangle rasterization and not much else.

These days, the GPU can chew through massive numbers of vertices at very high speeds while performing advanced vertex and pixel transformation and the CPU simply cannot even remotely keep up. On top of that, the interface between the CPU and the GPU has been designed around this speed difference meaning that it's not even possible to submit vertices to the GPU one at a time anymore.

All GL drivers must emulate `glBegin` by internally allocating a vertex buffer, putting the vertices submitted with `glVertex` into this buffer, and then submitting that whole buffer in a single draw call when `glEnd` is called. The overhead of these functions is far greater than if you just updated the vertex buffer yourself, which is why some documentation will (very mistakenly!) refer to vertex buffers as "an optimization" (it's not an optimization; it's the only way to actually talk to the GPU).

There are various other APIs that have been deprecated or obsoleted in OpenGL over the years. The so-called fixed-function pipeline is another such piece. Some documentation might still use this pipeline or mix with the programmable pipeline. The fixed-function pipeline comes from the olden days when graphics cards hard-coded all of the math used to render 3D scenes and the OpenGL API was limited to setting some configuration values for that math. These days the hardware has very little hard-coded math and (just like your CPU) runs user-supplied programs (often called shaders) instead.

Once again the drivers must emulate the old API as the fixed-function features simply aren't present on hardware anymore. This means that the driver has a bunch of compatibility shaders embedded in it that execute the old math from the fixed-function days which is used when you don't supply your own shaders. The old OpenGL functions that modify that old fixed-function state (like the old OpenGL lighting API) are actually using modern OpenGL features like uniform buffers to feed these values to the driver's compatibility shaders.

Drivers that support compatibility have to do a lot of behind-the-scenes work just to figure out when you're using these obsolete features and making sure that you can combine them with modern features smoothly, which adds overhead and greatly complicates the driver. This is one of the reasons that some drivers force you to enable the Core Profile to get at newer features; it simplifies their driver internals greatly by not having to support both the old and new APIs being used simultaneously.

A lot of documentation may recommend that you start with the old APIs simply on account of them being easier to get started with. Direct3D solved this problem for beginners by offering a companion library (DirectX Tool Kit) that provides simpler drawing APIs and pre-written shaders which can be freely mixed with raw Direct3D 11 usage as your expertise grows. The wider OpenGL community has mostly stuck with the Compatibility Profile for beginners, unfortunately, which is problematic as again there are systems that do not let you mix old OpenGL APIs with the newer ones. There are unofficial libraries and tools for simpler rendering on the new OpenGL with varying levels of features and target use cases and languages (MonoGame for .NET users for instance), but nothing officially endorsed or widely agreed upon.

Documentation you're finding may not even be for OpenGL but may be for one of the other similar APIs. OpenGL|ES 1.x had fixed-function rendering but did not have the OpenGL 1.x APIs for vertex submission. OpenGL|ES 2.x+ and WebGL 1+ do not have any fixed-function features at all and there is no backwards compatibility modes for those APIs.

These APIs look very very similar to main OpenGL; they're not quite compatible, but there are official extensions to OpenGL that some (not all) drivers support to become compatible with OpenGL|ES (which WebGL is based on). Because things weren't confusing enough before.

# Answer
> 9 votes
The primary difference is how up-to-date the strategies are. The immediate mode used in the first tutorial:

```
glBegin(GL_QUADS);
    glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
    glColor3f(1, 1, 0); glVertex3f(100, 0, 0);
    glColor3f(1, 0, 1); glVertex3f(100, 100, 0);
    glColor3f(1, 1, 1); glVertex3f(0, 100, 0);
glEnd();

```

Is outdated and not supported on newer versions.

Using vertex buffers and shaders is the current method of rendering with OpenGL. It may seem more complicated, but it performs considerably better. Additionally, once you have your supporting code wrapping up the OpenGL stuff, the differences are abstracted away for the most part.

# Answer
> 2 votes
Just to add some more context to the other excellent answers.

The immediate mode as described in the first link is, as others have said, legacy code from the earliest versions of OpenGL (1.1). It was used back when GPUs were little more than triangle rasterizers and the idea of programmable pipelines didn't exist. If you look at the source code for some of the early hardware-accelerated games like GLQuake and Quake 2 for example, you will see immediate mode in use. In simple terms, the CPU sends instructions for vertices one at a time to the GPU to start drawing triangles on the screen. For the record, GL\_QUADS has the same result as GL\_TRIANGLES, except the GPU has to turn those quads into triangles itself on the fly.

Modern (3.2+) OpenGL takes a different approach. It buffers the vertex data into the GPU memory for quick access, and then you can send drawing instructions either using glDrawArrays or glDrawElements. You also have the programmable pipeline (glUseProgram) which allows you to customise how the GPU positions and colours the vertices.

There are a few reasons why immediate mode was deprecated, the main reason being performance. As Sean said in his answer, nowadays GPUs can crunch the data faster than the CPU can upload it, so you would be bottlenecking the GPU performance. There is a small overhead involved for every call to OpenGL you make, it is miniscule but when you're making tens of thousands of calls every frame it begins to stack up. Simply put, to draw a textured model using immediate mode, you need at least 2 calls per vertex (glTexCoord2f and glVertex3f) per frame. With modern OpenGL you use a couple of calls at the start to buffer the data, then you can draw the entire model, regardless of how many vertices it contains, using just a few calls to bind the vertex array object, enable some attribute pointers and then a single call to glDrawElements or glDrawArrays. To maximise this performance benefit, many modern engines will batch their vertex data, so rather than having one vertex array object per mesh in the scene, they will batch them all up into one giant vertex array and then crunch it in one go, minimizing the communication overhead.

Which technique is right? Well that depends on what you're trying to do. A simple 2D game which doesn't require any fancy post-processing techniques or shaders will work just fine using immediate mode and it will probably be easier to write the code. However, a more modern 3D game would really struggle, and if you're planning on learning GLSL (shader language), then definitely learn the modern technique.

---
Tags: opengl, architecture
---


# Question
Title: Using a different "max texture size" depending on the device
I am developing an Unity game for a wide range of iOS devices. I noticed that some scenes load pretty fast in the iPad mini 3, but very slow in the iPad mini 1. Of course, that's to be expected as one is much faster than the other.

The scene is composed mostly of several sprites. As an optimization attempt, one could reduce the `max texture size` property of the sprites, as I'd imagine this will allow them to load faster.

Is it possible to have a max size of 2048 for the iPad mini 3, but only 1024 for the iPad mini 1?

I suspect that the answer is no, as Unity "compiles" the images depending on the settings you used when building the game.

# Answer
> 2 votes
One way I'd go about is to set all textures in your materials to the smaller version for fast loading, and in the Resource folder (http://docs.unity3d.com/ScriptReference/Resources.html) you put the higher resolution versions with matching names ("Dirt" -\> "Dirt**\_HD**").

Then on devices that can handle it you have a script in your game that go through all the materials and load the HD version of all its textures, replacing them in all the materials.

Make sure you use a dictionary to **only load each texture once** when multiple materials share the same texture.

And call `Resources.UnloadUnusedAssets()` to unload the low resolution versions.

---
Tags: unity
---


# Question
Title: Does level streaming in games load directly from the HDD?
I wondered if the level streaming loads directly from the HDD. My first thought was if that would not be to slow, or if the chunks are just loaded into RAM and asynchronously processed if appropriate or something I didn't thought of yet.

# Answer
A lot of engines uses both in a two steps loading approach:

1. Load groups of compressed chunks (level/world sections) off the storage device, slightly in advance if possible.
2. Decompress the small chunks within from RAM into an active usable format when they are needed.

Keeping the larger compressed chunk groups cached in RAM for a little while in case the player walks back and forth.

In your larger groups you can put list of local assets (textures, meshes to instantiate, etc) to preload as well.
> 1 votes

---
Tags: streaming
---


# Question
Title: Creating an in-game time system only works with real time
I'm trying to create an in-game time system. Thus far it only works properly if you use 1440 minutes to the day (realtime), but I would like to be able to alter the day length to something like 10 minutes for example.

When adjusting it to 10, 20, etc, the clock starts to increment extremely rapidly to the point that an entire week passes in less than a second if you set it to one minute, or a day passes in about 12 seconds at around 10 realtime minutes to the day.

```
public float DayLengthInMinutes = 1440;// How long a day is in real world minutes
public int HoursToTheDay = 24;       // How many hours there are in a day
public int MinutesToTheHour = 60;    // How many minutes there are in an hour
public int SecondsToTheMinute = 60;  // How many seconds there are in a minute

public float _dayLength;                // Day length in seconds
public float _hourLength;               // Hour length in seconds
public float _minuteLength;             // Minute length in seconds
public float _secondLength;             // Seconds length in seconds
private float timer;                    // Timer that will be tracking game time

void Initialize () {
    timeSinceStart = Time.realtimeSinceStartup;
    _dayLength = _dayLengthInMinutes * 60;  //get seconds to the day
    _hourLength = _dayLength / HoursToTheDay; //determines how long an hour is
    _minuteLength = _hourLength / MinutesToTheHour; //determines how long a minute is
    _secondLength = _minuteLength / SecondsToTheMinute; //determines how long a second is
}
void CalculateTime () {
    if (timer >= _secondLength) {
        currentSecond++;
        timer = 0;
    }
    if (currentSecond >= _minuteLength) {
        currentMinute++;
        currentSecond = 0;
    }
    if (currentMinute >= _hourLength) {
        currentHour++;
        currentMinute = 0;
    }
    if (currentHour >= HoursToTheDay) {
        currentDay++;
        currentHour = 0;
        currentMinute = 0;
        currentSecond = 0;
        dayOrNight = "AM";
    }
}

```

EDIT: I'm actually basically finished with the while thing, it just isn't very user friendly yet. If people are interested I can answer with the two scripts it is currently running as. I haven't managed to get it into one without Unity crying and I'm not certain why.

# Answer
> 6 votes
I see your problem, so let's run through the code here. At the start, you say there are (1440 * 60) seconds in a day, but then you proceed to define the number of hours in the day, the number of minutes in an hour, and the number of seconds in a minute. It works when the numbers are correct, but let's go through the logic of what happens if you define 600 seconds in a day (so 10 minutes in "realtime" is a day). What happens is you have \_dayLength = 600. This is then divided by 24, which gives a result that is the number of seconds in your new hour. \_hourLength = 600 /24, so an hour is now 25 units, which in this case is "realtime seconds". You then define a minute as being \_hourLength / 60, so \_minuteLength is 0.417 (rounded up) "realtime seconds". You then define a \_secondLength as being \_minuteLength / 60, so a second is now 0.007 "realtime seconds".

Taking the function CalculateTime(), the first thing it does is see if the timer that has expired since the last time we ran this is greater than \_secondLength. For the purposes of this example, let's say your timer value comes in at 0.1 "realtime seconds". In CalculateTime, it checks to see if timer is greater than \_secondLength, which it is. So currentSeconds gets incremented by 1 (and for the purposes of this discussion, it is starting at 0, so it is now 1), and timer is set to 0. The next compare is whether currentSecond \>= minuteLength. Since minute length is set to 0.417 "realtime seconds", and 1 is definitely greater than 0.417, currentSeconds is getting set to 0, and currentMinutes is being incremented by 1. Our timer is already way off here, but everytime we hit this loop, as long as timer is greater than \_secondLength, we'll increment another minute. If we call this loop 60 times a second, then in 1 second an hour has gone by, and in 24 seconds a day has gone by.

There's a number of failures in this code, but it all starts with a fundamental one, which is that you are not consistent in whether you measuring "game seconds" or "realtime seconds". \_secondLength is 0.007 "realtime seconds", which is fine, but where it gets mixed up is in the comparison of CurrentSecond \>= \_minuteLength. CurrentSecond is in "game seconds", not "realtime seconds", but \_minuteLength is a minute measured in "realtime seconds", so you can't compare the two. I am assuming you still want 60 seconds in a minute, no matter what, so CurrentSecond \>= \_minuteLength should actually be CurrentSecond \>= SecondsToTheMinute. This same problem occurs down the line with the rest of the time intervals.

There's an additional bug in the code, which is that everytime you call this loop, if more than one "game second" has passed, you will only count the first one, so it's not counting the overflow condition correctly. What you want to do is something like this:

```
while (timer >= _secondLength)
{
        currentSecond++;
        timer -= _secondLength;
}

```

This will make it count correctly if more than one "game second" has passed. The same overflow condition exists in your other tests, so here's the whole CalculateTime function fixed:

```
void CalculateTime ()
{
    while (timer >= _secondLength)
    {
        currentSecond++;
        timer -= _secondLength;
    }
    while (currentSecond >= SecondsToTheMinute)
    {
        currentMinute++;
        currentSecond -= SecondsToTheMinute;
    }
    while (currentMinute >= MinutesToTheHour)
    {
        currentHour++;
        currentMinute -= MinutesToTheHour;
    }
    while (currentHour >= HoursToTheDay)
    {
        currentDay++;
        currentHour -= HoursToTheDay;
        dayOrNight = "AM";
    }
}

```

# Answer
> 2 votes
```
_hourLength = _dayLength / HoursToTheDay; //determines how long an hour is
_minuteLength = _hourLength / MinutesToTheHour; //determines how long a minute is
_secondLength = _minuteLength / SecondsToTheMinute; //determines how long a second is

```

Could be all that. Integer division results in integers, and you didn't supply enough code to know what type `_dayLength` and friends are.

In general, just get rid of all this hour and minute math. Count everything by seconds from some epoch. A 32-bit count of seconds is enough to hold almost 70 years; a 64-bit count of seconds is more time than the universe has left.

Just be sure to sensibly deal with frame time updates. e.g., a frame might only take 5 milliseconds, but you can't add `.005` to an integer and get a useful result. You could keep a second floating-point time accumulator that rolls into your seconds count every time it reaches `1.0`, or you could even just use `double` for your seconds count.

You can get the current year, month, day, hour, minutes, and seconds by simply dividing that world time counter by the appropriate value; no need to keep track of them. You can scale the speed of time by simply multiplying the elapsed time before adding it to the time counter; no need to modify any other expression or constants in the system.

# Answer
> 2 votes
If a in-game day is 10 minutes in real life, you just need to get the number of seconds since the last 10 minutes and add a ratio to convert it to a 24 hours format.

Get the number of seconds from the last 10 minutes.

```
realTimeSecondsSinceTheLast10Minutes = (Minutes % 10) * 60 + seconds;

```

Get the ratio between a 10 minutes day to a 24 hour day

```
ratio = (60*60*24) / (60*10)

```

And add that ratio

```
worldSecondsSinceBeginingOfDay = realTimeSecondsSinceTheLast10Minutes * ratio;

```

And now you have a the number of world seconds since the beginning of the day. This can be converted to hours/minutes in a multiples of ways.

```
worldHours = worldSecondsSinceBeginingOfDay / 60 / 60
worldMinutes = (worldSecondsSinceBeginingOfDay % (60 * 60)) / 60
worldSeconds = worldSecondsSinceBeginingOfDay % 60

```

If you don't need to display the time, just work with realTimeSecondsSinceTheLast10Minutes and assume that a day is (60 * 10) seconds long.

# Answer
> 2 votes
**\[EDIT\]** (Original post below)

I found an even simpler way of doing this, using the TimeSpan class. I also updated the class to be semi-singletonish, with an 'Instance' property that gets auto set in the Awake event. (Just make sure not to use this before it is 'Awoken')

You only need to add this script to any existing game object in your scene, and you can access the timer like 'GameTimer.Instance.GameTime.Minutes' for example, from anywhere in your code.

While running, I watched the debug output while I adjusted the TimeRatio in the inspector and the time did slow down or speed up accordingly, so this appears to be working.

```
using System;
using UnityEngine;

public class GameTimer : MonoBehaviour {
    public static GameTimer Instance;
    public float TimeRatio = 0.01f;                         // Game Day ratio to Real Day
    public TimeSpan GameTime = new TimeSpan();              // Current adjusted game time
    private float gameSeconds = 0;                          // Accumulated 'Game Time' in seconds

    void Awake() {
        Instance = this;
    }

    public void Update() {
        gameSeconds += Time.deltaTime / TimeRatio;          // Add to 'GameTime' - number of ms at 'TimeRatio' rate
        GameTime = TimeSpan.FromSeconds(gameSeconds);       // Convert to a usable format
        Debug.Log("Current Game Time: " + ToString());
    }

    public override string ToString() {
        //                        DAYS,  HOUR : MINS : SECS . MS
        return string.Format("{0} Days, {1:00}:{2:00}:{3:00}.{4:000}", GameTime.Days, GameTime.Hours, GameTime.Minutes, GameTime.Seconds, GameTime.Milliseconds);
    }
}

```

## ------------------------------------------------------------

**\[ORIGINAL POST\]**

The following should give you what you want.

```
public class GameTimer : MonoBehaviour {
    public float TimeRatio = 0.01f;                     // Game Day ratio to Real Day
    public float GameTime = 0;                          // Accumulated 'Game Time' in seconds

    public void Update() {
        GameTime += Time.deltaTime / TimeRatio;         // Add to 'GameTime' at 'TimeRatio' rate
        Debug.Log("Current Game Time: " + ToString());
    }

    public override string ToString() {
        //                        DAYS,  HOUR : MINS : SECS . MS
        return string.Format("{0} Days, {1:00}:{2:00}:{3:00}.{4:000}", Days, Hours, Minutes, Seconds, Milliseconds);
    }

    public int Milliseconds {
        get {
            return (int)((GameTime - TotalSeconds) * 1000);
        }
    }

    public int Seconds {
        get {
            return TotalSeconds % 60;
        }
    }

    public int Minutes {
        get {
            return TotalSeconds / 60 % 60;
        }
    }

    public int Hours {
        get {
            return TotalSeconds / (60 * 60) % 60 % 24;
        }
    }

    public int Days {
        get {
            return TotalSeconds / (60 * 60 * 24);
        }
    }

    public int TotalSeconds {
        get {
            return (int)GameTime;
        }
    }

}

```

The TimeRatio is what fraction of a real day the game day is. So 0.01 means the game day is 1/100th of a real day.

You can adjust the TimeRatio mid-game, and it will blend perfectly - only affecting the time from now on. Useful for powerups / modes that temporarily increase or decrease clock speed.

Just use GameTimer.Seconds, GameTimer.Hours, GameTimer.GameTime, GameTimer.ToString(), etc in your code to access the various properties. (If you make everything static, or via a reference variable.)

I haven't tested this too much, just thought it was a neat challenge, and may one day use it in one of my games.

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


# Question
Title: Java LWJGL - How can I add water to my 3d world?
The title says it all, how can I implement a simplistic water system into my game? I am using Java LWJGL and OpenGL glsl shaders. I am still fairly new to game programming, and a complete noob in the use of shaders so some guidance and a thorough explanation would be great!

# Answer
> 0 votes
Well you could just start with a plane/quad with a static/animated water texture. From there you could maybe make an animated mesh with a texture. If you want to get into shaders, then you'd have to research the optical physics of water before trying to develop any

---
Tags: java, shaders, lwjgl, water
---


# Question
Title: How can I create 2D, sprite-based reflections in HTML5 Canvas?
I'm trying to create simple reflections in a 2D, sprite-based game using HTML5. I'm looking to recreate an effect like the one you'd often see in GBA games, such as Pokemon Emerald and Mother 3:

These days we don't really get to see many 2D games that pull off this kind of effects. How could I achieve this with HTML5 Canvas?

# Answer
> 4 votes
1. Draw the water

2. Draw your sprites, flipped upside-down about the water level, and with some effects

3. Draw the ground (this covers the reflection and water)

4. Draw everything else normally

http://jsfiddle.net/cgzrwhpn/

---
Tags: 2d, html5, html-canvas, reflection-rendering
---


# Question
Title: Applying statements to a single instance in Game Maker?
I'm currently in the process of making a platformer, and am currently in the process of creating **"depth"** into my game, by making Up/Down-W/S control your depth. (Come closer to screen, go further).

The reason I chose to do this is so I can walk around stairs, go behind tables, etc.

But I have run into a problem.

When I call in my **player** code, `if (depth == oWall.depth) {//code}`, it is applying to every single **wall** ever. Is there a way to only make it apply to the object you are currently touching?

Here is my code so far:

```
/// Collision

// TODO: Make "depth" apply to a singular instance.
//   \/          \/
if (depth == oWall.depth) {

    /*
        Colliding with a wall on the Horizontal Axis, causes the player to stop moving.
    */

    if (place_meeting(x + h_speed, y, oWall)) {
        while(!place_meeting(x + sign(h_speed), y, oWall)) {
            x += sign(h_speed);
        }
        h_speed = 0;
    }

    /*
        Colliding with a wall on the Vertical Axis, causes the player to stop moving.
    */

    if (place_meeting(x, y + v_speed, oWall)) {
        while(!place_meeting(x, y + sign(v_speed), oWall)) {
            y += sign(v_speed);
        }
        v_speed = 0;
    }
}

```

Hope you understand what I'm asking.

# Answer
You probably need to check for collision first, then check for depth. You can get the wall you are colliding with using `wallHit = instance_place(.., .., oWall)` then compare `depth` with `wallHit.depth`.

Since you are checking collision twice, once for movement on each axis, you will need to check twice just in case there is a different collision result in each case.
> 0 votes

---
Tags: collision-detection, game-mechanics, platformer, game-maker, depth
---


# Question
Title: Sprite animation with "overlapping" animations?
I'm trying to implement my own sprite animation system, and so far I've got it working quite nicely. I store each animation as a "take" which basically denotes the row of the animation in the sprite sheet, the starting frame and the number of frame. These takes are created during start-up and played by calling `play(takeID)` on the animation. The player is split into four sprites: head, torso, arms and legs, and different animations can be played on each of these separately from the other parts.

Now, this works fine for situations where I only need a single animation (walking, idling, running, swinging a sword etc.), but I need a more complex animation system for situations where the player performs multiple things at the same time, for example walking while swinging a sword.

I've tried to break down the requirements of the animation system by using the example above, and I've found these cases:

```
1. Player swings the sword
    1.1. Play swinging animation
    1.2. When done, play idle animation

2. Player starts walking
    2.1. Play walking animation until player stops
    2.2. Play idle animation when player stops

3. Player walks and swings the sword
    3.1. Play walking animation
    3.2. Replace the animation of the hands by a swinging animation
    3.3. When swinging animation is done, revert back to the "walking hands" animation

4. Player walks, initiates a swing and stops walking during the swing
    4.1. Play walking animation
    4.2. Replace the animation of the hands by a swinging animation
    4.3. (Player stops walking during the swing)
    4.4. Stop walking animation and play idle animation for
         all other body parts except the hands
    4.5. When swinging animation is done, play idle animation for hands

```

I've tried fiddling around with "overriding" animations where the animation with the higher priority (in this case, the "swinging" animation) would be shown instead of the lower priority animation (the walking animation) while updating still both simultaneously to maintain the correct rhythm of the original animation. However, I have trouble getting it to work properly.

The "reversion to idle animation" is a rather challenging task: if I have just the single walking animation, I can stop it and then play the idle animation (or rather, the "idle frame"), but when the sword swinging is added, it becomes more difficult to know when to swap to the idle animation.

So, to conclude with my question: has anyone faced a similar problem? How should I tackle this issue?

# Answer
> 1 votes
Sounds like you have one-half of this problem licked: your player is split into independent sprites with their own animations. That seems totally reasonable for what you want to achieve.

I think the next step is to investigate state machines. With state machines you could define your various states (idle, walking, attacking, falling, and so on) and then define transitions between them.

It sounds like your particular state machine would be hierarchical in that walking is a "super state" and attacking, at least for the player's hands, is a "sub state".

---
Tags: animation, sprites
---


title: Simplify paths when a user builds

text:
# Question
Title: Simplify paths when a user builds
I am looking for some guidance on how to simplify my nodes on a path when a user builds on the fly.

Imagine a path like this with a gap:

Logically 3 nodes are required 2 connected one isolated.

But now the user builds another inbetween these nodes like this:

You can see the idea is now the nodes have simplified automatically and i only now have 2 nodes on my path.

My question is how would i approach the logic for this so the code can update accordingly? I currently store my path data as an array of nodes which have a property that lists an array of other nodes that link to them. This is what it would look like before the user adds a new tile to the map:

```
var path    = [];
    path[0] = {'x':1,'y':3,'linksTo':[1],'id':0};
    path[1] = {'x':1,'y':4,'linksTo':[0],'id':1};
    path[2] = {'x':1,'y':1,'linksTo':[3] ,'id':2};
    path[2] = {'x':1,'y':0,'linksTo':[2] ,'id':3};

```

I use JavaScript - but the language isn't strictly important only the logical approach here.

I should be more clear, the paths can go in 8 compass directions in total the diagonals will be 45 degree angles rather than any other type of shallow angle. But the image just merely shows an example of a path running north to south.

# Answer
> 1 votes
I'd use two rules, one for tiles and one for corners of tiles:

1. If a floor tile is surrounded by *three* wall tiles and *one* floor tile, then that floor tile is an end of of a corridor, and should be marked with a waypoint.
2. If a corner is surrounded by *one* wall tile and *three* floor tiles, then that corner is a place where you might want to make a turn. The floor tile *opposite* the wall tile should be marked with a waypoint.

I've implemented the second rule with an interactive demo on this page. Try clicking on the Waypoints diagram and see what waypoints it calculates. I haven't implemented the first rule because it's for single-tile-wide corridors and I didn't have that in the demo.

The second part is to link the waypoints together. Line of sight would work for this; there might be better ways.

# Answer
> 1 votes
First off, I would store paths as an array of points/vectors/ whatever they call it in the framework you're using. It's a coordinate, using x and y variables.

When the player builds a path, you know the x and y coordinates of that point (let's call them points). For all your path arrays, check if it contains one of the 8 adjecant points (same x, but y+1, etc). If it contains one of them, it's connected. Now you can go from the point at index 0 in the array, and iterate through them. Check if the angle between A and B is identical to the angle between B and C. If so, remove B from the array (and shift everything down by 1 position in the array). just keep going until you reach the end of the array. All useless nodes have been erased. The only problem here is with intersections. But you could treat them as different paths that simply contain the same point in the array) the intersecting point.

---
Tags: 2d, javascript, grid, path
---


# Question
Title: OpenGL 4.3 in C++ : Drawing static Triangle ("Hello Triangle"). Color does not appear (Triangle is just completely white)
I am going through an OpenGL book trying to get the examples to work. I am using Glew, Glfw, and that's it beyond Opengl 4.3, which my I know my graphics card supports completely via the OpenGL Extension viewer.

The problem is that the triangle displays in the window, but it *flashes* at a fluctuating rate between black/background and completely white. I am drawing the triangle with a red, green, and a blue point. My thoughts were that the **positionData** were too close to the camera (floating point errors/clipping). What could be the source of this error. I've never successfully gotten modern ( 3.X or greater ) OpenGL to work. The setup is really intense.

Here is the main.cpp:

```
#include "shaders\tools.h"
//#define GLEW_STATIC
#define GLFW_DLL                    //Required for linking
#define GLFW_INCLUDE_NONE           //Load our own opengl
#include "glfw\glfw3.h"

using namespace std;

int main() {

    //Use glfw to create window
    if (!glfwInit())
    {
        cout << "Error: could not init glfw" << endl;
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "Shader Demo", nullptr, nullptr);
    if (window == nullptr)
    {
        cout << "failure creating window!" << endl;
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    GLenum glew_err = glewInit();
    if (glew_err != GLEW_OK)
    {
        cout << "Glew Error: " << glewGetErrorString(glew_err) << endl;
        return 1;
    }

    GLuint vertShader_i;
    GLuint fragShader_i;
    bool shader_compile_error = compileShaders( &vertShader_i, &fragShader_i, "basic.vert", "basic.frag");

    if (shader_compile_error)
    {
        cout << "shader compile error!" << endl;
        return 1;
    }

    GLuint glslProgram_i;
    bool shader_link_error = linkShaders( &glslProgram_i, vertShader_i, fragShader_i );

    if (shader_link_error)
    {
        cout << "shader link error!" << endl;
        return 1;
    }
    else
    {
        glUseProgram( glslProgram_i );
    };

    float positionData[] =
    {
       -.8f,  -.8f,  0.f,
        .8f,  -.8f,  0.f,
        .0f,   .8f,  0.f
    };

    float colorData[] =
    {
        1.f, 1.f, 1.f,
        0.f, 1.f, 0.f,
        0.f, 0.f, 1.f
    };

        //Create buffer objects
    GLuint vboHandles[2];
    glGenBuffers(2, vboHandles);
    GLuint positionBufferHandle = vboHandles[0];
    GLuint colorBufferHandle = vboHandles[1];

    //Populate the position buffer
    glBindBuffer( GL_ARRAY_BUFFER, positionBufferHandle );
    glBufferData( GL_ARRAY_BUFFER, sizeof(positionData), positionData, GL_STATIC_DRAW );

    // color buffer
    glBindBuffer( GL_ARRAY_BUFFER, colorBufferHandle );
    glBufferData( GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW );

    GLuint vaoHandle;
    glGenVertexArrays( 1, &vaoHandle );
    glBindVertexArray( vaoHandle );

    //Enable vertex attribute arrays
    glEnableVertexAttribArray(0); //vertexPosition
    glEnableVertexAttribArray(1); //vertexColor

    //map index 0 to position buffer
    glBindBuffer( GL_ARRAY_BUFFER, positionBufferHandle );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

    // map index 1 to color buffer
    glBindBuffer( GL_ARRAY_BUFFER, colorBufferHandle );
    glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

    glBindVertexArray( vaoHandle );
    glDrawArrays( GL_TRIANGLES, 0, 3);

    //show version of opengl
//  glVersionData gl_version_data;
//  getGLVersion( &gl_version_data );
//  glDisplayVersionData( gl_version_data );

    while (!glfwWindowShouldClose(window))
    {
        // Keep running
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

```

basic.vert:

```
#version 430

layout (location = 0) in vec3 VertexPosition;
layout (location = 1) in vec3 VertexColor;

out vec3 Color;
void main()
{
    Color = VertexColor;
    gl_Position = vec4( VertexPosition, 1.0 );
}

```

and basic.frag:

```
#version 430

in vec3 Color;

out vec4 FragColor;

void main()
{
    Color = vec4( Color, 1.0 );
}

```

I can include the "shaders\tool.h" which defines `loadShaderCode`, `compileShaders`, and `linkShaders` if necessary, but I don't want to post too much code to break the flow of my question. They do what you'd expect, and I don't get any errors returned. They load the codes, link them attach them to a program, compile the program and spit out the glsl programHandle.

I'm on windows x64 using g++ 4.8.1. with C++ 11.

EDIT: here is the shader loader function:

```
const GLchar * loadShaderCode(const char * shaderFilename)
{
    fstream shaderFile( shaderFilename, std::ios::in | std::ios::ate);

    streampos end = shaderFile.tellg();
    shaderFile.seekg(0, std::ios::beg );
    streampos beg = shaderFile.tellg();

    string code;
    code.reserve(end-beg);
    shaderFile.read(&code[0],end-beg);
    shaderFile.close();

    return code.c_str();
}

```

WHen I load both shaders, **there is a marking at the end that doesn't make sense**:

```
#version 430

in vec3 Color;

out vec4 FragColor;

void main()
{
        FragColor = vec4( Color, 1.0 );
}o↨☺  // <--- What is this marking???

```

The Vert Shader is very similar. I tried to delete the last character from the returned string containing this code and it changed the closing brace at the end of main. I also tried setting it to zero - then the triangle doesn't display at all, even though the code looks perfect then. What is this character and how do I get rid of it?

THank you @Boreal for the help! Here is the (beautiful result):

# Answer
There's an error in `basic.frag`. Instead of setting `FragColor`, you're setting `Color`, which is an input variable. I don't know why that's not being reported as an error because it is certainly not permitted.

As for the flashing problem, I have a feeling it might be due to a ping-ponging double-buffer setup. Since you only draw the scene once, every other swap is showing a blank buffer. Try moving your draw calls to the main loop.
> 2 votes

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


# Question
Title: How do I derive an appropriate acceleration value for my game?
I am creating a Flappy Bird clone from this tutorial.

I have a question about acceleration in libgdx. The author assigned the bird a constant acceleration vector in the constructor of the bird

```
        acceleration = new Vector2(0, 460);

```

and later updated the velocity vector from the accleration vector with

```
        velocity.add(acceleration.cpy().scl(delta));

```

I understand generally why acceleration is constant - like the author mentioned, acceleration due to gravity is 9.81m/s^2, meaning that the speed of an object falling will increase by 9.81m/s every second. It seems the author somehow got from 9.81 real world value to 460 in the actual code. How does one go about deriving this value? Is this a standard derivation or something the author just made up?

# Answer
How the author specifically got that value was via experimentation. From the comments:

> Q: Hi James, you set acceleration.y to 460. How did you find this number? Is it static?
>
> A: Acceleration was experimentally determined. Its value does not change.

And this is often the case when determining values for your game. You pick a value and play-test with it. Adjust the value according to your play-testing results.

Sometimes you can find something close to the value you want with some calculations. These calculations are similar to real world physics, but you'll need to take into account the game world. In this case the value likely has something to do with the number of pixels per unit of distance.
> 1 votes

# Answer
Adjust birdSpeed and pixelMovement in below code to achieve your 9.8m/s2 speed. s=0\*t+1/2gt\*t

```
Public Class bird extends Actor
{
private float pixelMovement=30;       // No of pixel you want to move bird in one touch
private float birdNextPosition;   //This will be used to hold next position of bird
private boolean birdisMoving=false; // flag to track bird movement
private float birdSpeed=80;
bird()
{
   birdNextPosition=pixelMovement+getY();
}
@Override
    public void act(float delta)
              {
                 // set birdMoving flag true in stage class when you get any touch
                 if(birdisMoving() && getY()<= birdNextPosition)
                     {
                      setY(getY()+birdSpeed*delta);
                     }
                 if(getY()> birdNextPosition)
                    {
                    birdNextPosition=pixelMovement+getY();
                    setbirdisMoving(false);
                     }
               }
 @Override
public void draw(Batch batch, float parentAlpha)
             {
                batch.draw(birdTexture, getX(), getY());
             }
}

```
> 0 votes

---
Tags: libgdx, physics, game-mechanics
---


# Question
Title: In Unity, how do I create a drag and drop object?
I have a 2d scene. I want the player to be able to pick up an object, move it around the scene and drop it somewhere. I can't find any way to do this, and all of the resources for Unity are really daunting and I can't find anything relevant to what I'm doing.

I've tried adding the drag rigidbody script to both my camera and the sprite I want to drag, to no effect.

Where can I find relevant documentation for stuff like this? Basic things like how to implement a script or what objects I need to attach these scripts to - the stuff on the unity website is a little too advanced.

# Answer
Basically you say that the Object follows your mouse coordinates after you clicked it.

Use: `if (Input.GetMouseButtonDown(0)){
 /*Move Object which gets hit by the Raycast you shoot to Mouse coordinates */};`

Also you have to convert the world coordinates to screen coordinates.

Here is a good Tutorial for that: Klick
> 1 votes

---
Tags: unity, 2d
---


# Question
Title: Why do mobile games have delays for certain actions?
Many phone games restrict the number of actions you can take in a given amount of time. I don't get what is the purpose of this limitation. Is it only to force the player to buy additional turns? Some games don't even allow this for some turn "kinds" (like action A can be played again by spending real money while action B cannot be played again by spending money).

Another possible reason would be to limit the bandwidth usage to their server and make it more predictable over time, but I can't see phone games using so much data.

# Answer
If you can buy more turns then it's for monetization.

The non-buyable turns are to keep you playing over time. You have no choice but to wait until they regenerate which means you will come back the next day to spend them and then see the advertisement to buy more turns of the other kind.

If it is a multiplayer game then the goal is usually to limit the grinding options and keep casual and hardcore gamers at roughly the same level.
> 3 votes

# Answer
1. It's an easy way to make money from addicted players. You're so close to the goal, but you die. You can pay $5 to replenish your lives now or wait 2 hours. You want to play one more turn but you can't, unless you wait or pay. Repeat indefinitely because you're addicted and...
2. ... the game enforces delays so that you have something to return to later. Instead of going through the game quickly, you split your gameplay over a large period of time, with short sessions of play. This fits the mobile market well because people have their devices with them all the time, and boring moments can be filled with their favorite game instead. Usually, around that time, the delays have expired and the game has something new to show the players.

Fragmented gameplay also helps alleviate the impact of paying real money. For example, the user may not be likely to spend $10 in a single session, but he may be likely to spend $10 in a few more sessions with N days in-between.
> 3 votes

# Answer
Limiting turns is a general way of equalizing a game, making sure it balances.

For example, in online MMORPGs, players with fast computers or a fast internet connection would otherwise be unbeatable, while players with a slow connection would constantly fail in a game. (This already happens, but it is a much less severe imbalance *because* of turn limiting).

Also, it can be used in some cases to prevent people from benefiting disproportionately from automated scripts that help them win a game. Even if their script pumps commands into the game at a high speed, their character can't move faster than any other player, or NPCs they are competing with.

By limiting the number of actions to be done over time, you limit everything else, and make it possible to have e.g. an enemy that is intentionally impossible to win against. (E.g. at the edge of a map). Or you can have an enemy at the gate to a dangerous area that threatens (but does not damage) players of a lower level, and that way prevents beginners from accidentally walking into e.g. a PvP area before they're powerful enough.

This problem was for example the reason for the "Turbo" button on old PCs. Turning off the Turbo would force the CPU to run at half-speed, like the previous models. If you didn't do that, games that didn't limit the number of turns would run too fast, and became unplayable.

It's a tried-and-true technique, you also have the same concept in most board and card games, where each player takes a turn before the next one is permitted to do theirs.
> 0 votes

---
Tags: turn-based, monetization
---


# Question
Title: Releasing a demo in an unfinished state?
I'm a fairly unexperienced game developer, (despite having some coding abilities) as i never really had the opportunity to launch more than 1 "finished" game. So in terms of getting the word out, marketing or even getting usefull feedback of players, i have very little experience.

Now, i'm working for almost 3 years on a game which i'm developing in my spare-time. Despite its pretty long development cycle it is a fairly "simple" game.

The question i'm asking myself multiple times (and more frequently as time goes on) is: \- When should i release a demo? (Should i release a demo at all?)

I don't want the players to play it now and loose interest afterwards after the game finishes. (as it will take maybe another full year until it is even remotely finished.) But at the same time i know that i have to do something in terms of marketing (it is going to be a free game, but i would like to reach as much people as i can) as despite the 3 year long development cycle, not many people know about this project. (Which isn't really optimal, as i have a potential target audience which i know would like a game of this type.)

My strategy up to this point was to simply develope it in my spare time, not having a demo at all and only showcasing (meaningfull) progress of the game in youtube videos (This videos are released every 2 or 4 months, depending on how much time i have to develope the game...) and only release the game after it is more or less finished.

Its a very strage scenario for me to be in. I would love to let people know about the project (like every other dev), but at the same time i fear that people will be put down by its quality (alpha-state) and that they aren't going to be interested in it afterwards after they played it. (The only thing you can currently do is to "free-roam" \> no objectives whatsoever.)

So my question is: Am i to worried about this stuff? Should i release a demo? (Now or later after it's more polished?) What are your experiences in releasing games or using demos?

# Answer
Releasing unfinished versions long before the release of the finished version is becomming increasingly popular among indie developers and even larger studios under the label "Early Access".

The advantages are clear:

* Obtaining new financial capital before the product is finished
* Intensive playtesting by the community to find bugs and get feedback
* Generating hype
* Testing if the game is marketable before spending the whole development budget

However, there are also some disadvantages:

* The early access buy-in is usually lower than the final price, which means that the early access buyers generate less revenue than they would have paid when they would have bought it on the actual release day (although the generated hype during early access usually makes more than up for it)
* While the software is in early access, the developers must provide support and regular updates which add new features to keep the community interested. This greatly reduces project planning freedom.
* When your game doesn't offer much long-time motivation and replay value, the developers risk "burning out" their community with a long early access phase. When they finally release the game for full price, the popularity might already be beyond the peak.
> 1 votes

# Answer
As the Game is free and you seem to love what you are doing but you want attention for your Game without disappointing someone, I would recommend sharing as much of your work as possible to as many Persons as possible.

I'm a Webdeveloper and one thing I've learned since I'm working highly professional, is the importance of a short feedback cycle.

I love the Idea of "Lean Startup". Basically this Guy did a MMPORG and collect his experiences, advantages and mistakes he did with that Project. One main principle was to share the Product as often as he can to his customers. But the really Important thing is, to have channels to measure the reactions and improve the Product every time with the next iteration.

Even though I'm a Webdeveloper we use this Principle every Day to stay in our Business.

The other aspect I like, you could use as well is open sourcing your Project. That does not mean, that everyone can break your Code. In fact with tools like Github, you can share your Code, other People can contribute and you decide wether you want the changes or not.

And as soon as you integrate some changes into a stable Branch, you can provide a Download link to the current Demo/Preview/Early Access/Alpha Version to your followers. Also a Project Page (a Blog works well), is always nice, to keep the Followers up to date.

So Basically this answer only tries to help you to decide more into the direction of an early demo by solving the Problems @Philipp mentioned like:

* updates on a regular basis
* burning out the community

If you follow these Principles it may happen that your Game become maybe as popular as Minecraft. So release often, collect Feadback and Improve your Product as often as possible, that would be my advice.

If your still afraid delivering sth. broken or not complete, try to show, the possibilities and the Goal you want to achieve. Maybe also provide a small Roadmap with Tasks you want to finish as a prioritized list.

Hope I could help you out.
> 0 votes

---
Tags: demo
---


# Question
Title: Simple LibGDX Pong game drag player instead of getting x position
I got a working pong game in LibGDX but when I touch the screen the player x automaticly jumps to the coordinates I touched. I wan't my game to detect I touched and then move the player to the left/right if I swipe my finger to the left or the right.

This is what I tried so far:

```
if(Gdx.input.isTouched() && Gdx.input.getY()>240*screenheight){
  if(tapped)TouchX = Gdx.input.getX();
    tapped = false;
    DragX = Gdx.input.getX();

    distance = player.getX() - TouchX;

    PlayerX = Gdx.input.getX() + distance;

    Gdx.app.log("PlayerX "+player.getX(), "Distance "+distance);
    Gdx.app.log("DragX ", ""+DragX);
}else{
    tapped = true;
}

```

Here I update the player X coordinates

```
player.setX(PlayerX);

```

Does anyone know how to make this work?

# Answer
> 1 votes
You can use InputAdapter class and methods

```
touchDown(int screenX, int screenY, int pointer, int button)
Called when the screen was touched or a mouse button was pressed.

boolean touchDragged(int screenX, int screenY, int pointer)
Called when a finger or the mouse was dragged.

boolean touchUp(int screenX, int screenY, int pointer, int button)
Called when a finger was lifted or a mouse button was released.

```

# Answer
> 1 votes
You could update the position over time:

```
currentPos = currentPos + Math.signum(currentPos - touchedPos) * wayPerTime * deltaTime;

```
* `wayPerTimestep` is your velocity.
* `deltaTime` is the time passed since the last update.
* `currentPos` is the current position of your player (might be `x`, `y` or both as vector).
* `touchedPos` is the position the player has clicked on the screen (might be `x`, `y` or both as vector).

`Math.signum()` gives you `+1` if the value is positive or `-1` if negative. Otherwise `0`. This takes care about the same speed regardless how big the distance is between player and clicked position.

The code uses this formula for calculating the way ***s***:

---
Tags: java, libgdx, touch
---


# Question
Title: Category/genre name for games like: Ogame, Kings of Chaos, and Bitefight.?
I'm searching for a category name for games like: Ogame, Kings of Chaos, and Bitefight.

When I learned about those, they were just called browser games, but today where we have the technology to create every genre of games in the browser, I miss a box to put these: 'only text, pictures and no fancy animation-games' into.

Do they actually have a name, leading to my Google-Fu being miserable?

# Answer
They are called browser based games as you've guessed.

There are many technologies used to create browser based games however. You may want to limit your searches to technologies that don't support 3D or advanced gameplay. For example, searching for PHP browser games or HTML 4 browser games would likely limit you to the only-text-pictures-and-no-fancy-animation-games you're looking for. Further, you can search for 'Text based browser games', even though it sounds like it's limited to text only, these frequently include images as well like the games you've listed.
> 0 votes

---
Tags: browser-based-games
---


title: Crop a texture procedurally

text:
# Question
Title: Crop a texture procedurally
Is there a way to crop a texture having a list of triangles which represent the part to be kept?
For instance, I have a rectangular texture and I want to obtain a texture shaped by the triangle list I have.

# Answer
> 2 votes
I don't think you can have non-rectangular texture. But you could get a bounding box for the vertices and crop the texture with it. Just read the pixels inside the bounding box and write them to a new texture instance.

```
Vector2i min = triangleslist[0]; // Assuming the list is integer Vector2 list
Vector2i max = triangleslist[0]; // and the vertex positions are in pixels

foreach(var p in triangleslist) {
    if(p.x < min.x)
        min.x = p.x;

    if(p.x > max.x)
        max.x = p.x;

    if(p.y < min.y)
        min.y = p.y;

    if(p.y > max.y)
        max.y = p.y;
}

var size = max - min;
var texture = new Texture2D(size.x, size.y, TextureFormat.ARGB32, false);

for(int x = 0; x < size.x; x++) {
    for(int y = 0; y < size.y; y++) {
        texture.SetPixel(x, y, originalTexture.GetPixel(x + min.x, y + min.y);
    }
}

```

---
Tags: unity, unityscript
---


title: Reflection/environment mapping

text:
# Question
Title: Reflection/environment mapping
I'm implementing reflection/environment mapping using a cubemap. I have it working for the most part but when I move my camera around, I see the same area reflected on the object. I am calculating the eye vector and normal vector in view space similar to OpenGL Shading Language 3rd Edition example (p.311, Section 10.4).

Why does the reflection stay as if it is from the same view?

Which space should I be doing my calculations?

How render looks:

Snippets of HLSL code

Vertex shader:

```
normal = mul( (float3x3)mvMatrix, input.normal );
normal = normalize(normal);
viewPos = mul( mvMatrix, float4(input.pos, 1) );

```

Pixel shader:

```
viewPos.w = 0;
V = normalize(viewPos);
normal.w = 0;
normal = normalize(normal);

float4 reflectVec = normalize(reflect(V, normal));
float4 reflectColor = tex.Sample(samLinear, reflectVec.xyz );

```

# Answer
Right now you transform the normal by both the model and view matrices. Instead, just transform by the model matrix. If the view matrix is identity and you're just manipulating the model matrix, then the image results are expected, since rotating a teapot doesn't rotate the world around it. In that case, you should switch and leave the model matrix fixed, and manipulate the view matrix, so that you're manipulating the camera instead of the teapot.
> 1 votes

---
Tags: directx, lighting, cubemap, reflection-rendering
---


# Question
Title: Does conservation of energy exist in most physics engines?
The reason I am wondering, is because while trying to create gravity around a point in the physics game I am creating, I wondered "*If I create an object in the middle of the screen, where would the energy come from to allow it to fall towards the object of mass?*" So this leads me to wonder, is the gravitational energy for an object created (defying the law of conservation of energy), and if so, why do objects orbiting another object not speed up to infinity?

PS: I didn't know whether or not to put this question here, or in physics, but I assume it's more applicable here. (I am also using c++ and SFML if it is important, or you want to include some source code as an example)

# Answer
It's really only the creation of an object out of thin air that violates natural law, since it's the position at which the object is created that generates GPE. All forces are entropic, which is to say (in a tremendous simplification of terms) that they cause systems to evolve toward a resting state. The more starting energy the bigger the forces, and the faster (usually) the final state is reached. It's actually change in force, the gravitational attraction between one thing and another which popped into existence, that "generates" energy.

Energy would be conserved in such a system if, say, you could only create 5 objects, and they eventually reached a final position where they orbited each other or landed, the energy would end up being retained as angular momentum. We could explain away rounding errors (which should be in favor of energy loss) as universal entropy. =P
> 0 votes

# Answer
After some rounding errors energy will be different from one step to the next.

Most physics engines just let you apply forces to objects nilly willy and don't care where the "energy" for the work it is doing would have come from and letting the programmer decide how it came about.
> 4 votes

---
Tags: physics
---


# Question
Title: Understanding Scene Graphs and Graph Edges
So I'm trying to getting to grips with using Scene graphs and nodes in my code (game coding in C++) and I think I understand the basics of them and how they are used (and I can definitely see the benefits), but I'm coming across the term "Graph Edge" and I can't find any reading material explaining exactly what they are and how they fit in with Scene Graphs/trees/nodes in object hierarchy structures.

If anyone knows of any good material or has their own answer on what graph edges are and how they fit in (in use and implementation) that would be great.

Thanks

# Answer
> 1 votes
You probably don't need to worry about the edge concept explicitly, in scene graphs.

Any time that a parent object in the scene graph holds a reference to one or more children, that reference (pointer) is itself the connection that would be termed an "edge". It it is likely that the child also holds a reference back to the parent. These are just pointers. Being a trivial connection, we need no additional information in the connection other than the target it points to. So a pointer alone suffices.

This is very different from graph applications such as often used in planning utilities networks, which seek the most cost-effective paths across a graph; see MSTs for more. These sorts of graphs require explicit edge information... in this case, edge weights representing (monetary) cost. Nodes are usually explicit in code, as represented by a class or struct (a block of memory). Edges OTOH are usually implicit for the reason described above.

Be aware that with explicit nodes and implicit edges, a path across a graph might be `node->node->node`; this is compact. When both nodes and edges are explicit, the same path would be `node->edge->node->edge->node`. This latter form increases the number of memory jumps (the arrows) to get from first to last node, increasing the chance of a cache miss. So unless you explicitly need edges, just reference one node from another, keeping memory access tight.

---
Tags: c++, scene-graph, graph
---


title: Getting the real fragment depth in GLSL

text:
# Question
Title: Getting the real fragment depth in GLSL
I am trying to write a simple GLSL shader that just renders the real (not normalized) depth of a fragment as a floating point value.

So far, I've figured out how to get the depth of a vertex, and just interpolate across the fragments, but I'm starting to realize that this is not going to give me the correct depth of each fragment, is it?

Here's what I have so far:

Vertex shader:

```
uniform mat4 world;
uniform mat4 view;
uniform mat4 projection;
attribute vec3 position;
attribute vec3 color;
varying float distToCamera;
void main()
{
    vec4 cs_position =  view * world * vec4(position, 1.0);
    distToCamera = -cs_position.z;
    gl_Position = projection * cs_position;
}

```

Fragment shader:

```
varying float distToCamera;

void main()
{
    gl_FragColor = vec4(distToCamera, distToCamera, distToCamera, 1.0);
}

```

# Answer
> 5 votes
~~Yes, your Z value, distToCamera, will be correct at each triangle's vertices, but won't be anywhere else (except between vertices of matching Z-value), because of linear interpolation.~~

*Edit: In current GLSL, the default interpolation is "in perspective", where gl\_Position/gl\_FragCoord is taken into account for interpolating. This can be overridden (you won't want to for your case) as a type qualifier, like:*

```
noperspective out float distToCamera;  // vertex shader
noperspective in float distToCamera;  // fragment shader

```

*Alternatively, you can get it recover it from gl\_FragCoord...*

In a fragment shader, `gl_FragCoord` contains `(x, y, z, 1/w)` in window coordinates. x, y, and z have already been divided by w.

So, you can recover your vertex shader output, `gl_Position.z`, interpolated correctly in 3d, as

```
float originalZ = gl_FragCoord.z / gl_FragCoord.w;

```

(Depending how you've done your vertex shader projection matrix, this might not be your world Z, of course.)

---
Tags: opengl, graphics, glsl, depth-buffer
---


title: Refer to a gameobject on start

text:
# Question
Title: Refer to a gameobject on start
So I want my script to set the initial position of an object depending on the size of the screen and whatever. How do I refer to the gameobject? I know you can modify stuff like their location if the user clicks on it, but how do I refer to the gameobject right when the program starts?

Also, would it be better to have the object already exist and then move it to the right location on start, or instantiate it in the right location on start? How would I do either of these things?

# Answer
Attach the script to the object itself and you can manipulate it in the built-in `Start` (Reference). It's similar to the `Update` function except instead of being called every frame it's called when the script begins.

```
public void Start ()
{
    DoStuff();
}

```

There's also the function `Awake` (Reference) which is the same except happens earlier in the initialization chain with the noted difference that in `Awake` not everything may be set up yet. AND `Awake` will run even if the script isn't enabled.

```
public void Awake ()
{
    DoStuff();
}

```
> 1 votes

# Answer
You can reference objects within the scene by linking them to the script component in Unity's editor. Either declare the variable as public or use SerializeField so that the variable appears in the Inspector, and then drag an object from the scene onto that variable.

EDIT: Write either this

```
public GameObject object;

```

or this

```
[SerializeField] private GameObject object;

```

at the top of your script. Now the variable 'object' will show up in the Inspector within Unity's editor, and you can drag objects onto that variable.
> 0 votes

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


# Question
Title: What causes this distortion in my perspective projection at steep view angles?
For various reasons – partly educational, partly technical – I'm writing a 3D game engine from scratch, using OpenGL 3.0; aiming for Core Profile, eventually, so of course I'm using a custom matrix stack and shaders. I've got nearly all of that working, but I'm getting strange results and not sure where I'm making a mistake.

The problem: using a perspective projection matrix (based on the formulas from the OpenGL 2.1 Reference), everything looks great… until I aim the camera up or down at a steep angle, when it gets horribly distorted, as shown in the screenshots below.

I've checked out the answers here (though the video is unavailable, so I'm not sure if it's the same sort of distortion), and double-checked my code against my references. So far as I can tell the math is correct and I don't see any glaring typos, but I'm hoping a fresh pair of eyes can help me find the cause – thanks in advance.

### Code

If there's anything else relevant you need to look at, just ask.

```
Vector3f Util::normalize(const Vector3f &v)
{
    float d = std::sqrt(dot(v, v));
    return d ? (v / d) : v;
}

Vector4f Util::buildQuaternion(const Angle &angle, const Vector3f &axis)
{
    Angle halfAngle = 0.5f * angle;
    float c = halfAngle.cos(), s = halfAngle.sin();
    return Vector4f(s * axis.x, s * axis.y, s * axis.z, c);
}

Vector3f Util::rotate(const Vector3f &p, const Vector4f &q)
{
    Vector4f r = qmul(qmul(q, Vector4f(p.x, p.y, p.z, 0.0f)), ~q);
    return Vector3f(r.x, r.y, r.z);
}

void Util::orbit(Vector3f &planet, const Vector3f &sun, const Vector3f &up, const Angle &yaw, const Angle &pitch)
{
    Vector3f f = planet - sun;
    Vector3f s = cross(up, f);
    Vector4f qx = buildQuaternion(pitch, normalize(s));
    Vector4f qy = buildQuaternion(yaw, normalize(up));
    Vector3f r = rotate(f, qmul(qx, qy));
    planet = r + sun;
}

Transform &Transform::makeRotate(const Vector4f &q)
{
    float xx = q.x * q.x;
    float xy = q.x * q.y;
    float xz = q.x * q.z;
    float xw = q.x * q.w;
    float yy = q.y * q.y;
    float yz = q.y * q.z;
    float yw = q.y * q.w;
    float zz = q.z * q.z;
    float zw = q.z * q.w;
    float ww = q.w * q.w;

    float *m = m_matrix;
    m[ 0] = 1-2*(yy+zz); m[ 4] =   2*(xy-zw); m[ 8] =   2*(xz+yw); m[12] = 0.0;
    m[ 1] =   2*(xy+zw); m[ 5] = 1-2*(xx+zz); m[ 9] =   2*(yz-xw); m[13] = 0.0;
    m[ 2] =   2*(xz-yw); m[ 6] =   2*(yz+xw); m[10] = 1-2*(xx+yy); m[14] = 0.0;
    m[ 3] = 0.0;         m[ 7] = 0.0;         m[11] = 0.0;         m[15] = 1.0;
    return *this;
}

Transform &Transform::makeRotate(const Angle &angle, const Vector3f &axis)
{
    return makeRotate(Util::buildQuaternion(angle, axis));
}

Transform &Transform::makePerspective(const Angle &fov, float aspect, float zNear, float zFar)
{
    float f = (fov * 0.5f).cot();
    float e = f / aspect;
    float g = (zFar + zNear) / (zNear - zFar);
    float h = 2.0f * zFar * zNear / (zNear - zFar);

    float *m = m_matrix;
    m[ 0] =  e ; m[ 4] = 0.0; m[ 8] =  0.0; m[12] = 0.0;
    m[ 1] = 0.0; m[ 5] =  f ; m[ 9] =  0.0; m[13] = 0.0;
    m[ 2] = 0.0; m[ 6] = 0.0; m[10] =   g ; m[14] =  h ;
    m[ 3] = 0.0; m[ 7] = 0.0; m[11] = -1.0; m[15] = 0.0;
    return *this;
}

Transform &Transform::makeLookAt(const Vector3f &eye, const Vector3f &center, const Vector3f &up)
{
    Vector3f f = Util::normalize(center - eye);
    Vector3f u = Util::normalize(up);
    Vector3f s = cross(f, u);
    u = cross(Util::normalize(s), f);

    float *m = m_matrix;
    m[ 0] =  s.x; m[ 4] =  s.y; m[ 8] =  s.z; m[12] = 0.0;
    m[ 1] =  u.x; m[ 5] =  u.y; m[ 9] =  u.z; m[13] = 0.0;
    m[ 2] = -f.x; m[ 6] = -f.y; m[10] = -f.z; m[14] = 0.0;
    m[ 3] =  0.0; m[ 7] =  0.0; m[11] =  0.0; m[15] = 1.0;
    return translate(-eye);
}

void Camera::orbit3P(const Angle &yaw, const Angle &pitch)
{
    /// 3rd-person orbit - move camera around subject
    Util::orbit(m_eye, m_center, m_up, yaw, pitch);
    m_dirty = true;
}

void Camera::orbit1P(const Angle &yaw, const Angle &pitch)
{
    /// 1st-person orbit - change camera direction
    Util::orbit(m_center, m_eye, m_up, -yaw, pitch);
    m_dirty = true;
}

```

### Screenshots

Horizontal - all is well

About 45° - distortion begins to appear

Almost 90° - what is this I don't even

(The ortho overlay was to help visualize the camera eye and center locations.)

# Answer
Inside makeLookAt contains your error:

```
Vector3f f = Util::normalize(center - eye);
Vector3f u = Util::normalize(up);
Vector3f s = cross(f, u);
u = cross(Util::normalize(s), f);

```

`s` is not normalized.

It should be:

```
Vector3f f = Util::normalize(center - eye);
Vector3f u = Util::normalize(up);
Vector3f s = Util::normalize(cross(f, u));
u = cross(s, f); // no norm needed because s,f both unit length and orthogonal

```

If `up` and `f` (forward) are perpendicular, then `s` is already (approximately) unit length. That is why it works for looking horizontally but not vertically.
> 2 votes

---
Tags: opengl, camera, projection, perspective
---


# Question
Title: Accurately measure time between calls to onDrawFrame (Android OpelGL ES 2.0)
I'm trying to sort out some timing issues within my gameloop and I've seen something that I don't understand.

The Nexus 10 is supposed to have (as far as I'm aware) a VSync on 60Hz. So that would be mean would it not that **onDrawFrame** is called by the system every 16.66ms?

When I try to measure it I get different readings on every iteration like so:

```
public void onDrawFrame(GL10 gl) {

        Log.v("NewTag","Millis between this call and last: "+((System.nanoTime()-newTime)/1000000));

        newTime = System.nanoTime();
}

```

See my results:

As you can see, it varies between 11.53ms and 21.85ms

Why is it not a constant 16.66 or is it just that nanoTime isn't acurate enough to give a more exact reading?

# Answer
First, as Matthew said it's not going to be exact because of fill rates and whether the \`onDrawFrame' is called before or after you do your drawing.

But this would by my approach. First, I'd average over several seconds. Remember that just printing to the log takes time. You don't need to know the FPS every frame, just the average every few seconds. Second, I would only capture the time once, not multiple times. Use that captured time for everything that needs a time base.

I would do something like this:

```
public void onDrawFrame(GL10 gl) {
    timeThisRound = System.nanoTime()/1000000.0f;  // only capture the time once in seconds
    deltaTimeThisRound = timeThisRound-timeLastRound;  // to use for certain calculations
    fpm++;
    if(timeThisRound > lastMin + 5.0f)
    {
        lastMin=timeThisRound;
        Log.v("NewTag","fps: " + fpm/5.0f));
        fpm=0;
    }
    timeLastRound = timeThisRound;
}

```

You can change the 5.0f in both places to be whatever amount of time you want to check. Just make sure you change it in both places.

If you want to print out the average time per frame instead just swap the formula to be `5.0f/fpm`. fps is frames/time. time for one frame is time/frames.
> 1 votes

# Answer
Video frame flip times are very consistent. However, this is no guarantee that onDrawFrame is being called precisely the instant after a video flip. As you've measured, it is not particularly timely. If the system is not heavily strained, you can get an accurate measurement of the frame rate by averaging the values above. If the system is heavily strained, however you will start getting dropped frames in which the computer does not have enough time to fill the image buffer before the flip. In this case, you will start seeing multiples of 16.67 (plus random error) in your measurements. Even though the hardware frame rate is 60 Hz, there will be less than 60 frames displayed each second.
> 1 votes

---
Tags: opengl-es2, timing, vsync, profiling
---