# Question
Title: Why does clip space in OpenGL have 4 dimensions?
I will use this as a generic reference, but the more i browser online docs and books, the less i understand about this.

```
const float vertexPositions[] = {
    0.75f, 0.75f, 0.0f, 1.0f,
    0.75f, -0.75f, 0.0f, 1.0f,
    -0.75f, -0.75f, 0.0f, 1.0f,
};

```

in this online book there is an example about how to draw the first and classic hello world for OpenGL about making a triangle.

The vertex structure for the triangle is declared as stated in the code above.

The book, as all the other sources about this, stress the point that the Clip Space is a 4D structure that is used to basically decide what will be rasterized and rendered to the screen.

Here I have my questions:

* i can't imagine something in 4D, i don't think that a human can do that, what is a 4D for this Clip space ?
* the most human-readable doc that i have read speaks about a camera, which is just an abstraction over the clipping concept, and i get that, the problem is, why not using the concept of a camera in the first place which is a more familiar 3D structure? The only problem with the concept of a camera is that you need to define the prospective in other way and so you basically have to add another statement about what *kind* of camera you wish to have.
* How i'm supposed to read this `0.75f, 0.75f, 0.0f, 1.0f` ? All i get is that they are all float values and i get the meaning of the first 3 values, what does it mean the last one?

# Answer
The magic term is "Homogeneous coordinates" which are used in systems where perspecive is a factor. Check the wiki for an overview, but it's a long course of study to really understand it (which I don't).
> 11 votes

# Answer
Read the introduction of books you read, you'll be surprised ;)

http://arcsynthesis.org/gltut/Basics/Intro%20Graphics%20and%20Rendering.html under Rasterization Overview

EDIT: the website is down for some time now but the page I refer to is still on the web archive: https://web.archive.org/web/20130901150530/http://www.arcsynthesis.org/gltut/Basics/Intro%20Graphics%20and%20Rendering.html

The "w" value (where the first 3 values are x, y and z) basically says what the dimensions of the clip space are. Because this is 1 scalar value, all 3 dimensions of the clip space are equal (and that's why the clip space is a cube). Every vertex has it's own clip space in which it exists (and basically needs to "fit" in, otherwise it CLIPS :D), there is not 1 "world" that is the clip space(though all clip spaces are in the same "world" I think, even I'm having trouble with this ;P).

So if your vertex has for example the coordinate \[1,1,1\], if the clip space is 1 then the vertex is in the top right near corner of the screen (when all is default, I don't know if the directions can be altered). But if the vertex has a clip space of 2, then the coordinate \[1,1,1\] will be somewhere let's say, 3 quarters across the screen to the right, 3 quarters across the screen to the top, and the third dimension you can guess yourself.

I think having let's say a clip space of 5 would mean the locations within that clip space range from -5 to 5 on every dimension, instead of the cube being 5x5x5. But that's probably because simply put: all x y and z coordinates are divided by the clip space dimension, so basically your vertices undergo this:

x = x / w

y = y / w

z = z / w

And that's what makes it all possible. I think the reason this exists is for easy comparisons. If the coordinates have been divided by the clip space dimension, then the coordinate that has 1 or more components with a value higher than 1, exists outside the clip space. So if your clip space is let's say 1024, but the coordinate is \[2000,3,-100\] then the x(2000) component is outside the clip space (which only ranges from -1024 to 1024).

computingwise it's easy to tell if something is inside the clipspace if all you have to do is (very crudely put ofc): (x/w)\<1 && (x/w)\>-1 then render. Also, I suppose having all clip spaces of all vertices the same size (so every clip space cube ranging from -1 to 1 in every dimension) makes it easier for whatever comes after the normalisation process, seeing as from that moment on all coordinates are floats ranging from 0 to 1 (disregarding that which has been clipped off).
> 12 votes

# Answer
TL;DR it's not 4D space, it's 3D plus a scaling number which is virtually always 1. If it is 1, you can ignore it and the first three numbers are x,y,z. If not it gets more complicated.

Here's a simple explanation. Vertices in 3D *should* only have three components

`⌈x⌉
v = |y|
 ⌊z⌋`

If we want to manipulate them (e.g. rotation, scaling etc.) we use a matrix. The most common example of course is the Model-View-Projection (MVP) matrix which transforms world coordinates into clip space. Like this:

`⌈m11 m12 m13⌉ ⌈x⌉
c = |m21 m22 m23| * |y|
 ⌊m31 m32 m33⌋ ⌊z⌋`

However this has a big flaw: you can't do translation. If `[x,y,z]` is zero, no matter what `m` is the result will always be zero, so we can't have an MVP which includes translation. Obviously we'd like that. The solution is to add a 1 to the end of our vectors and expand the matrix to 4x4:

`⌈cx⌉ ⌈m11 m12 m13 tx⌉ ⌈x⌉
|cy| = |m21 m22 m23 ty| * |y|
|cz| |m31 m32 m33 tz| |z|
⌊ 1⌋ ⌊ 0 0 0 1⌋ ⌊1⌋`

(If you look at any orthogonal MVP matrix - e.g. from `glOrtho()` \- you'll find the 4th row is `0 0 0 1`. Sometimes it is even left implicit.) If you work through the maths you will see that that is the same as

`⌈cx⌉ ⌈m11 m12 m13⌉ ⌈x⌉ ⌈tx⌉
|cy| = |m21 m22 m23| * |y| + |ty|
⌊cz⌋ ⌊m31 m32 m33⌋ ⌊z⌋ ⌊tz⌋`

The 4th component is called `w`, and while it doesn't *have* to be 1, it nearly always is (*before* a transformation anyway; afterwards it is usually re-homogenised by dividing the the whole vector by `w` so it is 1 again). It's kind of a hack to allow transformation matrices to include translation.

**Edit**

I believe the original motivation was for perspective projections, which are impossible with 3D coordinates. There are other transformations you can only do with 4D vectors, but translation is the easiest to understand.
> 11 votes

# Answer
There is also one more reason that I see and that was not mentioned in the previous answers.

Translation matrices are 4x4 so that you can also translate the object around "the world". Because with a 3x3 matrix you can rotate and scale a 3d coordinate, but you can translate a 3d coordinate only with a 4x4 matrix, from here the need to express the 3d coordinates in a 4d vector.
> 1 votes

---
Tags: opengl, camera, clipping
---


# Question
Title: Custom arcade physics rate (e.g. bullet time)?
Is there a way to modify the rate that physics is applied, either globally or on a per-sprite basis in Phaser? That is, how can I slow down or speed up the rate at which sprites move around, or fall due to gravity? One use case would be for the "bullet time" effect - by slowing down the physics rate for everything else apart from the player character.

I understand that the way physics works is that deltas are applied to sprite bodies every frame, based on the `game.time.elapsed` value. One method would be to set a custom multiplier on this elapsed value so movements happen slower or faster, but is this possible?

Alternately, I could apply all the physics effects myself, but can I do this without losing compatibility with the rest of the physics system?

# Answer
> 1 votes
Slowing down time globally is possible, via the `game.time.slowMotion` variable. It defaults to 1.0, setting it to 2.0 makes things half speed for example.

There's a demo on the Phaser examples page under Time \> Slow Down Time. It appears that when slowed down, the number of updates slows down (i.e. movement becomes less frequent and jerky) as opposed to things moving as frequently but in smaller increments, which may or may not be what you want. The example doesn't show what happens when setting this number \< 1.0.

From what I can find in the docs, there's no way to set this on a per-sprite basis.

---
Tags: physics, phaser
---


# Question
Title: Difference between Spherical Harmonics and Spherical Harmonics Lighting
What is the difference between Spherical Harmonics and Spherical Harmonics Lighting in OpenGL?

# Answer
Spherical harmonics lighting use spherical harmonics to approximate a lighting lobe on an object.

It has property that make it cheap to compute in real time (dot product vs the normal) and to store (7floats per channels generally, for example in unity engine, but it vary based on the use, The movie avatar used spherical harmonics with 81floats per channel). However it's low frequency and don't handle specular well, so it is use mostly for diffuse representation (incoming radiance). It's a cheap and compressed representation for lights.

There is several uses:

**1. To compute a lot of diffuse lights at a single object.**

Because each light need a pass, it's cheaper to accumulate lights in a single spherical harmonic representation and apply it to objects. However this does not handle specular lighting, so you need passes for at each principal lights.

**2. To store baked global illumination.**

Spherical Harmonics can be blended linearly to quadrilinearly in a volume. It allow to store light in point of space then interpolate to find the light at objects position.

**3. To store lightmap**

Being able to be interpolate linearly makes spherical harmonics good candidate for lightmap intensity as you can store second order spherical harmonics (4 floats) in a regular rgba texture (could be stored at vertex value too). It works like above and allow to modify or move normal of a surface, or tesselate it, and retain the correct baked global illumination. Basically it allow to add correctly lit high frequencies for cheap.

**4. More**

It can be use to store better AO map, secondary bounce for radiosity, thickness map, smooth shadow casting (the last of us), time of day etc ...

Spherical harmonics is well documented at that point but all are very math heavy, I understand the overall idea, but I can't manipulate it because it's written in an opaque manner and the community was VERY unhelpful so far, pointing at document without clarifications. It mean that the entry level stays high unlike other aspect of learning shader (like physically based rendering).

So if you can find a competent mentor, cherish him!

http://www.research.scea.com/gdc2003/spherical-harmonic-lighting.pdf http://nccastaff.bournemouth.ac.uk/jmacey/MastersProjects/MSc11/Ravi/msc\_thesis\_ravi\_acharya.pdf http://sebh-blog.blogspot.com/2010/04/spherical-harmonics-lighting.html https://dickyjim.wordpress.com/2013/09/04/spherical-harmonics-for-beginners/ http://ppsloan.org/publications/StupidSH36.pdf http://www.gamasutra.com/view/news/173409/Indepth\_Photon\_mapping\_and\_baking\_light\_maps.php http://sebastien.hillaire.free.fr/index.php?option=com\_content&view=article&id=60&Itemid=71
> 4 votes

# Answer
Spherical harmonics is a general mathematical concept that can be applied to a number of problems. One of those problems is modeling the behavior of light for use in 3D rendering. There's not really a difference, just a scoping of the application. It's sort of like asking *"What's the difference between Fourier Analysis and Fourier Analysis of Sound Signals?"*
> 1 votes

---
Tags: opengl
---


# Question
Title: Should I switch to UDP for a mobile p2p game when considering 3G network?
I have been making a mobile game that is similar to "Street Fighter" where two players play with each other via Internet.

The game sends out a small packet (controller status) to the other party every 30ms (a lot of packets going on).

I am currently using a server to connect two players and all communications are via TCP through the server. The server load increases a lot even for just 30 concurrent players. I know it sounds not wise to let the communication go through the server, so I think the best design should let these two players to communicate directly via UDP after the server hooks them up.

However, I have some questions when trying to move on to the new design:

Since it's a mobile game, players might be using 3G network a lot. Does UDP hole punching work well in 3G network? Does it matter when a player is actually moving physically (such as inside a car)? Do you think I should change the design or any recommendation of better design concepts?

# Answer
> 4 votes
3G is optimized for stuff like streaming video. It's terrible with regard to latency when talking about small bits of data. There's a reason multiplayer mobile games over 3G with split-second timing don't exist.

---
Tags: networking, client-server, mobile, udp, peer-to-peer
---


title: Generating 3D-like effect

text:
# Question
Title: Generating 3D-like effect
I'm making a 2D sidescroller game and want to give the blocks a 3D like effect. This way it looks like the player is walking on 3D blocks while walking on a 2D plane (thus having only x,y coordinates).

I have already written the code to generate the terrain in 2D, but the 3D effect is now baked in. It looks like this:

At this moment the 3D effect is baked into the blocks, but I want to try to generate it.

Is there a common way to achieve this 3D like effect while still staying 2D? Do I have to convert from 2D to 3D or is it also possible to do this with calculations/shaders?

EDIT; The reason I want the top texture of the block separate of the block is because when the camera would go up, the top should get bigger as the camera sees more of the top of the block and the other way around when the camera goes down.

# Answer
> 5 votes
Sarting with the clouds, a simple method is to draw them as three layers:

**Layer 1** is the bottom layer, and is drawn first. It just contains the cyan background.

**Layer 2** is the middle layer, drawn between the other two, and it represents the 3D highlights. The background in this layer would again be transparent (represented by a purple colour in the following image) to let the cyan background show through. The clouds would be drawn slightly brighter than the normal cloud colour, and should drawn offset upwards vertically from the normal position of the clouds.

**Layer 3** is the top layer, drawn last. It contians the clouds drawn normally, but with a transparent background (the transparent background is represented by a purple colour in the following image).

The idea is that clouds on Layer 3 will obscure most of the clouds on Layer 2, leaving just the highlights visible. The cyan background will show through the transparent bit, too.

**Result**

When these layers are composted, you get the following:

**Movement**

When the camera goes up or down, you would simply adjust the offset of the highlight layer:

A similar method could be applied to other objects.

# Answer
> 3 votes
You could achieve this effect using parallax scrolling by making the earth and each shade of green a separate layer. With a parallax effect, no 3D calculations are required, and you get to stay with the pixelated, simple color style you're using.

Note that parallax doesn't have to be limited to just horizontal motion. Vertical movement (when the camera goes up and down) can also be handled by shifting layers up and down relative to each other.

Though it is not exactly in the style of what you are doing, take a look at http://www.nevermindthebullets.com/strip.html#1-1 for an interesting example of using parallax in both X and Y for some interesting visuals.

# Answer
> 0 votes
You can add a depth component to your 2D textures and set the depth value in the pixel shader.

There will be some performance loss due to setting the depth in the pixel shader but shouldn't matter for a 2D game on PC.

The other way is to use multiple layers of 2D textures for your background.

---
Tags: opengl, java, 2d, libgdx, shaders
---


# Question
Title: How to position a Weapons model in a first person shooter with XNA
I am building a first person shooter and positioning the weapons is hard. I am trying to get the bat to look like you are holding it but I keep trying things and they don't appear in the positions I want them to be in. Here is what I did with one version of the function.

```
void DrawModelModel(Model model, Matrix world)
    {
        Vector3 modelPosition = Vector3.Zero;
        float modelRotation = 0.0f;
        Viewport viewport = graphics.GraphicsDevice.Viewport;
        float aspectRatio = (float)viewport.Width / (float)viewport.Height;
        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 200.0f);
        // Copy any parent transforms.
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        // Draw the model. A model can have multiple meshes, so loop.
        foreach (ModelMesh mesh in model.Meshes)
        {
            // This is where the mesh orientation is set, as well
            // as our camera and projection.
            foreach (BasicEffect effect in mesh.Effects)
            {

                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                    * Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f);
                effect.View =  Matrix.CreateLookAt(cameraPosition,
                    Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(35.0f), aspectRatio,
                    1.0f, 10000.0f) ;
            }
            // Draw the mesh, using the effects set above.
            mesh.Draw();
        }
    }

```

Here is what I did with a different version of the function.

```
void DrawModelModel(Model model, Matrix world)
    {
        Vector3 modelPosition = Vector3.Zero;
        float modelRotation = 0.0f;
        Viewport viewport = graphics.GraphicsDevice.Viewport;
        float aspectRatio = (float)viewport.Width / (float)viewport.Height;
        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 200.0f);
        // Copy any parent transforms.
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        // Draw the model. A model can have multiple meshes, so loop.
        foreach (ModelMesh mesh in model.Meshes)
        {
            // This is where the mesh orientation is set, as well
            // as our camera and projection.
            foreach (BasicEffect effect in mesh.Effects)
            {

                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                    * Matrix.CreateFromYawPitchRoll(0.0f, 1.0f, 1.0f);
                effect.View =  Matrix.CreateLookAt(cameraPosition,
                    Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveOffCenter(-2.0f,1.0f, 0.0f, 1.0f, 1.0f, 10000.0f) ;
            }
            // Draw the mesh, using the effects set above.
            mesh.Draw();
        }
    }

```

What matrix can I use to get the bat model to appear realistically as if you are really holding it in a first person view. I am new to matrices so my knowledge of them is basic. What matrix should I use or what parameters with my current matrix should I be editing? I am thinking the projection matrix is what I need to be editing, but I am very confused at this point. Any help would be great.

# Answer
> 0 votes
You're already using bone transforms. I suggest you read up on bone animation in blender. You can create a chain of bones that represent arms, holding the bat, and animating that in blender. Then just export the model, including the animations, and you can use the bone animation you made yourself.

Download blender and follow this tutorial: http://wiki.blender.org/index.php/Doc:2.6/Tutorials/Your\_First\_Animation/2.Animation

---
Tags: xna, matrix, models, projection-matrix
---


# Question
Title: Application components dependancy and decoupling
In my client application I have two major components:

1. GameCore - wrapper that handles everything about running the actual game
2. NetworkClient - A layer that takes care of communicating(receiving/sending packets) with the server.

What I am not sure about is the way the NetworkClient should server information to the GameCore process of the game. The core process has an event queue that is executed in update() calls. My initial idea is to have something like this:

NetworkClient receives a snapshot of the state changes, takes that snapshot and chops it down to event objects for the GameCore process to handle.

The problem I see with that, isn't the NetworkClient class too dependent on the Core class. The oposite is not an issue however because, there can be a different client(udp,tcp etc) that works with the Core class.

So from a design point of view, is there a reason I might not want the NetworkClient class to be written for the specific implementation of the Core class.

PS: I am using JavaScript, but the question does not necessary concern the implementation technology.

# Answer
> 1 votes
This is hugely dependent on the type of the game you're creating. For say Chess, the only thing `NetworkClient` would do is reacting on the move being made and sending that. Some other games might send parts of their state or even the whole state.

In general, you might think about splitting the networking part into two smaller components: the transport that is able to communicate and handles the actual connection, and something like "Network-View" or "Synchronization-View", that's able to take subset of the main game state and send it periodically, react to events and send updates based on those, or both.

That way you separate actual game processing logic from logic used to take the process results and converting them into wire-compatible form. Similarly, on the other side the same part is able to understand the messages and merge them with the present game state.

---
Tags: architecture, javascript, design-patterns, client-server
---


# Question
Title: Accessing Canvas and Button components in a scene
I have a scene with the following hierarchy:

This is game scene and the game manager is a singleton with the following variable fields:

```
// canvas
public Canvas PauseCanvas;
public Canvas MainMenuCanvas;

```

Before implementing singleton, I assigned them from the inspector. Now that the game manager is singleton, I need to assign them through script on level load. I can see one solution to this situation:

* Getting all canvas components through `GetComponents<Canvas>()` and then iterating and checking their `name` fields to assign them accordingly or maybe using LINQ.

**What I want to ask is**: Is there a name-based search method just like finding game objects with name `GameObject.Find("Name")` that is applicable for Components?

# Answer
There is no such method but you can use this to find your elements : `yourCanvas = GameObject.Find("CanvasName").GetComponent<Canvas>();`
> 2 votes

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


title: How to rotate model 180º with XNA

text:
# Question
Title: How to rotate model 180º with XNA
I got a model, and a camera pointing at this model, I think my camera position is the problem. Its showing the front of the model, but I want it to show its back like in third person. My camera code is:

```
Vector3 thirdPersonReference = new Vector3(0, 100, -100);
public Camera(Vector3 landscapePosition, Player _player)
    {
        this.player = _player;
        rotationMatrix = Matrix.CreateRotationY(this.player.Rotation);
        Vector3 transformedReference = Vector3.Transform(thirdPersonReference, rotationMatrix);
        this.position = transformedReference + this.player.Position;
        viewMatrix = Matrix.CreateLookAt(this.position, this.player.Position, new Vector3(0.0f, 1.0f, 0.0f));
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.player.AspectRatio,
            1.0f, 1000.0f);
        terrainMatrix = Matrix.CreateTranslation(landscapePosition);
    }

```

What is that Im doing wrong???

# Answer
If I understand right what you are trying to move the camera backwards and upwards relative to the player model. However, in the Z-axis direction XNA ago, that is, you need to set Z coord 100 instead of -100. Or you can do like that:

```
Vector3 thirdPersonReference = Vectro3.Up * 100 + Vector3.Backward * 100;

```

Vector3.Backward has value (0, 0, 1), abd accordingly Vector3.Forward has value (0, 0, -1).

Please, see link and pay special attention to Remarks section.
> 1 votes

---
Tags: xna, c#, 3d
---


# Question
Title: How to reposition a bouncing ball after it has passed through a surface
I have a bouncing ball which can collide with lines of a random slope. The ball passes through the lines a bit and I need to set the ball back some distance from the line.

The ball (defined by position and radius) travels according to a speed vector (obtained by multiplying a direction vector by a magnitude) and I want to find the distance between the center and the line so I know how many pixels the ball passed through the line.

In the example the ball passed 10 pixels (radius - dist) after the line, I need to move the center of the ball 10 pixels in the opposite direction.

How can I those pixels between x and y so I can subtract them from the center coordinates?

Thanks

# Answer
What you need is the vector of the shortest distance between the Wall and the balls center. More generally, you seek the distance between a point and a line.

Paul Bourke has given a general solution to this well known geometry Problem on his website:

> This note describes the technique and gives the solution to finding the shortest distance from a point to a line or line segment. The equation of a line defined through two points P1 (x1,y1) and P2 (x2,y2) is P = P1 + u (P2 - P1)
>
> The point P3 (x3,y3) is closest to the line at the tangent to the line which passes through P3, that is, the dot product of the tangent and line is 0, thus (P3 - P) dot (P2 - P1) = 0
>
> Substituting the equation of the line gives
>
> \[P3 - P1 - u(P2 - P1)\] dot (P2 - P1) = 0
>
> Solving this gives the value of u
>
> Substituting this into the equation of the line gives the point of intersection (x,y) of the tangent as
>
> x = x1 + u (x2 - x1)
>
> y = y1 + u (y2 - y1)
>
> The distance therefore between the point P3 and the line is the distance between (x,y) above and P3.
>
> **Notes**
>
> * The only special testing for a software implementation is to ensure that P1 and P2 are not coincident (denominator in the equation for u is 0)
> * If the distance of the point to a line segment is required then it is only necessary to test that u lies between 0 and 1.
> * The solution is similar in higher dimensions.

With the distance now calculated as (x,y) and the center of your ball as (cx,cy),

new\_cx = cx - (radius-x)

and

new\_cyy = cy - (radius -y);

On a side node, very fast moving balls might not intersect with the wall if they move more than the balls diameter per frame, since they might then "skip" through the wall, being in front of it in one fraem and completely behind behind it in the next.
> 0 votes

---
Tags: 2d, collision-detection, mathematics, physics
---


title: How to make a game from the ground up

text:
# Question
Title: How to make a game from the ground up
I've been using unity to make 2d indie type games for a while now. However, i've tried to branch into different genres and unity cant do some of the things that i want it to do(*although it is still very good*).

I really want to make a game from scratch were i have complete control over what happens, although i wouldn't have the slightest clue were to start.

tldr what resources do you need to build a game from the ground floor. *or more or less. what resources/software/libraries did most well made indies such as super meat boy, braid or limbo use.*

# Answer
A great place to start is from this book, but I'll go over the basics. This list is built on the basis that C++ is the language you would be using and you're developing a desktop game.

1. Games rely on maths, so you need a good maths library. A good place to look is at glm.
2. You also need some way of displaying an output to a screen. You need a some way to get a window open and handle input (glfw, SDL) and some way to access the graphics card(opengl \+ tuts) to render.
3. Assets such as texture (FreeImage), models & animations(AssImp, roll your own), shaders(roll your own) and sound(ffmpeg) need to be handled.
4. Most games have some form of collision and physics so you need something for this (bullet, box2D).
5. Sound playback needs to be handle as well (OpenAL, FMOD).

This list is by no means exhaustive but this list and book should give you a pretty good start.

As for "*what resources/software/libraries did most well made indies such as super meat boy, braid or limbo use.*", I have no idea.
> 0 votes

# Answer
I would recommend using HaxeFlixel for the programming part. You have a control over almost anything in the game because it relies on it's programming(but you need to know programming in Haxe (Although it's not very difficult)). You can build an entire system from that, if that's what you're searching for.
> -2 votes

---
Tags: game-design
---


title: Compress 16 bit raw data in webgl

text:
# Question
Title: Compress 16 bit raw data in webgl
I have a 3D volume where every voxel is 16 bits. Is there anyway I can use some kind of compression to store the data so I can use less video ram? Webgl supported different compressiosn if you enable them with extension, but can I use them for a one channel data?

Like `WEBGL_compressed_texture_s3tc` only supports rgb and rgba data:

```
COMPRESSED_RGB_S3TC_DXT1_EXT
COMPRESSED_RGBA_S3TC_DXT1_EXT
COMPRESSED_RGBA_S3TC_DXT3_EXT
COMPRESSED_RGBA_S3TC_DXT5_EXT

```

If its not possible in webgl, is it supported in OpenGL to compress a 16 bit values with one channel?

# Answer
> 1 votes
In short: no.

S3TC and other compression formats will destroy your 16bit values.

Texture compression formats have a fixed compressed size and therefore need to be lossy in order to ensure this.

If you need 16bits of lossless data you must use a non-compressed format. Ideally `GL_R16UI`.

---
Tags: opengl, webgl, compression
---


# Question
Title: How can I load another form containing a new level when my player reaches the current level's exit?
I am coding a very basic side-scrolling game in C#, using Windows Forms.

I want to connect my game's levels with 'exit points'. When the player touches an exit point, a new form should be loaded immediately. How can I do this?

# Answer
Yes, it's feasible: if the player hits the trigger area, create the new form and position it appropriately and then close the old form (the order is relatively important here, because the default Windows Forms application driver, the `Run` call, will terminate the application when the last form is closed so you always want to make sure at least one exists, or you want to change that `Run` call).

For example, assuming you call a method of the current form called `OnPlayerHitExit` when the player hits the exit area, you could:

```
void OnPlayerHitExit () {
  var nextLevel = new FormContainingNextLevel();
  nextLevel.Show();
  Close();
}

```

---

That said, you shouldn't put each level in its own form. A form is a Win32 window, and closing one/opening a new one will be visible and noticeable to the player even if you spend time doing all the necessary hackery to get as close as possible to a seemless transition.

Instead, store your level data independently of the form itself (maybe in a `Level` class) and when the player hits the trigger area, replacing the existing level data with new level data.
> 1 votes

---
Tags: c#, windows-forms
---


# Question
Title: How can I support multiple player inputs in Pygame?
I'm trying to develop a team-based Asteroids game. It's going well except for the "multiple user inputs to a single machine" part. Can anyone recommend a method for getting and updating 6 players using a single computer? Is it even possible? At the moment I'm working with a couple of old XBox controllers and a keyboard and it's almost working...

Is it possible to add additional keyboards? And would you arrange the code into one big get events function or is there a better way to check for user inputs at this scale?

# Answer
> 1 votes
I'm pretty sure you'll find it impossible to support multiple keyboards. This thread about multiple keyboards support for SDL indicated it was impossible, and pygame is at heart a python wrapper for SDL. Furthermore I believe it uses SDL 1.x not SDL 2.x, so it hasn't been actively developed for a long time. I'm not aware of any limits to the number of joysticks or game pads though, and a single usb bus can support theoretically 127 devices though you're likely to hit problems with power or bandwidth before that.

Regarding code architecture for handling many inputs gracefully, its hard to give advice to a problem that generalized. I think you'll find basic programming best practices helpful. You can use one big event loop as long as you 'Don't Repeat Yourself' in your implementation. You're welcome to read or use my solution.

---
Tags: input, pygame
---


# Question
Title: Unity question on OnTriggerStay() function
I'm currently working on a soccer game.I have a script for the ball that whenever the ball collides as trigger with the goal line,the ball will return to the middle point.But seems like the ball doesn't `Lerp()` back,afterward I tried to check if Unity counts it as collide or not with `Debug.Log("Goal");` but nothing is logged to the console.Please help me with that.Here is the first code:

```
public var smooth : float;

private var newPosition : Vector3;

function Awake ()
{
    newPosition = transform.position;
}

function OnTriggerStay (ball : Collider)
{
    var positionA : Vector3 = new Vector3(0, 0.3, 0);

    newPosition = positionA;

    transform.position = Vector3.Lerp(transform.position, newPosition, smooth * Time.deltaTime);
}

```

Here is the second code (after changing to `Debug.Log()`):

```
function OnTriggerStay (ball : Collider)
{
    Debug.Log("Goal");
}

```

# Answer
> 0 votes
In addition to having a ridgidbody (one must be present for OnTriggerStay to be called at all), you may also want to try different 'collision detection mode' types on that rigidbody. If the ball is moving too fast the default 'discrete' might not be accurate enough to see the ball whizzing by, and if the ball is going too fast then the 'Continues Dynamic' collision detection mode type might be the best option. For more information on the different types of detection modes please see: Rididbody Collision Detection Mode in the Unity Documentation

# Answer
> 0 votes
You need a rigidbody connected to at least one of the objects with a collider (as @Savlon mentioned), but the other issue with gravity can be alleviated by toggling the rigidbody's Kinematic attribute.

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


# Question
Title: How to make unitypackage from allseen alliance's android sdk?
Im making an offline multiplayer for Android device by Unity and I found only one way to do this is the allseenalliance sdk. After download its from here I found that to use it I need to create an .unitypackage file but I cant understand the tutorial they give

```
> Open a CMD window.
>     Add the path to Unity.exe (the Unity IDE) to your PATH, if it is not there already.
>         For example, set PATH=%PATH%;C:\Program Files\Unity\Editor
>     CD to each "unity" folder in the SDK, and run the following command in each location:
>         Unity.exe -batchmode -nographics -quit -projectPath %CD% -exportPackage Assets AllJoyn.unitypackage
>     This command creates the AllJoyn.unitypackage file.

```

Please give me a noob tutorial for this or the package file, thanks.

p/s:Is there another way to connect mobile device without internet in unity3d?

# Answer
> 0 votes
Based solely on the instructions and my reading comprehension, the following is a more easy to follow guide on how to accomplish those tasks.

---

1. Open the command prompt.
> This can be done many different ways based on your version of windows. The easiest way would be by clicking: "Windows Key + R", then typing "cmd.exe", then clicking "OK".

---

2. Run (type in the command prompt and hit enter) the command: **set PATH=%PATH%;C:\Program Files\Unity\Editor**
> This command appends the location of the Unity Editor folder to your path variable. Anything located in the PATH variable is checked when running a program, so adding the path allows you to run the Unity.exe program from anywhere, this is useful in Step 7.

---

3. Know where the SDK is located on your computer.
> You can cheat and look using the GUI if you would like.

---

4. Run the command: **CD "*location to SDK*"**
> Instead of putting "location to SDK", replace that with the path to the SDK found in Step 3. If there are any spaces in this path, then include quotation marks around the entire path. This command tells the command prompt what directory to use when looking for programs by their name.

---

5. Run the command: **DIR**
> DIR allows you to see all of the files and folders in the Current Directory (set in step 4). OR you can cheat and look using the GUI. Find a unity folder that you have not already done this process to.

---

6. Run the command: **CD "*name of unity folder*"**
> This sets your current directory to the unity folder located inside of the sdk. Change 'name of unity folder' to the actual name of the folder in this directory.

---

7. Run the command: **Unity.exe -batchmode -nographics -quit -projectPath %CD% -exportPackage Assets AllJoyn.unitypackage**

---

8. Run the command: **CD..**
> This command changes the current directory to the parent of the current directory.

---

9. Repeat steps 5 - 8 until all of the unity folders in the sdk have been completed.

---

p/s: If you have the android pro license with unity, you can use sockets to have two clients talk with each other over the lan. If you don't have a pro license, it sounds like a pain because .NET sockets are off the table... but even if that is the case, it sounds like this might help in making your own solution: Mobile Socket Support with Unity3D

---
Tags: unity, android, multiplayer
---


# Question
Title: How to make a model parts glow one after the another
I have a brain model. I want to glow the parts of the brain model one after the another after a period of time. I have done to glow the parts, but when the second part glows, the color of the first part still remains.

```
public GameObject pons;
public GameObject frontallobe1;

void Update () {
    Invoke("PonsGlow",2);
    Invoke("frontalLobe1Glow",4);
}
void PonsGlow()
{
    pons.renderer.material.color=Color.red;
}
void frontalLobe1Glow()
{
    frontallobe1.renderer.material.color=Color.red;
}

```

# Answer
> 1 votes
```
public GameObject pons;
public GameObject frontallobe1;

void Start() {//runs when this gameobject is first added to the game and only runs once.
    StartCoroutine("Glow", 2f, pons);
    StartCoroutine("Glow", 4f, frontallobe1);
}

//store the last glowing object and color,
//so it can stop glowing.
private GameObject lastGlow;
private Color preGlowColor;

IEnumerator Glow(float waitTime, GameObject go){
    yield return new WaitForSeconds(waitTime);

    if(lastGlow!=null){//if first time running, ignore this
        lastGlow.renderer.material.color=preGlowColor;//set the color back to its original color
    }
    preGlowColor = go.renderer.material.color;//save the original color
    lastGlow = go;//save the now glowing game object, replacing any prior ones
    go.renderer.material.color=Color.red;//make gameobject glow - you might even want to make a fancy Color.Lerp here
}

```

There are many ways to skin this cat. The above way works by 'saving' the last glowing thing (and it's color, if that's important) so that when something new glows, it 'cancels' the old glow by replacing the last object 'glow color' with its original color. But this way will only work if only one thing is glowing at a time (if you want to have two things glowing, the first one will be canceled by the second one).

If the requirement is that 'any number of things can start glowing at the same time', then you will need to make an array (a big list of stuff) of all the things that are currently glowing (and possibly their original colors as well), so that when something new starts to glow that all the old stuff (everything in the list of 'currently glowing' stuff) gets turned off properly.

Also adding a color lerp in there would make it look pretty, instead of just 'popping' on and off.

And lastly, if you didn't notice, I changed the invoke to a start coroutine because I think it made it look a little prettier (or more readable to me). Also I changed the Update function to Start: this means that it is only ran once, rather than once per rendered frame (if it was still in update, it would flicker between the two pieces over and over again, after about 4 seconds).

Hope that helps!

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


# Question
Title: Why my dynamically generated Sprites overlap?
I'm trying to dynamically generate scene representing chess board made from sprites. I'm using two textures for these:
\- pieces.png (taken from here: http://opengameart.org/sites/default/files/chess\_2.png)
\- tiles.png (drawn by hand, consists of two 128x128 squares filled with different colors)

The best result I achieved so far is a board with overlapping tiles:

The sprite mode for these textures is "Single" and pixels per unit are set to "128" (unsure whether I should've done this or not)

The textures are being sliced to sprites in my MonoBehavior.Start:

```
            var tiles = new Dictionary<int, Tile> ();
            var sprites = new Dictionary<int, Sprite> ();

            // Load all tilesets
            foreach (var externalTileset in map.tilesets) {
                    var tilesetAsset = (TextAsset)Resources.Load ("Boards/" + externalTileset.source);
                    var tileset = (Tileset)tilesetSerializer.Deserialize (new StringReader (tilesetAsset.text));

                    Texture2D texture = (Texture2D)Resources.Load ("Boards/" + tileset.image.source.Replace (".png", ""), typeof(Texture2D));
                    Debug.Log ("Texture for " + tileset.image.source + " loaded: " + texture.width + 'x' + texture.height);

                    int tilesPerRow = tileset.image.width / tileset.tilewidth;
                    int totalTiles = (tileset.image.width / tileset.tilewidth) * (tileset.image.height / tileset.tileheight);
                    for (int tileId = 0; tileId < totalTiles; tileId++) {
                            float x = tileset.tilewidth * (tileId % tilesPerRow);
                            float y = (tileId / tilesPerRow + 1) * tileset.tileheight;
                            sprites [externalTileset.firstgid + tileId] = Sprite.Create (texture, new Rect (x, texture.height - y, tileset.tilewidth, tileset.tileheight), new Vector2 (0.5f, 0.5f));
                    }

                    if (tileset.tiles != null) {
                            foreach (var tile in tileset.tiles) {
                                    tiles.Add (externalTileset.firstgid + tile.id, tile);
                            }
                    }
            }

```

And when sprites are added to newly created game objects:

```
        float minX = -4;
        float maxX = 4;
        float minY = -4;
        float maxY = 4;

        for (int i = 0; i < map.height; i++) {
                float y = minY + i * (maxY - minY) / map.height;
                for (int j = 0; j < map.width; j++) {
                        float x = minX + j * (maxX - minX) / map.height;
                        if (pieces [i, j] != null) {
                                GameObject piece = new GameObject (pieces [i, j].properties ["Color"] + ' ' + pieces [i, j].properties ["Type"]);
                                SpriteRenderer renderer = piece.AddComponent<SpriteRenderer> ();
                                renderer.sprite = piecesSprites [i, j];
                                piece.transform.position = new Vector2 (x, y);

                        }
                        if (tileSprites [i, j] != null) {
                                GameObject tile = new GameObject ("Tile");
                                SpriteRenderer renderer = tile.AddComponent<SpriteRenderer> ();
                                renderer.sprite = tileSprites [i, j];
                                tile.transform.position = new Vector2 (x, y);
                        }
                }
        }

```

I believe I can hack something to make this work, but I want to know how to do it properly What's wrong with my code or scene/resources setup?

# Answer
Solved! http://docs.unity3d.com/ScriptReference/Sprite.Create.html I should've used proper Sprite factory method and passed pixel to units:

```
Sprite.Create (texture, new Rect (x, texture.height - y, tileset.tilewidth, tileset.tileheight), new Vector2 (0.5f, 0.5f), 128)

```
> 1 votes

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


title: How to make natural looking voxel

text:
# Question
Title: How to make natural looking voxel
I'm developing a voxel game, but I think I use the wrong technique. I currently use flat tiles, to make blocks, and I think theres a better and more efficient way.

I have seen a voxel game, which have naturally looking terrain. By that I mean non blocky. The game have 4\*4\*4 blocks per cubic meter, and blocks like dirt, sand and stone, have round edges, and kind of melt together (Like in ordinary games). Heres a screenshot

How is this achieved?

# Answer
> 14 votes
This is achieved by interpolating ramps between cubes of different height.

When you have a scenery like this (seen from the side)

```
  #
 ####   ##
############

```

you would add polygons to make it look like this:

```
 /#\
/####\ /##\
############

```

An algorithm to calculate these ramps is the marching cubes algorithm.

When you want it to be even more beautiful, don't just use single polygons to interpolate between cubes, use curves of multiple polygons. But keep in mind that it will add quite a lot of polygons to your scene, so you should only do this for those cubes which are close to the camera.

# Answer
> 6 votes
There are two obstacles you need to deal with in order to achieve similar quality like the one in the image, the first is artistic and the second is technical (memory, processing). First I assume that you already solved your artistic problem, you can make the models, the art and the shaders etc. (Partially because I can't answer art problems)

The major technical problem is that when voxelizing those models you created in a high level of detail you will end up with huge number of tiny voxels. Processing and rendering huge number of voxels is not trivial. The answer to this is called Sparse Voxel Octrees

SVO will give you the ability to render highly detailed models without processing all the voxels, but only the visible ones. Note that in order to render SVO you will need to use ray-casting rather than the usual rasterization technique.

More details on SVO in this paper

Here is an open-source with BSD License implementation of SVO https://code.google.com/p/efficient-sparse-voxel-octrees/

Here is a video that explains polygon vs SVO based rendering (pros and cons).

---
Tags: opengl, rendering, voxels, terrain-rendering
---


title: YAW not working correctly with XNA

text:
# Question
Title: YAW not working correctly with XNA
I successfully draw the model, and made it move forward and backward, but when I try to make it rotates (yaw) its not working correctly, like its moving too instead of only rotate. Here is my camera code:

```
public class NewCamera
{
    float aspectRatio;
    public NewPlayer player;
    Matrix viewMatrix;
    Matrix projectionMatrix;
    Matrix terrainMatrix;

    public NewCamera(float aspectRatio, NewPlayer player)
    {
        this.player = player;
        this.aspectRatio = aspectRatio;
    }

    public void Update()
    {
        Vector3 campos = new Vector3(0, 0.2f, -0.6f);
        campos = Vector3.Transform(campos, Matrix.CreateFromQuaternion(player.rotation));
        campos += player.position;

        Vector3 camup = new Vector3(0, 1, 0);
        camup = Vector3.Transform(camup, Matrix.CreateFromQuaternion(player.rotation));

        viewMatrix = Matrix.CreateLookAt(campos, player.position, camup);
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 0.2f, 500.0f);
    }

    public void SetEffects(BasicEffect basicEffect)
    {
        basicEffect.View = viewMatrix;
        basicEffect.Projection = projectionMatrix;
        basicEffect.World = terrainMatrix;
    }

    public void Draw(Terrain terrain)
    {
        terrainMatrix = Matrix.CreateTranslation(terrain.position);
        SetEffects(terrain.basicEffect);
        foreach (EffectPass pass in terrain.basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            terrain.Draw();
        }
        player.Draw(viewMatrix, projectionMatrix);
    }
}

```

And here is my player (character) code:

```
public class NewPlayer
{
    Model model;
    public Vector3 position = new Vector3(8, 1, -3);
    public Quaternion rotation = Quaternion.Identity;
    public Matrix worldMatrix = Matrix.Identity;

    public NewPlayer(Model _model)
    {
        model = _model;
        foreach (ModelBone bone in model.Bones)
        {
            bone.Transform *= Matrix.CreateScale(0.01f);
        }
    }

    public void RecreateWorld()
    {
        worldMatrix = Matrix.CreateRotationY(MathHelper.Pi)
            * Matrix.CreateFromQuaternion(rotation)
            * Matrix.CreateTranslation(position);
    }

    public void Draw(Matrix viewMatrix, Matrix projectionMatrix)
    {
        RecreateWorld();
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = transforms[mesh.ParentBone.Index]
                    * worldMatrix;
                effect.View = viewMatrix;
                effect.Projection = projectionMatrix;
            }
            mesh.Draw();
        }
    }

    public void MoveForward(float speed)
    {
        Vector3 addVector = Vector3.Transform(new Vector3(0, 0, 1), this.rotation);
        this.position += addVector * speed;
    }

    public void MoveBackward(float speed)
    {
        Vector3 addVector = Vector3.Transform(new Vector3(0, 0, -1), this.rotation);
        this.position += addVector * speed;
    }

    public void Yaw(float amount)
    {
        this.rotation *= Quaternion.CreateFromYawPitchRoll(MathHelper.ToRadians(amount), 0, 0);
    }
}

```

So, whats wrong at the Yaw function??

EDIT: Adding some SS to show what I mean, it appears that it yaws around camera and not player

# Answer
I guess I found out the problem. Its not the model or camera that is not rotating, the problem is with the terrain. As the only thing I draw is model and terrain, I was basing my vision on the terrain, but when I log the position, its rotating the model and keeping it in the same position, wich is the correct thing to do, so its yaw is correct, the problem is with the terrain that is changing position. Ill try to find out the problem in the terrain, if I correct it I'll post here so others wont get the same error.
> 0 votes

# Answer
Since I misunderstood your question and your camera seems not to be working correctly here is a minimal solution for what you want to achive. (Note this is a bare bones example which uses only what you need)

```
class FollowCamera
{
    public Vector3 offset;
    public MeshTransform target;

    public Matrix view;
    public Matrix projection;

    public FollowCamera(Game game)
    {
        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 0.01f, 1000.0f);
    }

    public void Update(GameTime gameTime)
    {
        Vector3 cameraPosition = Vector3.Transform(offset, target.rotation);
        cameraPosition += target.position;
        view = Matrix.CreateLookAt(cameraPosition, target.position, Vector3.Up);
    }
}

class MeshTransform
{
    public Model mesh;
    public Vector3 position;
    public Quaternion rotation;

    public MeshTransform(Game game) {
        // From http://msdn.microsoft.com/en-us/library/bb197293%28v=xnagamestudio.31%29.aspx
        mesh = game.Content.Load<Model>("Models\\p1_wedge");
        position = Vector3.Zero;
        rotation = Quaternion.Identity;
    }

    public Matrix GetTransform() {
        return Matrix.CreateScale(Vector3.One * 0.005f) * Matrix.CreateFromQuaternion(rotation) * Matrix.CreateTranslation(position);
    }

    public void Draw(FollowCamera camera) {
        mesh.Draw(GetTransform(), camera.view, camera.projection);
    }
}

class Game1 : Microsoft.Xna.Framework.Game {
    GraphicsDeviceManager graphics;
    MeshTransform cameraTarget;
    MeshTransform referencePoint;
    FollowCamera camera;

    public Game1() {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void LoadContent() {
        cameraTarget = new MeshTransform(this);
        cameraTarget.position = Vector3.Backward * 5;
        referencePoint = new MeshTransform(this);
        referencePoint.position = Vector3.Forward * 150 + Vector3.Right * 50;
        camera = new FollowCamera(this);
        camera.offset = Vector3.Backward * 20;
        camera.target = cameraTarget;
    }

    protected override void Update(GameTime gameTime) {
        float dTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
        float turnSpeed = 10 * dTime;
        Quaternion rotation = cameraTarget.rotation;

        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            rotation = Quaternion.CreateFromYawPitchRoll(turnSpeed , 0, 0) * rotation;
        }
        else if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            rotation = Quaternion.CreateFromYawPitchRoll(-turnSpeed, 0, 0) * rotation;
        }
        cameraTarget.rotation = rotation;

        camera.Update(gameTime);

        base.Update(gameTime);
    }

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

        cameraTarget.Draw(camera);
        referencePoint.Draw(camera);

        base.Draw(gameTime);
    }
}

```

The camera is glued to the offset from the cameraTarget mesh, the important part is in FollowCamera::Update() to get a view matrix where the camera is behind your model you have to rotate the offset you want with the current offset from the model, you will get your offset in "transformed model space" then you just have to add the current position of your model to get the desired effect.

A small tipp I have for you is, use the Vector3.Up/Down/Left/Right... propertys. They are much less code to write and you can see by the name Up/Down... already what it is used for instead of looking at the constructor arguments you pass in.
> 1 votes

# Answer
I'm want to clarify about this line in your camera Update method

```
campos = Vector3.Transform(campos, Matrix.CreateFromQuaternion(player.rotation));

```

As I can understand you rotate camera with your model. If so you cannot not see rotation. Did you have any other objects in scene to determine that model realy rotated or not? Please add some screenshots with no rotation and with applying some yaw.
> 0 votes

# Answer
Not a pro at these things but try changing

```
effect.World = transforms[mesh.ParentBone.Index]
                * worldMatrix;

```

to...

```
effect.World =  worldMatrix
                * transforms[mesh.ParentBone.Index];

```
> -1 votes

---
Tags: xna, 3d
---


# Question
Title: OpenGL rendering to multiple windows, having 1 main loop for each window
I have written a little OpenGL framework in the past year that i would like to extend to support multiple windows in the near future. I have an idea about what I would like to do but I am not sure if that is possible so far.

I a nutshell the inner working of my framework is as following:

1. A window is created.
2. A render context for that window is created.
3. An application deriving from an interface is created.
4. window.run() is called, passing the application running in the window and the render context used as parameter.

```
sglr::W32Window w(nCmdShow);
w.create(L"DemoApp", sglr::DISPLAY_MODE::ENUM::WINDOWED, sglr::Resolution(800, 800));

sglr::W32Rendercontext r;
r.create(w, 4, 0, sglr::CONTEXT_TYPE::ENUM::DEBUG);

TestApp app;

return w.run(app, r);

```

The run method on the Win32 implementation looks like following (just some of the code):

```
        mRunningApp->onInit();

        // start message loop
        while (1)
        {

            while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
            {

                TranslateMessage(&msg);

                DispatchMessage(&msg);
            }

            // if message is WM_QUIT, exit loop
            if (msg.message == WM_QUIT)
                break;

            mRunningApp->onUpdate(mDt);

            mRenderContext->setAsCurrent();

            mRunningApp->onRender();

            mRenderContext->disableAsCurrent();

        }

    }

```

What I would like to do is to create a seperate window, rendercontext and application and start a seperate main loop by calling run() just like with the first window. I already have a seperate rendercontext for each window and know about setting it active before rendering to each window.
What possible solutions would exist to do that? Just running each run() method in a seperate threads sound like a kinda naive approach to me. (I admit I already tried it with failure :D)

# Answer
I think you mis-designed your API. Why does a window take an app, instead of an app taking multiple windows?

An application can have multiple windows, but a window can only belong to one application.

If you change this around there will be no need for multiple run loops. There will just be one in the application, and the application will handle events and dispatch rendering calls etc. for each window.
> 2 votes

---
Tags: opengl, window-management
---


# Question
Title: Handle vertex indicies in a vbo batch drawing call
I'm new in the OpenGL 2 world and want to render a lot of cubes (\> 150.000).

How can I render such kind of cubes in practise?

My idea is to split the cubes to a set of vbo's (Maybe 2000 cubes per vbo). Should I upload all cubes in one vbo or could I get a better performance with this approach?

Generally I have a problem, if I do a batch drawing call. On design side, I want to add some structure to my code, so I want to work with object-oriented programming for my cubes. In time each cube is a object from the class `cube.cpp`. The class contains, among other things, the verticies for geometry, color and indicies.

My problem in oop is to manage the indicies for the verticies of each shape. Has someone an idea to manage the indices?

# Answer
If you upload VBOs with many identical cubes inside of them you will just waste bus bandwidth. The keyword you should search for is "instanced rendering". There are many questions about it on here.
> 1 votes

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


title: Camera Movement Smoothing

text:
# Question
Title: Camera Movement Smoothing
I am trying to smooth a camera I create in my game, but I can't seem to find a way to actually do this correctly.

What I have :

```
//Calculate the "current" Forward vector
var cameraForward =
    -Vector3.Cross(-Self.forward, target.up)
    .normalized.Cross(target.up).normalized;
//Rotate the camera on the Y axis of the current target,
// and X Axis based on delta.y and CurrentVerticalLook
cameraForward =
    Quaternion.AngleAxis(delta.y, ViewTarget.transform.up) *
    Quaternion.AngleAxis(CurrentVerticalLook, Self.right) * cameraForward;

var offset = cameraForward * CameraDistance;
var pos = LookAt + offset;
Self.Position = pos;
Self.transform.LookAt(ViewTarget.position)

```

So what I ahve tried :

I tried Lerping the Vector Position, I tried smoothing the delta.y based on the last N frames.

The Camera I need is something like this :

Rotate on the Around UP Axis of the target and Rotate on Right Axis of the Camera, Camera Up is always = to Target UP.

So this is sort of Orbital Camera, but I am having trouble finding the correct rotation/operations. The way its set right works, but the camera movement is jaggy, but I can't seem to find a way to add Slerp in there without messing everything.

Thanks!

Edit : \<\>

# Answer
> 1 votes
All you really need is an exponential filter on each of the relevant variables. Have:

```
// Translation parameters
Vector3 target;

// Rotation parameters
float phi;
float theta;
float radius;

// Values we want to smoothly interpolate to
Vector3 nextTarget;
float nextPhi;
float nextTheta;
float nextRadius;

// Value between 0.0 and 1.0. If 1.0, no interpolation happens.
// If 0.0, no movement happens at all. Intermediate values determine
// intermediate interpolation
float alpha;

```

Here's how you calculate the new camera parameters:

```
void UpdateCurrentTarget()
{
    target = (alpha) * nextTarget + (1.0f - alpha) * target;
    phi =    (alpha) * nextPhi    + (1.0f - alpha) * phi;
    theta =  (alpha) * nextTheta  + (1.0f - alpha) * theta;
    radius = (alpha) * nextRadius + (1.0f - alpha) * radius;
}

```

The camera parameters will converge to the new values smoothly. Here's how you actually compute the pose of the camera using spherical coordinates:

```
void UpdateCameraPose()
{
    float x = radius * sin(theta) * cos(phi) + target.x;
    float y = radius * sin(theta) * sin(phi) + target.y;
    float z = radius * cos(theta) + target.z;

    Self.transform.position = new Vector3(x, y, z);
    Self.transform.LookAt(target);
}

```

I prefer to do it this way because no quaternions are required.However, because they are Euler Angles, you will inevitable run into Gimbal Lock at around `phi = +/- 0.5 * pi`, as well as the `LookAt` function failing due to having the wrong up vector. You can avoid this by limiting `phi` so it never gets to `0.5 * pi`.

---
Tags: unity, camera, rotation, quaternion
---


title: Coins don't show up in game in Unity

text:
# Question
Title: Coins don't show up in game in Unity
I have a 2D game I'm making with Unity, and I want the player to be able to collect coins that I place all over the game. I used the coin prefab with a 2D circle collider and an animation to make it spin. The problem is that only the first coin I put into the scene shows up in the game, and when I collect that one coin, the counter shows that all the others have been collected as well. Here's the script I attached to the player for the coins:

```
private uint tokens = 0;

void OnGUI(){
    GUILayout.Label ("Tokens= " + tokens);
}

void CollectToken(Collider2D tokenCollider){
    tokens++;
    Destroy (tokenCollider.gameObject);
}

void OnTriggerEnter2D(Collider2D col){
    if (col.gameObject.CompareTag ("token")) {
        CollectToken(col);
    }
}

```

This is my current setup for the object properties:

Thank you for any help!

# Answer
I would add a bool for isCollected; so if(isCollected) token++

you want the coin to be inside a empty gameobject so when you go to animate it you are animating the child so it doesn't move all the coins to the position of where you created the first.
> 0 votes

---
Tags: unity, 2d, game-design
---


# Question
Title: Add XNA math references to non-xna project
I'm developing some game with server/client structure, and the client will predict the movements, but it should be validated by the server. In the client part, I got it moving nice, but now I'm trying to test it with the server calculating the movement. The problem is the client I use the xna classes like Quaternion, Vector3, Matrix, etc. Is there anyway to get this XNA classes in the server without making it a xna project??

I found a site with sources of the classes like XNA geomtries, but when I tried it out, it dont got the same results, so I'm still looking for the sources of it, or someother sources that gets at the same results for me to add into the server

# Answer
Assuming you're using a custom server written in C# with Visual Studio and you have access to the source...

1. Open Visual Studio, and go to your server project
2. Right mouse click on 'References' and then left click 'Add Reference'
3. Switch to the .NET tab, and scroll down to find 'Microsoft.Xnz.Framework'
4. Select it and then click on OK
5. Add 'using Microsoft.Xna.Framework;' to your server class files.
6. Use Vector, Matrix and Quaternion objects as normal.

Of course, this relies on the server having the Xna game studio installed on it. If you don't have the Xna framework installed on the server, you can either download and run the installer from here or search the GAC (Global Assembly Cache) on your build computer for the Microsoft.Xna.Framework.dll file, and then drop it into the bin folder of your server program when it gets deployed, but the framework installer is (IMO) the easier and safer way to go.

You can also add Xna assemblies to a project without making it an Xna project, its just that an Xna project has all the Xna framework references added by default. I currently have a Form and a Class Library project using Xna references, and they still run/compile as a Forms project and a Class Library .dll
> 0 votes

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


title: Easiest way to make a 3D overworld

text:
# Question
Title: Easiest way to make a 3D overworld
Using something like Blender, would it be easier and more time and space efficient to create 'tiles', and use some kind of software like Tiled to use these tiles in the various maps, or would it be faster to just create the entire maps in Blender?

I ask because the first approach sounds better, in that it takes less space, time and effort, but the second approach seems to be used everywhere. Right now my game uses tiles, but it's very hard to add any kind of elevation. So should I ditch tiles for building the entire scene in Blender or not?

(sorry if my question doesn't fit the format!)

# Answer
> 1 votes
Why not ~~Zoidberg~~ both?

Make a big 3D model of your map. Then, cut it into pieces. The size of the pieces doesn't matter all that much, but it'll be an inverse relationship between memory and speed. The bigger your "chunks" are, the more memory it will take, but the less often you'll have to load new ones. It's the opposite for small chunks.

In the code itself, only load the chunks closest to the player. As the player moves in a direction, load the chunks in that direction so that the map always appears roughly the same size.

One way that pops to mind immediately is to wait for a player to cross the border of a chunk, then load whatever chunk is next in that direction, and unload whatever loaded chunk is farthest in the opposite. Some pseudocode(ish) to illustrate what I mean:

```
void onPlayerMove(Player player):
    do:
        if (player.isOnCurrentChunk) break
        if (player.xPos > player.currentChunk.xMax):
            loadChunk(EAST)
            unloadChunk(WEST)
            moveCurrentChunk(EAST)
        else if (player.xPos < player.currentChunk.xMin):
            loadChunk(WEST)
            unloadChunk(EAST)
            moveCurrentChunk(WEST)
        else if (player.yPos > player.currentChunk.yMax):
            loadChunk(NORTH)
            unloadChunk(SOUTH)
            moveCurrentChunk(NORTH)
        else if (player.yPos < player.currentChunk.yMin):
            loadChunk(SOUTH)
            unloadChunk(NORTH)
            moveCurrentChunk(SOUTH)
        else break
    while true

```

`loadChunk(direction)` would load a chunk from a file or something and place it in the appropriate spot.

`unloadChunk(direction)` would find the chunk that's farthest in that direction and unload it from memory, saving it to disk if it might be changed so that those changes persist. Or not, if you don't want changes to persist.

Both could also load/unload the entire row of chunks in that direction, the chunk and the ones adjacent to it, whatever; the implementation is up to you. You could also use different boundaries for the chunks, but that might be more annoying to implement, since you'd have to separate the loading/unloading to prevent it from spiraling out of control.

`moveCurrentChunk(direction)` would change the chunk that the player is supposed to be changing on to the adjacent one in X direction.

This whole thing is looped so that if someone goes off the corner, it records them as going off in both directions, as opposed to one arbitrary one. In addition, this will automatically move to wherever they are, one chunk at a time, if you have some mechanism by which they can move more than one chunk at a time and you don't want to implement some special function for them.

You could probably also do something with their speed; loading the chunk early if they're going fast (e.g. on a mount or the like), or loading more than one at a time. Again, that's all up to you.

Hope this helped.

---
Tags: 3d, models, tilemap, maps, levels
---


# Question
Title: Unity 4.6 UI Replace Images on selection in List of buttons[i]
I made a list containing all the buttons in the UISelectionCanvas and would like to change each image as it is being selected. The problem is once the selection selects a new type of unit it will change all the buttons sprites in the list to the new selection instead of just changing the one selected.

```
     for a example imagine I have 10 units 9 peasants and 1 warrior

```

as each peasant is selected the sprite adds the peasant icon to the button. if 8 peasants are selected and then the 9th selection is a warrior it changes all 9 buttons to a warrior icon then if I selects the 10th peasant it changes them all back to peasant.

```
        for (int i = 0; i < buttons.Count; i++)
        {
            for (int c = 0; c < SelectedUnits.Count; c++)
            {
                if (i <= c)
                {
                   buttons[i].SetActive(true);

                  foreach (var unit in SelectedUnits)
                 {
                   if(unit.tag == "Peasant")
                 {
                    buttons[i].transform.GetComponent<Image>().sprite = peasant as Sprite;
                 }
             else if(unit.tag == "CityGuard")
            {
               buttons[i].transform.GetComponent<Image>().sprite = warrior as Sprite;

          }
        }

      }
      else
      {
      buttons[i].gameObject.SetActive(false);
    }
 }

```

}

# Answer
You probably don't want to be looping through SelectedUnits (not at all, and definitely not twice!) So something like:

```
for (int i = 0; i < buttons.Count; i++) {
  if (i < SelectedUnits.Count) {
    buttons[i].SetActive(true);
    var unit = SelectedUnits[i];

    if(unit.tag == "Peasant") {
      buttons[i].GetComponent<Image>().sprite = peasant as Sprite;
    }
    else if(unit.tag == "CityGuard") {
      buttons[i].GetComponent<Image>().sprite = warrior as Sprite;
    }
  }
  else {
    buttons[i].SetActive(false);
  }
}

```
> 1 votes

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


title: LibGDX multiple enemies animations

text:
# Question
Title: LibGDX multiple enemies animations
Hello everyone i have a question about animating multiple enemies on the screen at the same time.

Basically, i figured out how to use the Pool for creating enemies and dispose them after use etc.. All enemies are equal to each other, and all enemies have 3 different animations for creating, moving, destroying.

Everything is working fine, but when i have multiple enemies on screen, they are all animating at the same times, even if they were (obviously) created in different times.

For example, i create 3 enemies, make them moving on the screen and they all have the same frame.. the animation must be the same for all, but i expected that the time when they change frame should be different.

The animations are instantiated inside the Enemy class, so i guess every instance of Enemy must have its own animation.

This is how i draw them in the Renderer class:

```
private void drawEnemies(float runTime) {
    enemyArrayLen = catta.activeEnemies.size;
    for (int i = enemyArrayLen; --i >= 0;) {
        currentEnemyAnimation = catta.activeEnemies.get(i).getCurrentAnimation();
        batcher.draw(
            currentEnemyAnimation.getKeyFrame(runTime),
            catta.activeEnemies.get(i).getX(),
            catta.activeEnemies.get(i).getY(),
            catta.activeEnemies.get(i).getWidth() / 2.0f,
            catta.activeEnemies.get(i).getHeight() / 2.0f,
            catta.activeEnemies.get(i).getWidth(),
            catta.activeEnemies.get(i).getHeight(),
            1,
            1,
            0
        );
    }
}

```

Enemies are stored in the catta.activeEnemies array.

currentEnemyAnimation is a "support" variable in which i put the Enemy in every cicle of the for cicle.

This is how i initialize an Enemy:

```
public void init(float posX, float posY, int width, int height) {
    this.position.set(posX,  posY);
    this.width = width;
    this.height = height;
    this.alive = true;
    this.enemyRunTime = 0;
    this.creationTime = 0.8f;
    this.destructionTime = 0.8f;
    this.crea_Animation = AssetLoader.enemy_creaAnimation;
    this.crea_Animation.setFrameDuration(this.creationTime / 4);
    this.mo_Animation = AssetLoader.enemy_moAnimation;
    this.des_Animation = AssetLoader.enemy_desAnimation;
    this.des_Animation.setFrameDuration(this.destructionTime / 4);
    this.enemyState = EnemyState.CREATING;
    ...

```

Maybe it's all a runTime and delta matter?

# Answer
> 1 votes
SOLVED, i had to pass the enemyRunTime to batcher when drawing each enemy, instead of the global runTime.. like this:

```
private void drawEnemies(float runTime) {
    enemyArrayLen = catta.activeEnemies.size;
    for (int i = enemyArrayLen; --i >= 0;) {
        currentEnemyAnimation = catta.activeEnemies.get(i).getCurrentAnimation();
        batcher.draw(
            currentEnemyAnimation.getKeyFrame(catta.activeEnemies.get(i).getEnemyRunTime()),
            catta.activeEnemies.get(i).getX(),
            catta.activeEnemies.get(i).getY(),
            catta.activeEnemies.get(i).getWidth() / 2.0f,
            catta.activeEnemies.get(i).getHeight() / 2.0f,
            catta.activeEnemies.get(i).getWidth(),
            catta.activeEnemies.get(i).getHeight(),
            1,
            1,
            0
        );
    }
}

```

Now each enemy animates independently from the others

---
Tags: libgdx
---


# Question
Title: Textures "don't work" when I don't specify any texture parameters. Is this a driver bug or intended behavior?
Whenever I try to use textures, I have to at least specify the sample filtering parameters (GL\_TEXTURE\_MAG\_FILTER, GL\_TEXTURE\_MIN\_FILTER) for textures to work at all. If I don't, sampling the textures in a shader will usually just return a value of 0 for all texels in the texture, even though glReadPixels return the correct values, and rendering to the textures actually works. Debugging tools like Nsight and gDebugger confirm this.

I tested this on two NVIDIA GPUs (GTX 970, GT 555m) with the latest driver versions (347.09), and the behavior is the same.

However, I can't find any reference to this in docs like this or this

I assumed that not specifying these parameters just made them take on their default values. So is this actually intended standard behavior (probably meaning "undefined behavior") or can I assume this is a driver bug?

# Answer
> 6 votes
By default, OpenGL assumes that your textures will have mipmaps attached. If you haven't attached any mipmaps to a texture, then OpenGL assumes that you didn't finish setting it up. OpenGL will therefore deem the texture to be "incomplete" and will refuse to render from it.

In order to make your texture "complete" in OpenGL's eyes (and therefore usable for rendering), you need to do **one** of the following:

* Set `GL_TEXTURE_MIN_FILTER` to something which won't try to use mipmap data. (`GL_NEAREST` or `GL_LINEAR`)
* *or* set `GL_TEXTURE_MAX_LEVEL` to 0, thus explicitly declaring that your texture has no mipmaps, so that OpenGL won't be bothered by their nonexistence.
* *or* create mipmaps for your texture.
* *or* tell OpenGL to automatically create the mipmaps for you, using `glGenerateMipmap()` or the `GL_GENERATE_MIPMAP` texture parameter.

You can read more discussion of this issue in opengl.org's Common Mistakes document. This issue is number six in their list; "Creating a complete texture".

---
Tags: opengl
---


# Question
Title: 2D bouncing formula doesn't work properly
I am new to Unity, and I am trying to create a bouncing ball, so I've been researching bouncing related physics and I found a formula:

Formula:

```
-2*(V dot N)*N + V

```

Where V is the velocity vector and N is the normal of the surface on which the ball will bounce

Here is my script :

```
using UnityEngine;

using System.Collections;

public class BallPhysics : MonoBehaviour {

    void Start () {
        rigidbody2D.velocity =new Vector2 (-1,-3);

    }

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

    }
    void OnTriggerEnter2D(Collider2D col) {

        if (col.gameObject.name == "Pong") {
            tBounce ();
                }

    }

    void tBounce(){
        RaycastHit2D hit = Physics2D.Raycast (new Vector2 (transform.position.x,transform.position.y), rigidbody2D.velocity);
        Vector2 n = hit.normal;
        Vector2 v = rigidbody2D.velocity;
        Vector2 R = -2 * (Vector2.Dot (v, n)) * n + v;
        rigidbody2D.velocity = R;
    }
}

```

I am giving the ball a velocity vector in the start function, i am using OnTriggerEnter2D for collision handling and raycast2D to get the normal of a surface.

The problem is that the script doesn't reflect the velocity vector called R, I think the problem is in the normal vector.

For example let's say V is a Vector2(-1,-1) so basically R should be (-1,1), but it's not. R is (3,1) !

I've successfully been able to make a ball bouncing on Horizontal/vertical surface by reversing the ball velocity but this won't work properly with arbitrary angles, that's why I am using this formula. So what's the problem ?

# Answer
normalize your normal vector `n` before using in in the reflect formula.

```
Vector2 n = hit.normal;
n.Normalize();

```
> 0 votes

---
Tags: unity, 2d, physics, raycasting
---


# Question
Title: How can I make this shader background more efficient?
I want to use a shader as a background for a mobile game. I'm using libgdx for my project. I've never written glsl before, but here's my attempt so far:

http://glslsandbox.com/e#22332.13

On desktop the code runs fine, but on mobile it can be a bit slow sometimes. I have read that using built in functions reduces branching, so I tried to use mix and smoothstep instead of if statements.

I'm also not sure if I am rendering the shader correctly in the first place.

First I'm creating a TextureRegion:

```
fbo = new TextureRegion(new FrameBuffer(Pixmap.Format.RGB888, width, height, false).getColorBufferTexture());

```

Then I create a rectangle mesh, and render the shader as 2 triangles on the mesh. The device/window resolution is also passed to the shader as a uniform.

Then I am calling batch.setShader(background); and finally batch.draw(fbo, 0, 0, width, height);

Is there a better way I can achieve this?

Code from the link above:

```
#ifdef GL_ES
precision mediump float;
#endif

uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
//created 1/15/2015 by alex booth

const vec3 sky_top_color = vec3(90.0/255.0, 200.0/255.0, 190.0/255.0);
const vec3 sky_bot_color = vec3(235.0/255.0, 235.0/255.0, 215.0/255.0);

const vec3 hill_1_color = vec3(170.0/255.0, 210.0/255.0, 205.0/255.0);
const vec3 hill_2_color = vec3(150.0/255.0, 190.0/255.0, 185.0/255.0);
const vec3 hill_3_color = vec3(110.0/255.0, 142.0/255.0, 135.0/255.0);

void main(void) {
    vec2 pos = (gl_FragCoord.xy / resolution.xy);

    float hill_1 = 0.060*sin(pos.x*6.0+time*0.100)*sin(time*0.10)+0.55;
    float hill_2 = 0.075*sin(pos.x*6.0-time*0.090)*sin(time*0.12)+0.45;
    float hill_3 = 0.100*sin(pos.x*6.0+time*0.095)*sin(time*0.14)+0.30;

    //sky, far, middle, and closest
    vec3 color = mix(sky_bot_color, sky_top_color, smoothstep(hill_1, 1.0, pos.y));
    color = mix(color, hill_1_color, smoothstep(hill_1 + 0.004, hill_1, pos.y));
    color = mix(color, hill_2_color, smoothstep(hill_2 + 0.004, hill_2, pos.y));
    gl_FragColor = vec4(mix(color, hill_3_color, smoothstep(hill_3 + 0.004, hill_3, pos.y)), 1.0);
}

```

# Answer
What makes you think this is the shader code that is slow ? In most machines nowadays, and especially mobile devices, the bottlenecks are not these purely calculation-fed (ALU loaded) shaders, but memory bandwidth.

Memory bandwidth is used by framebuffers being fed to shaders as textures, or by the ROPs writing to the render target. Especially bad when render targets are multiple, or floating formats. This of course incrases with the sequare of the resolution and we know mobile devices have SUPER HIGH DPI. capitals intended.

What I suggest is to use half the resolution of your hardware native screen resolution + good antialiasing techniques like SMAA. This should accelerate wonders.

Tip: if you want to prove that you are going to accelerate something by optimizing this specific shader, make it return hardcoded red, and check your FPS.
> 1 votes

---
Tags: android, libgdx, shaders, glsl, mesh
---


title: Locked frame rate

text:
# Question
Title: Locked frame rate
I'm a little bit confused about the way game engines handle frame rate. Correct me if I'm wrong:

1. By my assumptions, usually we have a frame rate which graphical API runs by it and a frame rate called fixed frame rate which other parties like physics, network etc. run by it.
2. I know with v-sync on, the frame rate for graphical API would be the display device refresh rate which is usually 60hz in nowadays monitors, and with v-sync off graphical API wouldn't wait for display device to draw previous frame completely and it constantly sends the new frame. So, if I turn v-sync on and change refresh rate to something I like, then frame rate for graphical API would be locked by that rate and if I turn v-sync off, then frame rate for graphical API would be as fast as possible.
3. If my previous assumptions are correct, then why have we for example a `Time.captureFramerate` which locks the render frame rate and a `Resolution.refreshRate` with the same intention in an engine like Unity3D?
4. And, what does it mean when game developers say we locked the frame rate at 30 or 60 frames per second? Does this mean they leave v-sync on and set refresh rate to 30 or 60 and user is not able to alter v-sync at runtime?

If we are to limit the main loop which render operation runs under it, is this the way?

```
while (main_loop)
{
  while (fixed_loop)
  {
    // Stuff
  }

  // Lock main loop to 30 fps
  if (render_time >= 1 / 30)
  {
    render_time -= delta;

    Sleep(1);

    continue;
  }

  render();
}

```

# Answer
Usually game that claims they use locked frame rates, they are doing so by using a system timer in a thread that pulsates the game rythm like a metronome. The rendering thread will sleep on some condition variable waiting to be notified by this thread before calling `Swap` or `Present`.

This approach has many problems, like not being in good synch with the actual display, not interleaving well if vsynch is ON because of double waiting, which if everything runs smooth should compensate after the first frame, but every some thousands frames some stutter may happen. This is something that also depends a lot on the platform, depending on timer precision. On windows people use `timeBeginPeriod` and set it to 1, 2 or 5ms... the point is less than half of 16 is necessary.
http://msdn.microsoft.com/en-us/library/windows/desktop/dd757624(v=vs.85).aspx
Flash plugin does that (annoyingly). And most movie players.

Of course it is not so straightforward to have a game where each part is nicely decoupled, and refresh rate can drift freely between each part. They are possible but require great care from everybody, and mostly the higher level engine architects. This is not always buisness-friendly because of increased dev costs.

Also check that out:
http://gafferongames.com/game-physics/fix-your-timestep/
> 1 votes

---
Tags: frame-rate
---


# Question
Title: How to order objects with the same depth in the spritebatch cycle?
I have a tilemap in a isometric 2.5 view and i have also many objects moving and static. The problem is many statics are standing in a "integer" place for obvious reasons and the depths of each object is calculated based on their position in the tilemap.

So what happens for some strage reasons is that 2 objects standing next to each other if big enough overlap and if they are in an adjacent diagonal tile they also have the same exact depth, but when drawing the order of same depth object seems random... I draw them in the same order every cycle ofc but the overlapped part of the texture sort of flicker being drawed on top or bottom apparently randomly...

Is there a way to use depth to order objects but make the same depth ones be in some kind of order and not random?

# Answer
> 1 votes
What you describe here is often called z-fighting, and is a product of the fact that the items have exactly the same depth. Now, while iterating objects to draw, you could check if you've already drawn an object close to it that it might overlap with. You could then set the depthbias of your graphicsdevice's rasterizerstate to make sure they don't flicker. The depthbias should always be VERY close to 0. If you want to make sure one object draws in front of another that has the same depth, set the bias to be about -0.000000001 (give or take a few zero's)

A negative depthbias makes the object come forward, a positive depthbias makes the object go backward.

---
Tags: xna
---


# Question
Title: Unity3D rendering only some triangles in a mesh - and triangle fans?
In my OpenGL apps, one of my tricks that I've used often for displaying heads up displays and ui elements, is to have a sorted mesh of triangles and then only render a portion of them.

In one game I have a circular fuel gauge. I made a mesh of triangles using a triangle fan that spans around the circle. In code I can limit the number of triangles that it's drawing to make the fuel gauge appear at that % of fuel.

So in this example I take the % of fuel left, multiply by the number of segments in the fan, and then draw it:

```
    glDrawElements(GL_TRIANGLE_FAN, (int)remainingFuel+1, GL_UNSIGNED_INT, (void *) (0 * sizeof(GLuint)));

```

If 50% of the fuel is left it draws 50% of the triangles in the fan which appears to be half the circle shape.

Can this easily be replicated in Unity3D? Where I can limit the range of triangles of a mesh that will render to a specific start and stop range?

Does Unity3D even do triangle fans?

Or do I need to figure out a new way to do this?

By the way I do know how to create procedural meshes in unity code (C#) but am still fairly new to Unity. I know I could store the entire mesh in one class and then copy only a portion of it to a game object based on the fuel level. I'd rather not create a new version of the mesh for each frame because the fuel is constantly changing. It seems more efficient to just limit the count on a non-changing mesh.

# Answer
> 2 votes
Instead of manipulating meshes in Unity, I'd use a Shader instead. It gives you more control over the appearance of your gauge and will perform better.

For starters, you could use the built-in alpha cutoff shader and use a circular gradient as your cutoff ramp. Something like this should do the trick:

Then you can manipulate the cutoff value like this:

```
renderer.material.SetFloat("_Cutoff", myCutOffValue);

```

where `myCutOffValue` is a float ranging from `0` to `1`.

**Update:**

As requested in the comments, here's a shader-example that uses two textures. One for RGBA and the other for the cutoff. You can create a new shader in Unity and replace the automatically generated code with the following:

```
Shader "Custom/SeparateCutout" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
        _CutTex ("Cutout Texture", 2D) = "white" {}
        _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
    }

    SubShader {
        Tags {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
        }
        LOD 200

    CGPROGRAM
    #pragma surface surf Lambert alpha

        sampler2D _MainTex;
        sampler2D _CutTex;
        fixed4 _Color;
        float _Cutoff;

        struct Input {
            float2 uv_MainTex;
            float2 uv_CutTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            fixed4 cut = tex2D(_CutTex, IN.uv_CutTex);
            clip(cut.a - _Cutoff);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
    ENDCG
    }

    Fallback "Transparent/VertexLit"
}

```

You'll find this shader under `Custom` \> `SeparateCutout` in the shaders dropdown. For the cutout texture, I recommend you set it to `Alpha 8` (available under `Format`, when you switch the Texture type to "Advanced". Use "Alpha from Grayscale" setting if necessary). That way you'll save some GPU memory.

---
Tags: unity, mesh
---


title: Rotate arrow on canvas

text:
# Question
Title: Rotate arrow on canvas
I need to draw a flow dynamically based on some user choices. In that flow I want to draw the choices (blue circles with number) and the directions of that choices (line and arrow). For example: node 1 to node 2.

JSFiddle Example

To draw the direction I draw a arrow in the end of the line but I can't make the arrow rotate around itself.

**JS code**

```
$(document).ready(function () {
    drawOnCanvas();
});

function drawOnCanvas() {
    var canvas = document.getElementById('myCanvas');

    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        var circle1 = {
            x: 75,
            y: 75,
            r: 15
        };

        var circle2 = {
            x: 225,
            y: 50,
            r: 15
        };

        var arrow =
            {
                h: 5,
                w: 10
            };

        drawCircle(ctx, circle1, "1");
        drawCircle(ctx, circle2, "2");

        var ptCircle1 = getPointOnCircle(circle1.r, circle1, circle2);
        var ptCircle2 = getPointOnCircle(circle2.r, circle2, circle1);
        var ptArrow = getPointOnCircle(circle2.r + arrow.w, circle2, circle1);

        drawLine(ctx, ptCircle1, ptCircle2);
        drawArrow(ctx, arrow, ptArrow, ptCircle2);
    }
}

function drawArrow(canvasContext, arrow, ptArrow, endPt) {

    var angleInDegrees = getAngleBetweenPoints(ptArrow, endPt);

    canvasContext.beginPath();
    // first save the untranslated/unrotated context
    canvasContext.save();

    // move the rotation point to the center of the rect
    canvasContext.translate(ptArrow.x, ptArrow.y);
    // rotate the rect
    canvasContext.rotate(angleInDegrees);

    canvasContext.moveTo(endPt.x, endPt.y);
    canvasContext.lineTo(endPt.x - arrow.w, endPt.y + arrow.h);
    canvasContext.lineTo(endPt.x - arrow.w, endPt.y - arrow.h);
    canvasContext.closePath();
    canvasContext.fillStyle = "rgb(72,72,72)";
    canvasContext.stroke();
    canvasContext.fill();

    // restore the context to its untranslated/unrotated state
    canvasContext.restore();
}

function drawCircle(canvasContext, circle, text) {
    canvasContext.beginPath(); //começa ou reinicia o desenho de algo
    canvasContext.fillStyle = "rgb(43,166,203)";
    canvasContext.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI, false); //cria arcos
    canvasContext.fill(); //atribui estilos

    drawText(canvasContext, circle, text);
}

function drawText(canvasContext, circle, text) {
    canvasContext.font = '8pt Calibri';
    canvasContext.fillStyle = 'white';
    canvasContext.textAlign = 'center';
    canvasContext.fillText(text, circle.x, circle.y + 3);
}

function drawLine(canvasContext, startPt, endPt) {
    canvasContext.moveTo(startPt.x, startPt.y);
    canvasContext.lineTo(endPt.x, endPt.y);
    canvasContext.stroke();
}

function getPointOnCircle(radius, originPt, endPt) {
    var angleInDegrees = getAngleBetweenPoints(originPt, endPt);

    // Convert from degrees to radians via multiplication by PI/180
    var x = radius * Math.cos(angleInDegrees * Math.PI / 180) + originPt.x;
    var y = radius * Math.sin(angleInDegrees * Math.PI / 180) + originPt.y;

    return { x: x, y: y };
}

function getAngleBetweenPoints(originPt, endPt) {
    var interPt = { x: endPt.x - originPt.x,
        y: endPt.y - originPt.y
    };

    return Math.atan2(interPt.y, interPt.x) * 180 / Math.PI;
}

```

I think the problem is in drawArrow() method in the lines

```
canvasContext.translate(ptArrow.x, ptArrow.y);

canvasContext.rotate(angleInDegrees);

```

I already tried every possible values for the rotation and the translation but arrow still don't rotate properly around itself. Can anyone help me?

# Answer
> 3 votes
You got it wrong in your draw code : once you translated the context to a given point, you shouldn't use any more the point coordinates : the 'zero' is now at the translation point.
So to draw your arrow after you translated to its start point, just translate by the size of the arrow.

http://jsfiddle.net/gamealchemist/jxrdtLxx/2/

```
function drawArrow(canvasContext, arrow, ptArrow, endPt) {
    var angleInDegrees = getAngleBetweenPoints(ptArrow, endPt);

    // first save the untranslated/unrotated context
    canvasContext.save();

    // move the rotation point to the center of the rect
    canvasContext.translate(ptArrow.x, ptArrow.y);
    // rotate the rect
   canvasContext.rotate(angleInDegrees*Math.PI/180);

    canvasContext.beginPath();
    canvasContext.moveTo(0,0);
    canvasContext.lineTo( 0, -arrow.h);
    canvasContext.lineTo( arrow.w, 0);
    canvasContext.lineTo( 0, +arrow.h);
    canvasContext.closePath();
    canvasContext.fillStyle = "rgb(72,72,72)";
    canvasContext.stroke();
    canvasContext.fill();

    // restore the context to its untranslated/unrotated state
    canvasContext.restore();
}

```

Rq : i changed your css, since it was scaling the canvas. Change the size of the canvas directly in the canvas tag to avoid stretching artifacts.

---
Tags: javascript, html5, html-canvas, jquery
---


title: What GameEngine to choose

text:
# Question
Title: What GameEngine to choose
I concider myself an amateur, but I have quite some experince in Unity3D.

Over the course of the next three years - before I can quit my job and go to colledge - I want to make ONE game.

Now the question that bothers me is which gameengine to choose:

A) Unity3D, because I know it well and the community is great (even though I didn't touch it for a year or so)

B) GoDotEngine, because it's open source, still beeing improved and very lightweight

C) Blender, because Python (though..who really uses blender for games? and I kinda hate blender)

Initially I wanted to go with GoDot, since it is a lot like Unity and OpenSource, but I fear that the community is to small to help me out, if I get stuck and I really need to finish this, if I want to spend three years on it.

# Answer
> 0 votes
its best to choose Unity 3D game engine. As its easy and quickly to learn. Excellent community help, even in my 1.5 year career I didn't stuck on a single task, Every time I got the solution. So, I always prefer Unity 3D.

# Answer
> 0 votes
It depends mostly to the kind of game you are going to produce.

If you are going to prduce a FPS I can suggest Torque 3D by Garagegames

https://github.com/GarageGames/Torque3D \<- MIT license and HUGE community and tons of manuals and resources

An RTS is better done via Spring Engine HUGE community too

But tel lme what kind of game you are going to do and I'll edit this answer accordingly

---
Tags: unity, blender-game-engine
---


# Question
Title: Draw GUI.Button on certain position on a scrollable background
Problem is in a 2D game I have a large background around 2 screens wide. And on there I got 4 buttons placed on top of background all over complete width. Now when I swipe of move my mouse around I scripted that the camera will move with it. So for the GUI.Buttons (Unity4.5) to stick on their place I used a variable drawX

```
 drawX = Camera.main.transform.position.x * 100;

```

The 100 is for calculating it to pixels. I then add this to my buttons when drawing.

```
scaleX = Screen.width / 1920f;
 scaleY = Screen.height / 1200f;
 if (GUI.Button(new Rect((500 - drawX) * scaleX, 700 * scaleY, 325 * scaleX, 425 * scaleY), ""))

```

Now the problem is that under 1920x1200 my target resolution everything works exactly pixel perfect. But when changing the resolution or aspect ratio to something else the drawX increases to much or not enough so the buttons don't move on the same pace as they did in the 1920x1200 version. Somebody got the solution for me?

# Answer
> 1 votes
I'd wager it's related to you using this "DrawX" value for only one of the rect coordinates. I don't know Unity, but I'd wager that it at least needs to be applied to one other corner of the rect (the other X).

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