# Question
Title: InvalidOperationException when using C# DLLs with Unity3D
# Description

I've been attempting to use a custom DLL in Unity. I've confirmed the DLL runs correctly outside Unity.

The DLL imports into Unity and when I refer to it in my scripts, I get no compiler errors. However, trying to run a function from the DLL at runtime gives this error:

```
InvalidOperationException: Client endpoint configuration '*' was not found in 0 endpoints.
System.ServiceModel.ChannelFactory.ApplyConfiguration (System.String endpointConfig)
System.ServiceModel.ChannelFactory.InitializeEndpoint (System.String endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress)
System.ServiceModel.ChannelFactory`1[DNDUtility.ContentVaultServiceTest.IContentVaultService]..ctor (System.String endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress)
System.ServiceModel.ClientBase`1[TChannel].Initialize (System.ServiceModel.InstanceContext instance, System.String endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress)
System.ServiceModel.ClientBase`1[TChannel]..ctor (System.ServiceModel.InstanceContext instance, System.String endpointConfigurationName)
System.ServiceModel.ClientBase`1[TChannel]..ctor (System.ServiceModel.InstanceContext instance)
System.ServiceModel.ClientBase`1[TChannel]..ctor ()
DNDUtility.ContentVaultServiceTest.ContentVaultServiceClient..ctor ()
DNDUtility.DataManager..cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for DNDUtility.DataManager
TestStuff.OnGUI () (at Assets/TestStuff.cs:39)

```

I've tried compiling the DLL with .NET 4, 4.5, 3.5, and 2. (I can provide the DLL file if needed.)

What causes this?

# Code listings

## DLL code

```
using System;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Text;
using System.IO;

namespace DNDUtility
{
    using ContentVaultServiceTest;

    public class DataManager
    {
        static ContentVaultServiceClient contentClient = new ContentVaultServiceClient();

        public static bool Login(string user, string pass)
        {
            return contentClient.Login(user,
                SimpleEncrypt(pass, user));
        }

        public static string[] GetChars()
        {
            ContentInfo[] content = contentClient.GetAvailableContent(0);

            string[] chars = new string[content.Length];

            for (int i = 0; i < content.Length; i++)
            {
                XDocument doc = XDocument.Parse(content[i].CommittedContent.Details.ToString());
                var name = doc.Element("CharacterDetails").Element("Name").Value;

                chars[i] = string.Format("{0} : {1}", i, name);
            }

            return chars;
        }

        public static void GetData()
        {
            ContentInfo[] content = contentClient.GetAvailableContent(0);

            DataWithVersion data = contentClient.GetData(
                new ContentIdentifier() { ContentID = content[0].CommittedContent.Identifier.ContentID },
                null);

            RawContentBlob blob = data.Data as RawContentBlob;

            String charFile = new UTF8Encoding().GetString(blob.RawData, 0, blob.RawData.Length);

            XDocument doc = XDocument.Parse(charFile);
            doc.Save("d:\Users\Tim Williams\Desktop\Work Documents\TerabyteTim\DND App\ContentVault\ConsoleApplication1\contentdoc.xml");
        }

        public static byte[] SimpleEncrypt(string value, string key)
        {
            byte[] buffer2;
            ICryptoTransform transform = GetSimpleAlgorithm(key).CreateEncryptor();
            using (MemoryStream stream = new MemoryStream())
            {
                using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write))
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(value);
                    stream2.Write(bytes, 0, bytes.Length);
                    stream2.Flush();
                    stream2.FlushFinalBlock();
                    stream.Position = 0L;
                    buffer2 = stream.ToArray();
                }
            }
            return buffer2;
        }

        static SymmetricAlgorithm GetSimpleAlgorithm(string key)
        {
            AesManaged aes = new AesManaged();
            byte[] source = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(key));

            byte[] take = new byte[aes.BlockSize / 8];
            for (int i = 0; i < aes.BlockSize / 8; i++)
            {
                take[i] = source[i];
            }

            return new AesManaged { Key = source, IV = take };
        }
    }}

```

## Unity C# script

This script tries to access the DLL.

```
using System;
using System.Runtime.InteropServices;
using DNDUtility;
using UnityEngine;
using System.Collections;

public class TestStuff : MonoBehaviour
{
    void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 100, 100), "Login"))
        {
            Debug.Log(DataManager.Login("username", "password"));
        }

        if (GUI.Button(new Rect(125, 0, 100, 100), "Get Characters"))
        {
            string[] chars = DataManager.GetChars();

            for (int i = 0; i < chars.Length; i++)
            {
                Debug.Log(chars[i]);
            }
        }
    }
}

```

You can find the ContentVaultServiceTest at this Pastebin.

## DNDUtility `App.config` code

```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="CustomBinding_IContentVaultService" maxReceivedMessageSize="200000000"
                    allowCookies="true">
                    <security mode="None" />
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://ioun.wizards.com/ContentVault.svc"
                binding="wsHttpBinding" bindingConfiguration="CustomBinding_IContentVaultService"
                contract="ContentService.IContentVaultService" name="CustomBinding_IContentVaultService" />
        </client>
    </system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

```

I've tried multiple different settings for the `contentClient`:

```
static string endpointConfigurationName = "CustomBinding_IContentVaultService";
        static EndpointAddress remoteAddress = new EndpointAddress("http://ioun.wizards.com/ContentVault.svc");
        static ContentVaultServiceClient contentClient = new ContentVaultServiceClient(endpointConfigurationName, remoteAddress);

static WSHttpBinding customBinding = new WSHttpBinding() { AllowCookies = true, MaxReceivedMessageSize = 200000000, Name = "CustomBinding_IContentVaultService" };
        static EndpointAddress remoteAddress = new EndpointAddress("http://ioun.wizards.com/ContentVault.svc");
        static ContentVaultServiceClient contentClient = new ContentVaultServiceClient(customBinding, remoteAddress);

```

When used in an external project without an `App.config` (using the first solution) I get this error:

```
Exception:Thrown: "Could not find endpoint element with name 'CustomBinding_IContentVaultService' and contract 'ContentService.IContentVaultService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element." (System.InvalidOperationException)
A System.InvalidOperationException was thrown: "Could not find endpoint element with name 'CustomBinding_IContentVaultService' and contract 'ContentService.IContentVaultService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element."
Time: 4/13/2014 2:07:22 PM
Thread:<No Name>[7520]

```

Using the second solution, I get:

```
Exception:Caught: "Secure channel cannot be opened because security negotiation with the remote endpoint has failed. This may be due to absent or incorrectly specified EndpointIdentity in the EndpointAddress used to create the channel. Please verify the EndpointIdentity specified or implied by the EndpointAddress correctly identifies the remote endpoint. " (System.ServiceModel.Security.SecurityNegotiationException)
A System.ServiceModel.Security.SecurityNegotiationException was caught: "Secure channel cannot be opened because security negotiation with the remote endpoint has failed. This may be due to absent or incorrectly specified EndpointIdentity in the EndpointAddress used to create the channel. Please verify the EndpointIdentity specified or implied by the EndpointAddress correctly identifies the remote endpoint. "
Time: 4/13/2014 2:35:38 PM
Thread:<No Name>[1356]

```

What should I set the `EndpointIdentity` to?

# Answer
> 1 votes
It looks like the endpoint configuration in your app.config is missing in Unity. The exception points to the "ctor" or constructor. The fact that it errors on the "InvalidOperationException: Client endpoint configuration '\*' was not found in 0 endpoints." makes me believe that it cant find the configuration for that endpoint. It probably needs that, so that it can make the secure connection.

So, if it were a problem I needed to solve, i would start by looking at how to use the configuration in the app.config file, in my unity project.

This exception doesnt relate directly to the fact that the dll is compiled against the wrong .NET version, it relates to the configuration of the endpoint only.

EDIT:

if you look at the instancing of the contentClient:

public class DataManager { static ContentVaultServiceClient contentClient = new ContentVaultServiceClient();

you're simply calling the default constructor, but, the class has several constructors of choice, namely:

```
    public ContentVaultServiceClient(string endpointConfigurationName)
    public ContentVaultServiceClient(string endpointConfigurationName, string remoteAddress)
    public ContentVaultServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress)
    public ContentVaultServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)

```

so, you could ignore the requirement for an app.config, and simply pass in a string for the configurationname and endpoint, such as an endpoint written as eg: "http......". Im not sure how the configurationname should be written, you will need to look at that within your app.config and paste it as a string:

```
    string endpointConfigurationName = "someEndpointConfigurationName";
    string remoteAddress = "http......";
    static ContentVaultServiceClient contentClient = new ContentVaultServiceClient(endpointConfigurationName, remoteAddress);

```

EDIT 2:

It looks like the ContentVaultServiceClient is implementing the IContentVaultService, therefore we could write something like:

```
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://ioun.wizards.com/ContentVault.svc");

ContentVaultServiceClient contentClient = new ContentVaultServiceClient(binding, address);

```

If we look inside the ContentVaultServiceClient class, we can see a constructor that accepts both binding and endpointaddress parameters:

```
public ContentVaultServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
                base(binding, remoteAddress) {
        }

```

I would like to say that the errors you are getting have now changed from the first post you made, which highlights now the fact that it is becoming a service configuration problem in .NET now, and no longer an issue with trying to get DLLs working in Unity.

I would strongly suggest that this question is not drawn out any more, as it deviates from the original question too much, and might confuse readers in the future.

You're more than welcome to contact me directly on Skype, at coombes.jason, where I will help you further if you need.

---
Tags: c#, unity, dll, exceptions
---


# Question
Title: Is any data structure more efficient than quad-tree for storing and querying points that lay within an OBB?
Is there any method more effective than quad-trees for storing and searching sets of points that are not spread uniformly on the plane?

I need to be able to add, remove and search for points that are within a specified range.

I am currently testing with quad-tree but it seems the results are less than optimal when the points are not spread uniformly enough.

The points are mostly clustered in specific areas:

# Answer
You might want to give R-trees a try. They are similar to quad-trees in that they subdivide the plane recursively; however, unlike quad-trees, they do not necessarily split up each sub-plane into equally sized, non-overlapping quarters. Instead, sub-partitions are flexible in position and size.

From wikipedia:

> The key idea of the data structure is to group nearby objects and represent them with their minimum bounding rectangle in the next higher level of the tree; the "R" in R-tree is for rectangle. Since all objects lie within this bounding rectangle, a query that does not intersect the bounding rectangle also cannot intersect any of the contained objects. At the leaf level, each rectangle describes a single object; at higher levels the aggregation of an increasing number of objects. This can also be seen as an increasingly coarse approximation of the data set.
> 3 votes

# Answer
Another similar and useful data structure is the kd-tree. It divides the k dimensional space by spiting it recursively much like an R-tree. Some differences are described here:

https://stackoverflow.com/questions/4326332/could-anyone-tell-me-whats-the-difference-between-kd-tree-and-r-tree

An important difference is that some say kd-trees are hard to balance. They are probably not suitable when you need to make changes. They are useful for making lots of queries.
> 1 votes

---
Tags: data-structure, search, point-cloud
---


title: Surface normal to screen angle

text:
# Question
Title: Surface normal to screen angle
I've been struggling to get this working. I simply wish to take a surface normal and convert it to a screen angle.

As an example, assuming we're working with the highlighted surface on the sphere below, where the arrow is the normal, the 2D angle would obviously be PI/4 radians.

Here's one of the many things I've tried to no avail:

```
float4 A = v.vertex;
float4 B = v.vertex + float4(v.normal, 0.0);

A = mul(MVP, A);
B = mul(MVP, B);

A.xy /= A.w;
B.xy /= B.w;

o.theta = atan2(B.y - A.y, B.x - A.x);

```

I'm finally at my wit's end. Thanks for any and all help.

# Answer
This depends on your camera. So if the camera is directly facing the object, you can do this. The surface normal is lets say (x,y,z). z meaning the depth. Then just make z = 0, as if you are projecting it in to plane. Then angle is simply atan2(y,x). This is for the simplest case though. IF the camera is not aligned with the object then you have to figure out a more complex projection.
> 1 votes

---
Tags: mathematics, shaders, vertex, normals, angles
---


# Question
Title: What does the Particle engine do and how are special effects created/processed?
For example, take bullets, sparks, fireballs, light sabers, lightning bolts, any kind of special effect in a game.

Are there various ways to implement these effects in a game. As far as I can see you create either an animation is some modelling package like Maya and then load these animations, you also seem to be able to do these kind of effects using layer upon layer of textures(images).

So where does the particle engine come in in a game, what is the relationship with pre-made animations.

Lets say I wanted to have some custom effect like the player could have a Thor like hammer and smash it on the ground as special power. Now when it hits the ground, everything rumbles and bolts of lightning appear from the hammer which propagate in a every increasing circular motion away from the hammer, like a circular lightning bolt and eventual fade away.

What options do I have to create a special effects like this, is it mainly done in animation software or mainly done in the engines code.

# Answer
Particle effects which are procedurally calculated by the game engine have the advantage that they can interact with the world:

* Particles which collide with objects can either bounce off or disappear. A precalculated animation would just pass through any obstacles
* Particles emitted by a moving object can stay where they are while the object moves on. This can often look pretty good. A precalculated animation can only be moved as a whole.
* Particle effects can interact with 3d models. Imagine your game allows to set objects on fire. You could visualize this on-fire status by spawning fire particles from the whole surface of the model. A prerendered effect would have to be done separately for every single model. When the model is animated, you also need to do the fire-effect for every animation-phase. You would practically have to do every object twice - a normal version and an on-fire version. but a procedural effect could just calculate the model surface at runtime, which means it can be applied to any model in the game without any additional work.

Let's take your hammer-effect, for example. You want lightning-bolts which propagate over the ground. You could make these lightning bolts in a 3d animation program. That would likely be a much more comfortable workflow and allow you to do it a lot more resource-friendly. But what if the hammer strikes somewhere where the ground isn't perfectly flat? OK, when it's on a slope, you can just rotate the animation. But what if the ground is uneven? A prerendered effect can not adapt to that. Some bolts would be above or below ground, which might look strange. Also imagine what would happen when the hammer would hit near a wall? The bolts would pass right through the wall and appear on the other side. That would also seem quite glitchy.

A better solution would be to use a particle-engine and make the effect procedural. That way you can have the particles which represent the edges of the bolts check their surronding and have them travel along surfaces. They would then travel organically over uneven ground and up walls.
> 2 votes

# Answer
Perhaps, some custom animation will require a bit of coding. Usually, particles in engines are physically simulated instances. Wıth this option you have more control over your particles as particles are now dynamic entities that you have direct control over.
> 0 votes

---
Tags: c++, animation, maya, special-effects
---


# Question
Title: Best practice for handling "dead" objects and their particles
I'm developing a side-scrolling run'n'gun game (but with planes! :P). I'm an experienced coder, but new to game development.

When an enemy plane collides with a friendly missile, I start an explosion particle emitter on the enemy plane. The emitter is accessible as a private property of the plane object and its flow is controlled by the plane's update function (which is called from the game update function). The particle emitter's "render-update" method is called directly from the game renderer class.

I don't like these things:

* When the enemy plane is destroyed, I can't simply remove the object from my game's "enemyPlanes" array, as this would result in the particle sequence not completing itself.
* If I continue with this scheme, I have a very complex if statement in every execution of the render function, that will (a) check if the enemy is not shot down (b) check if the emitter is active (c) remove the plane as well as the emitter (if both previous conditions are met)
* The particle system is both accessed from the GameRenderer and from the plane object. I mean, I call something like `plane.getParticleEmitter().update(blabla)`.

Is there a better way to do this?

EDIT: The library I'm using is libgdx (Java).

# Answer
> 4 votes
The particles themselves associated with a particular effect shouldn't be tied directly to the object. While there is never a 100% use-case scenario, this still applies to most situations. Your object itself shouldn't be managing the life-cycle of a particle effect, though it may be the instigator for spawning particular effects in the world.

So, in your situation you have an object (a plane) that is constantly emitting a particular particle effect via an attached emitter object. In this situation, the only thing that should be dependent on the plane object being alive is whether or not your emitter object would choose to spawn particles as a part of an effect sequence during that frame.

For example, say this is your code. (Lets assume your real code is more thorough than these extremely lacking implementations)

```
class Plane : public Actor
{
public:
   Plane();
   ~Plane();

   void Update()
   {
       ParticleEmitter.Update();
   }

   bool IsAlive()
   {
       //return whether alive or not
   }

private:
   EmitterClass ParticleEmitter;
}

class EmitterClass
{
public:
   EmitterClass();
   ~EmitterClass();

   void Update()
   {
      if( ShouldSpawnEffect() )
      {
          //Tell particle system to spawn effects
      }
   }

   bool ShouldSpawnEffect()
   {
      return Parent->IsAlive();
   }

private:
   Actor* Parent;
}

```

In this situation, the particle emitter is responsible for spawning the effects by itself, but is not responsible for managing the individual particles. A separate system would perform any allocations, and behavior updates for the effects queued up. This decouples your effects from the object itself, and allows for a singular system to manage the resources associated with a potentially complex and expensive system.

*edit* A final thought is that this isn't necessarily the "Best practice", as the implementation that is best for you is entirely dependent on your context specifics. Therefore, the reality is that there is no such thing as a universal best practice. Hopefully this helps.

# Answer
> 0 votes
A small hack would be to set enemy to not visible on collision, and when the explosion finishes then remove it. But then you need to have a callback that is triggered when explosion finishes.

---
Tags: architecture, libgdx, particles
---


# Question
Title: How to make game menu in Unity using only the editor?
I am trying to implement a game menu screen in which all the levels are locked initially. Just like Angry Birds. When user scores he'll be promoted the level unlocks.

# Answer
You can't. Unity doesn't have an interface for creating GUI interfaces in the editor. Further, there may be extensions for this in the Unity marketplace, but it's highly unlikely you'll be able to get away from any coding at all. There's still going to be the requirement to connect the GUI to your game, and many of those interactions are going to require scripts to trigger events in your game, or alter the game state.

Your goal of using the Editor only to make anything more than the most simple game is unrealistic. You'll have to code.
> 3 votes

---
Tags: unity, game-design
---


# Question
Title: How big a transition from programmer to modeler/level designer/creator
So I think I may take a break from the programming side, I have put in 6 hard months learning C++ and graphics theory, I have learned a huge amount but over the last few days have been studying level design and modeling and think that is maybe more suitable to me.

So how would programming compare in a learning curve sense, C++ takes a while to grasp the core language never mind writing 100,000s lines of game engine code which you would eventually have to do.

Without being arrogant the modeling/level creation side seems a much faster progression, is that a fair thing to say?

# Answer
Level design is not easier. You may not need a less deep and thorough understanding of each involved topic, but there is much more topics to reckon with.

Roughly you must have notions in : sculpting, animating, drawing, programming, geometry, esthetics(part of philosophy), applied psychology, artificial intelligence (don't forget the NPCs), architecture and so much more !

If you are a total noob in everything but programming, this will be a huge gap. The good point is that you can also learn it. There are many books and websites to help you there. Also, most topic relevant to game design can be applied to level design and most books about game design discuss level design at some point.

With level design you will soon have to start learning so many things in parallel. I'm not trying to discourage you though; it is not more difficult than programming either—it mostly depends on your character. Programming is not smaller either, there so many interesting topics to solve in programming. In the end, know yourself !
> 2 votes

---
Tags: c++, animation, models, level-design
---


title: Drawing Lines on android with matrix

text:
# Question
Title: Drawing Lines on android with matrix
Can a matrix be used when drawing lines and paths on android?

the DrawBitmap mathod takes a matrix as argument, I cannot find anything similar when drawing lines.

# Answer
The Android Canvas drawBitmap method uses the matrix to transform the image as it is drawn. See this URL for the details: http://developer.android.com/reference/android/graphics/Canvas.html#drawBitmap
(android.graphics.Bitmap, android.graphics.Matrix, android.graphics.Paint)

There are several drawLine methods on the Canvas object, but none take a matrix as a parameter. See http://developer.android.com/reference/android/graphics/Canvas.html#drawLine
(float, float, float, float, android.graphics.Paint)

Your best bet is to use one of the Canvas's rotate, skew, and translate methods. See http://developer.android.com/reference/android/graphics/Canvas.html
> 1 votes

# Answer
I finally figured out how to use a matrix to do transformation on lines in Android.

It's a little roundabout but hope it helps someone.

The following code is to rotate a line around it's center.

```
// coordinates of line (x1,y1) to (x2,y2)
float x1,y1,x2,y2;

// get the center of the line
float centerX = Math.abs((x1+x2)/2);
float centerY = Math.abs(y1+y2)/2;

// set the angle
double angle = 90;

// put the lines in an array
float[] linePts = new float[] {x1, y1, x2, y2};

// create the matrix
Matrix rotateMat = new Matrix();

// rotate the matrix around the center
rotateMat.setRotate((float) angle, centerX, centerY);
rotateMat.mapPoints(linePts);

// draw the line
mcanvas.drawLine(linePts [0], linePts [1], linePts [2], linePts [3], mPaint);

```

Hope this helps.
> 2 votes

---
Tags: java, android
---


# Question
Title: Direct3D: should I use MIXED_VERTEXPROCESSING?
Yesterday on Youtube I watched a video tutorial about creating Direct3D stuff. On that tutorial there was a part about `VERTEXPROCESSING` compatibility with older video cards. The guy said that the compatibility can be checked by this code:

```
D3DDISPLAYMODE         d3ddm;
D3DPRESENT_PARAMETERS  d3dp;
D3DCAPS9               d3dc;
int VP;

d3d->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dc);
if (d3dc.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
    VP = D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
    VP = D3DCREATE_SOFTWARE_VERTEXPROCESSING;

//and then:
d3d->CreateDevice(D3DADAPTER_DEFAULT,
                  D3DDEVTYPE_HAL,
                  dxhwnd,
                  VP,
                  &d3dp,
                  &d3ddev);

```

But hey OpenGL does this stuff automatically so there must be a way to achieve that easier. So today I found that this can be done by `D3DCREATE_MIXED_VERTEXPROCESSING`. But on some forums I have read that some (most older) video cards can have problems with this mode. So is there any reason why should I or shouldn't use Mixed Vertex Processing instead of using them both but with `D3DDEVCAPS`?

# Answer
> 4 votes
Video cards without hardware T&L are dinosaurs. Seriously, there haven't been any new cards without hardware T&L since about 2000. Forget about them, just use hardware vertex processing and assume it's supported - unless you *specifically* need to support 14-year-old cards for some reason.

---
Tags: directx, rendering, vertex
---


# Question
Title: OpenGL 2.0 - Texture animation with 'pixelated' effect
I'm looking for a way to reproduce the effect I've tried to sketch in the image below with OpenGL ES 2.0.

The idea is to let a drop of color fall over a cube which get filled with a kind of 'pixelated' effect.

Could you figure out any feasible solution to achieve it?

Thanks for any hint!

DAN

*** EDIT WITH SOLUTION ***

Achieving good looking results with a procedural texture generated in real-time is quite hard. Here's a few screenshots taken from an implementation based on Nathan's idea, where the mask has been created by hand. Cheers!

# Answer
> 7 votes
It's easy to produce an effect like this in a pixel shader, using threshold animation. The idea is that you have a monochrome texture and apply a threshold value to it; wherever the texture is lower than the threshold, the material is colored, and where the texture is higher than the threshold the material is blank. You animate the threshold value from 0 to 1 (or some other stopping value) over time, which causes the colored area to grow.

The pattern in the texture controls what the growth looks like. You'd want a radial gradient that goes from black at the point where the drop hits, toward white in farther away areas. Then the color would grow out of the hit point in all directions. Add some noise to the texture and you can make the growth lumpy, so that it doesn't just form a perfect circle. If the texture is low-resolution and you use point sampling, you'll get the pixellated effect.

You can also generate the texture procedurally in real-time if desired, for instance by combining a radial gradient computed from the runtime drop hit point with a section of a pre-generated noise texture. That would allow you to have drops hit at different points without needing different textures.

---
Tags: textures, shaders, opengl-es
---


# Question
Title: How can I customize the DefaultInput.ini?
I need to make some bindings false. The ones are: .Bindings=(Name="W", Command="GBA\_MoveForward") and the same for S, A, D, LEFT, RIGHT, and LeftControl.

# Answer
> 1 votes
If I recall correctly, there's a hierarchy of configuration files in UDK.

At the lowest level you have BaseInput.ini, then DefaultInput.ini, and above all UDKInput.ini. Each configuration file adds/removes/overrides values of the one below with the following syntax:

```
+Something // adds a value to an array
-Something // removes a value from an array
.Something // overrides a value in an array

```

So in your case, if you really just want to disable a binding, you could do the following in UDKInput.ini:

```
-Bindings=(Name="W", Command="GBA_MoveForward")

```

---
Tags: udk
---


title: Game loop in Javascript

text:
# Question
Title: Game loop in Javascript
I've been into javascript game programming with html5 and canvas lately. So far I've only been able to implement a game loop with setInterval, but I'm aware this means using fixed timestep. I've always used game engines with the "delta time" approach, I'm sorry I can't recall how that timestep was called. But anyway, I had several questions.

* How could I implement a game loop with the delta time approach?
* Will I get benefit from it in any particular way?

Also any information you point out related to that is welcome.

# Answer
Basically you have three ways to periodically invoke some code.

* have a infinite loop with sleeps.
* use setIntervall to perodically be waken
* use requestAnimationFrame for when the browser is idle

Although this is about animation, it covers the basic crux of the problem: Animating In Code Using JavaScript
> 3 votes

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


title: Variable Jump in Unity3d

text:
# Question
Title: Variable Jump in Unity3d
I implemented variable jumping in unity for an endless running game. My question, how can I make the jump frame rate independent?

My algorithm

```
if ( keyDown ){
isJumping = true
ySpeed += jumpStep*Time.deltaTime;
if( ySpeed > maxJumpHeight )
    ySpeed = maxJumpHeight;
   //JUMP OVER
}
// Apply gravity
ySpeed -= ( currentGravity * Time.deltaTime ) ;
// set position
playerSprite.transform.localPosition = new Vector3(0,currentPos.y+ySpeed,0);

```

This varies on different devices, What I am trying to do that, whatever the device is, the jump should always be the same on a given time.

What if i do this in FixedUpdate? Will it work fine?

# Answer
> 1 votes
* You **shouldn't** multiply `jumpStep` by `Time.deltaTime`. It should always be the same value, regardless of frame rate.
* You **should** multiply `currentGravity` by `Time.deltatime`.
* In the last part, you should do `currentPos.y + ySpeed * Time.deltaTime`, When you use speed to compute movement, you need to multiply speed by time.

That is because jumping is an impulse and gravity a force. Impulses happen in an infinitely small time frame. Forces act over time.

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


title: Libgdx stage rendering issues

text:
# Question
Title: Libgdx stage rendering issues
I'm using scene2d for the first time, and I can't get anything to draw EXCEPT the stage ui. Say I have my ui on top of my game screen:

```
uiStage.act():
batch.begin();
gameSprite.draw(batch); //does not show up
uiStage.draw();
batch.end();

```

How can I render my game, and then render my gui stage on top? Should I use a stage for both the game and the ui?

# Answer
You should render stuff consecutively. Mixing up the rendering of your batch and that of the stage is not the way to do it. Especially if to consider that I am almost convinced the batch you are showing in your code and that used by the stage are two different objects.

Change your code as follows:

```
batch.begin();
gameSprite.draw(batch);
batch.end();

uiStage.act();
uiStage.draw();

```

I also highly recommend that you watch dermetfan's (Robin S.) beginner tutorial on libGDX, he makes use of scene2d in his episodes and provides very nice explanation and illustration of how to work with it properly. Just watch them all, starting with this one Java Game Development (LibGDX) | Episode 1.

Hope this helps you.
> 2 votes

---
Tags: java, libgdx, gui
---


# Question
Title: How can I determine which square in my memory game was pressed?
I want to develop an simple memory game on Android.

The memory game have squares like the picture below. How should I determine which of the square is pressed? Should I use image buttons? Personally I don't think it is an good idea to make the game with image buttons. Could you suggest me an solution on how I should determine which of the square is pressed?

# Answer
Here is an idea:

you probably know of the dimensions of the screen, you know of the resolution of the squares, and at any time when a point on the screen is touched, you know this points x and y coordinates.

```
int xSquare = floor(x/squareResolution)
int ySquare = floor(y/squareResolution)

```

If you store all your squares in a one dimensional array, the square you want is

```
squares = new Square[gridResolution*gridResolution];
theSquareYouWant = squares[ySquare *gridResolution + xSquare]

```

If you store it in a 2d array you want square

```
squares = new Square[gridResolution][gridResolution];
theSquareYouWant = squares[xSquare][ySquare]

```

You should not use image buttons. If you want to animate a square being pressed, create an animated sprite or whatever at the space occupied by the square and then remove it once the animation has finished.
> 0 votes

---
Tags: java, android
---


title: FPS camera specification

text:
# Question
Title: FPS camera specification
I remember I once composed a FPS viewing transformation, as a composition of 3 rotations, each with an angle as a parameter. The first angle specified the left/right rotation around the y-axis, the second angle the up/down rotation around the x-axis, and the third around the z-axis. The viewing transformation was therefore specified by 3 angles. Naturally, this transformation had a gimbal lock, depending in what order the transformation were performed. What should I look at to derive my viewing transformation without the gimbal lock? I know the "lookAt" method already, but I consider that cumbersome.

EDIT:

MY first guess is to do the first 2 transformations to get a viewing direction and then the `axis-angle` rotation on this axis.

# Answer
I honestly do not get this FPS/Arcball/Whatever camera nonsense that is going on. Just implement a general purpose camera, with either a transformation as 4x4 matrix or a position as R3 vector and orientation as a 3x3 matrix or quaternion. Then think about how that camera is moving though space.

For example I have implemented a general purpose camera with a a 4x4 matrix. The view matrix setup is straight forward:

```
mat4 transform;

// get column vectors x, y, z from transform
vec3 x = transform[0];
vec3 y = transform[1];
vec3 z = transform[2];

// set x, y, z as inverse into the matrix
// NOTE: column and rows are swapped
mat4 orientation(x[0], y[0], z[0], 0,
                 x[1], y[1], z[1], 0,
                 x[2], y[2], z[2], 0,
                    0,    0,    0, 1);

vec3 p = transform[3];

mat4 translation(    1,     0,     0, 0,
                     0,     1,     0, 0,
                     0,     0,     1, 0,
                 -p[0], -p[1], -p[2], 1);

mat4 view = orientation * translation;

```

See no need to pass the anything though lookat or whatever. BTW the code is basically what lookat does, except it needs to compute `x`, `y` and `z` form `eye`, `center` and `up` and `p` is `eye`.

Now to the FPS part. The actual logic is a bit more complicated since you need to collide something, like a capsule with the world, but I will outline the basics with the help of "fyling".

The basic jest is you handle the rotation as follows:

```
// assuming (0, 0, 1) is up and (1, 0, 0) is forward
float x, y; // mouse input

// NOTE: again columns and rows are swapped in code
mat4 yaw( cos(x), sin(x), 0, 0,
         -sin(x), cos(x), 0, 0,
               0,      0, 1, 0,
               0,      0, 0, 1);

mat4 pitch( cos(y), 0, -sin(y), 0,
                 0, 1,       0, 0,
            sin(y), 0,  cos(y), 0,
                 0, 0,       0, 1);

transform = transform * pitch * yaw;

```

The motion is similar:

```
// only forward

float speed;
float dt; // time difference since last frame

float ds = speed * dt;
mat4 translate( 1, 0,  0, 0,
                0, 1,  0, 0,
                0, 0,  1, 0,
               ds, 0,  0, 1);

transform = transform * translate;

```

If you need answers how to handle transformations the Matrix and Quaternion FAQ is always very helpfull.
> 3 votes

# Answer
I'm using this transform:

```
x' = [cos(phi), 0, sin(phi)]
y' = [-sin(phi)sin(theta),cos(theta),cos(phi)sin(theta)]
z' = [-sin(phi)cos(theta),-sin(theta),cos(phi)cos(theta)]

```

Where `phi` is the angle of rotation around the y axis, `theta` the angle of rotation around the x axis and `alpha` the angle of rotation around the z' (transformed) axis. Write these expressions into rows and you've got yourself a transformation matrix. The third parameter alpha (rotation around the z' axis), can be handled like this:

```
x'' = x'cos(alpha) - y'sin(alpha)
y'' = x'sin(alpha) + y'cos(alpha)
z'' = z'

```

Where `x'`, `y'` and `z'` are vectors. No gimbal lock as far as I can see.
> -1 votes

---
Tags: camera
---


title: Sprite/Tile Sheets Vs Single Textures

text:
# Question
Title: Sprite/Tile Sheets Vs Single Textures
I'm making a race circuit which is constructed using various textures.

To provide some background, I'm writing it in C++ and creating quads with OpenGL to which I assign a loaded .raw texture too. Currently I use 23 `500px x 500px` textures of which are all loaded and freed individually.

I have now combined them all into a single sprite/tile sheet making it `3000 x 2000` pixels seems the number of textures/tiles I'm using is increasing.

Now I'm wondering if it's more efficient to load them individually or write extra code to extract a certain tile from the sheet?

Is it better to load the sheet, then extract 23 tiles and store them from one sheet, or load the sheet each time and crop it to the correct tile?

There seems to be a number of way to implement it...

Thanks in advance.

# Answer
> 1 votes
Neither. You want to load a single tile sheet once and load that single texture into the GPU with no cropping or copying.

It's most efficient to actually draw from the tile sheet by figuring out the correct UV coordinates for a sprite in the sheet and then passing those to your draw commands. Individual textures should be avoided if you can, at least for small sprites and frequently-used textures.

You want to avoid any excess state switches and minimize draw calls. This means that you ideally want to only bind a single texture (the one sprite sheet) instead of many individual textures. It also means you ideally want to submit a single draw call (maybe an instanced call) for all your game objects that just use that single texture, instead of needing a separate draw call for each individual sprite (or worse, each individual object). Actually achieving a single state and a single draw call becomes impossible as your game gets more complex, but you want to keep the numbers as low as possible.

You only want to bind the texture once, since it'll be the same spritesheet texture for all sprites. The rest is figuring out the correct UVs. If sprite metadata says that some 500x500 image is located at position (1500,500) within a 3000x3000 spritesheet, then you know that the opposite corners are at (1500,500) and (2000,1000). Divide those by the sprite sheet dimensions to get the normalized UV coordinates, (1/2,1/6) and (2/3,1/3). When you draw the object, use those UVs (and extrapolate to get the other two corners). Ideally, you don't want to draw each object but rather fill a dynamic buffer with position and texcoord information and then draw all your objects (maybe with instancing) using a single draw call sourcing that dynamic buffer.

---
Tags: textures, sprites
---


# Question
Title: Can you adjust the proportions of a 3D model via scripting?
We are developing a game in Unity where the character is different ages in different levels. Would it be possible to use a single 3D model asset, and alter its proportions via scripting to achieve this effect? For example, stretching the head to make it more oval for older self, or increasing head size for toddler self?

We don't have a model yet. We are envisaging a simplistic, cartoony look rather than something realistic. Is this doable?

# Answer
Unity has the **scale** component in every transform. You can then scale the x,y,z of the model. So in theory if you have a model with separated body structure so that arms, legs and head are all individual `GameObjects` you can scale them individually.
> 3 votes

# Answer
Scale in script:

gameObject.transform.localScale = new Vector3(2,2,2);

in the numbers you set the scale to each axis of your gameObject.

edit: like Esa say you need to do this in each part of your model, but you can make it in a bone of skeleton of animation that create the effect you need.
> 0 votes

---
Tags: unity, 3d, models
---


# Question
Title: OpenGL - How to draw a transition of two textures on one quad?
I know when drawing a rectangle, if we select red and draw two vertices, and then select yellow and draw the other two vertices, the entire rectangle will show a nice transition of color between those vertices and the middle of the rectangle will appear orange.

Suppose I have two textures, and I want to do the same kind of thing. On one rectangle, I want two vertices to use texture from one image and the other vertices to use the texture from the other image, and show a smooth transition in the middle.

Please show me how this can be done in OpenGL, thanks!

# Answer
This is possible using GL 1.x and here's how.

So as you've found using vertex colors, a smooth transition is where it blends the two colors. This is a called a linear interpolation, or a "lerp" for short. It can be generalized to any dimension by operating on the elements of the vector individually and indeed colors are treated like a lerp in 3D -- blend R1 with R2, G1 with G2, B1 with B2.

The lerp() function has an "alpha" parameter, such that alpha = 0.0 yields fully color 1 and alpha of 1.0 yields fully color 2, and somewhere in-between creates a mixture. So you'll see then that if you have color 1 (C1) and color 2 (C2) and some alpha value (A), then would do it as: `lerp(C1,C2,A) = A*C1 + (1.0-A)*C2`. As many people will tell you, you can simplify this formula, but keeping it as is will help you understand how to do this with GL 1.x.

To do this with two textures using GL 1.x, you will be drawing two rectangles on top of each other, one with texture 1, one with texture 2. However, you will be adding the two colors. If you do this as-is you'll end up with a final texture that looks like

`final = C1 + C2`

If you look at the lerp() function, you'll see that we're missing the multiplication by `A` and `1.0-A`. So to do this, we're going to using colors.

In OpenGL 1.x, the default way that colors and textures are combined is like so:

`C' = Ccolor * Ctexel`

This is done by `glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_TEXTURE_ENV_MODE)`. Again, this is the default mode, so you shouldn't need to do this.

If we specify a color of { 1, 1, 1, 1} (pure white) on side of the rectangle in the vertex data, and then { 1, 1, , 0} (transparent) on the other side, the colors will be smoothly interpolated by OpenGL as you've already noticed. Generalize that to alpha, which isn't "visible" per se, but can be used in graphics techniques such as this. So in effect, you'll end up with the alpha value of the color varying from 0..1 smoothly as desired. Now we have to use this value. Simply having the alpha value varying across the rectangle doesn't do anything, because alpha itself is not visible like red, green, or blue. So we have to somehow multiply this alpha value with each color.

Enter blending. Blending in the GL 1.x fixed function does just that. It takes the incoming pixel (call the source) and blends it with the destination pixel (i.e. what is already in the framebuffer) by some function, so you can look at mathematically as: `Cblended = blend(Csrc, Cdest)`

First, you must enable it: `glEnable(GL_BLEND)`.

Then, you must give it the function `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)` for the first rectangle.

The first parameter to `glBlendFunc()` is what gets multiplied with the source color. We're saying the alpha value of the color. The second parameter is what is multiplied with whatever is already in the framebuffer. We're saying 1.0-alpha. This effectively means we're doing a lerp().

When drawing the second rectangle, you must give it the function `glBlendFunc(GL_SRC_ALPHA, GL_ONE)`. This preserves the previously calculated value (GL\_ONE meaning multiply old value by 1.0) and then blends the incoming (new rectangle) value by its alpha, performing the lerp().

Let's go other all of this, mostly so you can appreciate shaders.

1. Enable blending, possibly set up texture environment.
2. Set up the blending function
3. Draw rectangle 1 with left vertices having alpha of 1, right side alpha of 0
4. Switch blend function to GL\_SRC\_ALPHA / GL\_ONE (thanks Trevor)
5. Draw rectangle 2 with right vertices having alpha of 1, left side alpha of 0
6. Turn off blending and do other stuff.

This works because:

1. When you specify vertex colors, the alpha value is smoothly interpolated across the rectangle.
2. Using blending, we can multiply the color by that alpha value
3. Since we swap 1.0/0.0 alpha values depending on which rectangle we're drawing, for each pixel where alpha is some value `K` for rectangle 1, it will be `1-K` for rectangle 2.
> 2 votes

# Answer
For the sake of easiness, use GLSL shaders. This is mandatory for modern openGL, anyway.

Now, what you have to do is to unwrap your object to each texture. So you must associate to each vertex *two* texture coordinates in your vertex shader. Plus, you may wish to add a \[0-1\] value X to each vertex that tells how much of the first and second texture you wish to use.

In the fragment shader, you can pick the color of both color, and alpha-blend them manually using X. Something like this (not tested) :

```
uniform gsampler2D texture1;
uniform gsampler2D texture2;
varying vec2 textureCoord1;
varying vec2 textureCoord2;
varying float thatMuchOfTexture2; //value X
void main(void)
{
    vec4 c1 = texture(texture1, textureCoord1.st);
    vec4 c2 = texture(texture2, textureCoord2.st);
    gl_FragColor = c1*(1-thatMuchOfTexture2) + c2*thatMuchOfTexture2
}

```
> 2 votes

# Answer
I do not believe that this is directly possible using OpenGL 1.x. If you're using OpenGL 1.3, you can use Texture Combiners to merge two textures together in various ways, and you can even specify different sets of texture coordinates for the two textures, but I do not believe it's possible to set different opacities for the different textures per vertex within a single draw.

Because of this, when coding to OpenGL 1.3, people generally use other, 'hacky' ways to achieve a similar effect.

The usual way to do it would be to draw the quad twice -- once using the first texture at full opacity, and then drawing the quad again using the second texture, but with vertex alpha set to fade out the second texture where you want the first one to show through.

Now, if you're using 3D, then this gets tricky, as the two draws will exactly overlap each other in the depth buffer. (If not, then ignore the rest of this answer)

In that tricky 3D situation, you probably want to have the first quad draw into a stencil buffer, to track which pixels it drew into on the screen, and then have the second draw disable its depth testing, and use that stencil buffer to clip which pixels it's allowed to draw into (so it doesn't draw on top of closer objects, with its depth testing disabled).

Alternately, you can use glPolygonOffset() to force the second quad draw to pretend to be slightly closer to the camera, so that it doesn't fight with the first one. This fix is simpler and easier, but is less predictable, as the parameters to glPolygonOffset() do not have standardised meanings, and may vary in their effect from platform to platform and from GPU to GPU.
> 1 votes

---
Tags: opengl, textures, transparency
---


# Question
Title: How can I reorient the axes of an object?
I spent some time in Unity yesterday trying to fire a sphere from a horizontal cylinder (like a ball from a cannon). I was using Vector3.forward, but the sphere kept coming out the top of the cylinder rather than the front. Someone suggested using Vector3.up instead, and sure enough it worked!

The cylinder is vertical by default. So, it appears that when I rotated the cylinder by 90 degrees to lay it flat, the local axes remained the same. The relative front of the cylinder remained at the same point, so when I fired the sphere it shot out the new "top", not what looked to me like the "front". If I had happened to be facing the other way, I would have had to fire at Vector3.down instead.

How can I reorient/reset the axes of an object so that they match my expectations? (And if I can't, how can I tell by looking which way an object is oriented?)

# Answer
> 5 votes
Click on the object in the scene, and look at the Rotation values in the Inspector. This will tell you which way the object is oriented in absolute terms.

If the orientation does not match your expected axis (for example, 90 degrees off, or using an unintuitive axis for a given direction), you cannot change the axis of the object itself. Instead, you can use a "parent transform" as follows:

Create an empty GameObject as a parent of your object, and align its transform with your model's expected axis. Now use the parent transform to reference and manipulate the child object.

# Answer
> 0 votes
Try using `transform.up` and `transform.right` instead of `Vector3`. Vector3 takes the world coordinates and transform.up takes into account the transform's orientation.

# Answer
> 0 votes
But if your model don't be modeled to get the axis z to front in the modeller program you can't arrange this in unity

---
Tags: unity, orientation, visualization
---


# Question
Title: How to improve the performance of my OpenGL rendering context?
I have written a benchmark program that compares the performance of OpenGL and DirectX libraries. The problem is that OpenGL gets much lower performance than Direct3D. At the end the program generates a comparison chart. You can look at it here:

As you can see the OpenGL performance is poor compared with Direct3D (I know that FPS's aren't the best method of measuring out there but that was my choise from the begining). Rendered object is a BIG CUBE made of smaller cubes. BIG CUBE passes certain states that are:

```
  COLOR
  COLOR + LIGHTS
  TEXTURE
  TEXTURE + LIGHTS
  WIRE
  TRANSPARENT

```

OpenGL context uses atioglxx.dll (AMD) and nvoglv32.dll (NVidia) for HW rendering. Now I will provide some code for better view of what and how I am doing things. First of all I'm creating a rendering context that is loaded on `WM_CREATE`:

```
GLvoid StartOpenGL(HWND hwnd, HDC * hdC, HGLRC * hrc)
{
  PIXELFORMATDESCRIPTOR pfd;
  int format;
  *hdC = GetDC(hwnd);

  ZeroMemory( &pfd, sizeof( pfd ) );
  pfd.nSize = sizeof( pfd );
  pfd.nVersion = 1;
  pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  pfd.iPixelType = PFD_TYPE_RGBA;
  pfd.cColorBits = 32;
  pfd.cDepthBits = 24;
  pfd.cStencilBits = 8;
  pfd.iLayerType = PFD_MAIN_PLANE;
  format = ChoosePixelFormat(*hdC, &pfd);
  SetPixelFormat(*hdC, format, &pfd);

  *hrc = wglCreateContext(*hdC);
  wglMakeCurrent(*hdC, *hrc);
}
// also these functions are called on WM_CREATE:
    ApplyTextures();  //load texture
    reshape();        // reshape
    LOADcubeGL();     // load VBO's (for full code check LINK2 on Blockquote)
    ACTIVATEcubeGL(); // activate VBO's (for full code check LINK2 on Blockquote)

```

Context is destroyed on `WM_DESTROY:`

```
GLvoid StopOpenGL(HWND hwnd, HDC hdC, HGLRC hrc)
{
    wglMakeCurrent( NULL, NULL );
    wglDeleteContext( hrc );
    ReleaseDC(hwnd, hdC);
}
// also these functions are called on WM_DESTROY:
KILLcubeGL(); // zero VBO's (for full code check LINK2 on Blockquote)

```

On `WINAPI WinMain` I do

```
animationGL(); // rotate the cube
init();        // inits GLlight
display();     // set view + transformation + rendering the cube object with glEnable(); glDisable(); states
SwapBuffers(hdC);

```

Here is the full code:

```
GLvoid LOADcubeGL(GLvoid){

        glGenBuffersARB         = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
        glBindBufferARB         = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB");
        glBufferDataARB             = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB");
        glBufferSubDataARB      = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB");
        glDeleteBuffersARB      = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB");
        glGetBufferParameterivARB   = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB");

        glGenBuffersARB(1, &gVerts);
        glBindBufferARB(GL_ARRAY_BUFFER_ARB, gVerts);
        glBufferDataARB(GL_ARRAY_BUFFER_ARB,
                        sizeof(vertices) + sizeof(normals) + sizeof(colors) + sizeof(texcoords),
                        0,
                        GL_STATIC_DRAW_ARB   );
        glBufferSubDataARB(GL_ARRAY_BUFFER_ARB,                0, sizeof(vertices),  vertices);
        glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, sizeof(vertices),  sizeof(normals),  normals);
        glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, sizeof(vertices) + sizeof(normals),  sizeof(colors), colors);
        glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, sizeof(vertices) + sizeof(normals) + sizeof(colors), sizeof(texcoords), texcoords);

        glGenBuffersARB(1, &gIndices);
        glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, gIndices);
        glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, sizeof(indices), indices, GL_STATIC_DRAW_ARB);
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    };

GLvoid ACTIVATEcubeGL(GLvoid){
        gVerts = 0;
        gIndices = 0;
        glBindBufferARB(GL_ARRAY_BUFFER_ARB, gVerts);
        glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, gIndices);
        glVertexPointer(3, GL_FLOAT, 0, vertices);
        glNormalPointer(GL_FLOAT, 0, normals);
        glColorPointer(4, GL_FLOAT, 0, colors);
        glTexCoordPointer(2, GL_FLOAT, 0, texcoords);
};

GLvoid KILLcubeGL(GLvoid){
        glDisableClientState(GL_COLOR_ARRAY);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        glDisableClientState(GL_NORMAL_ARRAY);
        glDisableClientState(GL_VERTEX_ARRAY);
        glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
        glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
        glDeleteBuffersARB(1, &gVerts);
        glDeleteBuffersARB(1, &gIndices);
        delete[] vertices;
        delete[] indices;
    };

```

The BIG CUBE is drawn in `display();` stage by:

```
glNewList(1, GL_COMPILE);
  glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(indices[0]), GL_UNSIGNED_BYTE, indices);
glEndList();

```

Now I know that mixing VBO's with display list may cause problems and moreover DirectX 9 doesn't have equivalent for display list but otherwise my OPENGL code runs even slower: at 20FPS! What I am doing wrong?

My DirectX calls look pretty same except that there is no rendering context like OpenGL have. I draw by `vertex_buffer->Lock` `index_buffer->Lock` and finaly `d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 36, 0, 12);`. My equivalent for OpenGL's `PIXELFORMATDESCRIPTOR` is:

```
d3dp.Windowed = TRUE;
d3dp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dp.hDeviceWindow = dxhwnd;
d3dp.BackBufferCount = 1;
d3dp.BackBufferFormat = d3ddm.Format;
d3dp.MultiSampleType = D3DMULTISAMPLE_NONE;  // in OpenGL I set that elsewhere than pfd
d3dp.MultiSampleQuality = 0;
d3dp.BackBufferWidth = width;
d3dp.BackBufferHeight = height;
d3dp.EnableAutoDepthStencil  = TRUE;
d3dp.AutoDepthStencilFormat  = D3DFMT_D24S8;
d3dp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
d3dp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // in OpenGL I use wglSwapIntervalEXT(0);

```

# Answer
> 1 votes
I can't read all of the source code (dang firewalls), but a display list is something that you compile once, then execute many times. What you're doing is telling OpenGL to regenerate an optimized execution list containing such and such triangle data *every frame*. That isn't what display lists were\* used for -- they originally were more for things like old SGI workstations that could literally compile OpenGL commands into GPU command buffers and execute them. Even if you were executing this code on an SGI machine, this would perform terribly because you're re-creating this display list!

Modern GPUs don't function like this. If your data is in a VBO, doing a display list means OpenGL must *read the data back* to create it. JUST SAY NO. Do a glDrawElements() and be done with it. Nothing fancy. As an aside, display lists are gone in later versions of GL, so definitely don't use them. It pretty much guarantees problems going forward.

* "were", as in, don't do it now! Ever! No! Nope!

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


# Question
Title: Xbox Controller Not Connecting in Monogame Project
I have recently been playing around with the support of the wired XBox 360 controller in Windows development. I am developing in C# in Visual Studio 2012.

I have created 2 projects. The first (Project A) is an XNA project compiled in .Net 4.0. The second (Project B) is a MonoGame 3.0 Windows Open GL project also compiled in .Net 4.0.

My issue is that my wired Xbox 360 controller can only be picked up in Project A - the XNA project. I would really like to continue working with the Monogame type, but have hit a brick wall here.

I have verified that all the requisite libraries (OpenTK, Tao.SDL, SDL) are the exact same files being referenced by both projects. Still, the Monogame project does not pick up the controller.

The exact state of the `GamePadState` variable is `Connected = false`.

Any ideas?

Again, same computer, same code for accessing the controller, only difference is XNA vs Monogame.

# Answer
I found myself that it is a bug of OpenGL version of Monogame. Just create DirectX version and it should work.

**Edit1:** Issue has been send to the tracker. https://monogame.codeplex.com/workitem/7812
> -1 votes

---
Tags: xna, opengl, monogame, xbox-controller
---


title: Slick2D: Resizing the Window

text:
# Question
Title: Slick2D: Resizing the Window
I am using Slick2D, and I wanted to know which is the best way to resize, maximize, minimize the window, For example, Resizing all the images or scaling them, or Slick2D has an integrated method, Any help is appreciated.

# Answer
If you want to resize your images, scaled to the window size, you will need to scale your Graphics object in your render method.

To do this properly, you will need to make your game with a predetermined resolution (kind of like, the starting resolution of your game, that all users would start with.) Lets say you are writing a game with the window size 640x480.

This would make your base resolution width 640, and your base resolution height 480.

In the top line of your render method, you would type:

```
graphics.scale(Display.getWidth()/baseWidth, Display.getHeight()/baseHeight);

```

and then you would just draw your images as you would normally.
> 0 votes

---
Tags: java, slick, window-management
---


title: Infinite 3D Cave in Unity

text:
# Question
Title: Infinite 3D Cave in Unity
A friend and I are hoping to make a game in Unity in which you fly through an infinite 3D cave that can twist and wind in any direction (though obviously not to the point that the turns are impossible to make). We were thinking about creating a number of tunnel "pieces" that each curve a certain amount, and spawning each at the end of the one that came before.

But we have no idea how to make sure that the mouth of one tunnel piece always aligns perfectly (in both position and rotation) with the end of the previous one. Can anyone offer any advice on how to accomplish this?

Are we even going about it in the right way, or is there a better way to procedurally generate the cave? Bonus points: It'd be awesome if the cave could change in diameter and/or shape as well, though that'd just be gravy.

# Answer
> 6 votes
There is rarely a "right way" or "wrong way" when it comes to game design. There are many, many ways to solve this problem, but here are a few possible approaches to explore:

* Constrain the tunnel pieces to both start and end only in certain directions; for instance only along the axes. Then you just have to keep track of the offset from the beginning to the end of a segment, along with enums describing the direction of movement at the start and end of the segment. This way you don't have to worry about rotating your tunnel meshes at all, as long as you always pick the next one such that it starts in the same direction the last one ended in.
* Make each segment start at the origin of its local model space with the tunnel traveling along a specific axis (+X, +Z, or -Z would be the most logical choices, but all of the models should use the same one), then store the position of the end of the tunnel and final direction of travel in some way so that the next mesh can be transformed correctly. (a transformation matrix is probably the easiest way to store this information, but you could also use a displacement vector + quaternion, dual quaternion, displacement + new basis vectors, displacement + euler angle rotations, etc.)
* Procedurally generate your cave by streaming new vertex data to a few meshes. You can do this using the `Mesh` class. When generating new vertex data, the easiest way is probably to pick a point somewhere in approximately the same direction as the previous cave segment, then let the center of the cave move toward that point. Then you can use cylindrical coordinates to procedurally create detail on the walls of the cave. Think of it as extruding out the end of a cylinder, then individually translating each vertex closer to or further from the center of that cylinder.

Any solution that uses premade segments will require you to make sure that all the meshes have the same shape and diameter around the center of the tunnel, but you can get around this somewhat by having the segments overlap to an extent, and have each segment flare out at the ends. If done right, it shouldn't be too obvious to the player that there's a seam.

On the other hand, if you go for entirely procedurally-generated geometry, you'll have more work to ensure that you don't generate sections that are impossible to traverse, and you might run into issues with collision detection.

Keep in mind, with any "infinite" game, you should be aware of the limitations of floating point representations. If the player gets too far from the world origin, it becomes easy to lose precision in floating point calculations (when two large values are subtracted from each other, for instance). To avoid this, you can make the world move around the player, rather than the player move through the world, but its usually easier to just check the player's position every so often, and if they're too far from the origin, rebuild the world with the player at or near the origin.

# Answer
> 3 votes
Here's a technique I experimented with recently. My RenderMonkey prototype shows a section of badlands-style canyon, but the same principle should work in caves.

The idea is to start with tiles that are generic, downright boring, with simple predictable edges so they're easy to line up without seams or gaps:

These starting tiles could be shapes you've modelled, or procedurally-generated macaroni tubes of cylintrical geometry (this form is a variant on bcrist's and Steven Stadnicki's suggestions). Using models you've created makes it easier to handle arbitrary topology like branching paths, or points of interest like open caverns. This is still possible with pure procedural (see Gyroninja's suggestion about metaball techniques), but challenging.

Once a tile is placed into the world, displace its vertices using noise functions applied in worldspace. This preserves connectivity and seamlessness between tiles (since coincident vertices have the same worldspace input, and get the same displacement output), but makes every tile look unique and organic:

Texture and normals are applied in worldspace too - here using triplanar mapping - so that adjacent tiles are completely seamless, without tricky UV unwrapping constraints.

The hope is that a technique like this gives you the ease of planning and level design control of a tiled map, without visible repetition or mechanical-looking structure in the playable result.

You can use a lower-res mesh with only the low-frequency noise components applied to create the collision representation. As bcrist notes, you'll need to control the maximum amplitude of the noise relative to the radius and sharpness of turns of the tunnel, to ensure it never pinches off completely.

One further note: if your cave really is infinite, you may need to "recenter" it periodically as the player moves further and further from the origin. Because floating point numbers lose precision at high magnitudes, physics and rendering artifacts can creep in at extreme distances. If you do this, you'll want your worldspace noise to be periodic over a large scale, with the period exactly matched to your recentering offset, so you don't encounter seams after recentering.

# Answer
> 2 votes
You could model your cave as a sequence of points, each with an associated size, with lines connecting them. Then treat each point and line as metaballs and metacylinders. This gives you a basic shape for your cave, to which you might want to start adding variation, such as by randomly offsetting vertices.

# Answer
> 2 votes
Here's another approach to procedural generation that hasn't been explicitly mentioned yet: spline skinning. You can use a version of Hermite Splines (which provide a curve interpolating positions and tangents) to define the curves: when it's time to generate a new segment, just choose a position (roughly in the direction of the previous segment, as bcrist says) and a direction (roughly in the same direction - e.g., within some well-defined cone of the previous direction), then use the new position+direction and your previous position+direction to build a new 'spine' for your cave. Once you have this backbone, you can skin it with a cylindrical construction: determine the positions and tangents of (for instance) 10 points along the curve, use those positions/tangents to find an orthogonal 'frame', and then use these frames to build cylindrical segments. One small caution with this is that the cave can't curve *too* much, or else you may run into self-intersection issues.

**EDIT:** Here's a rough pseudocode breakdown of the algorithm:

```
Parameters:
  L = (average) segment length,
  V = segment length variation,
  R = cylinder radius,
  T = segment angular variation
  S = number of 'rings' per segment

Setup:
Choose an initial point P_0 and direction D_0 (for concreteness' sake, these can be
the origin and the X axis).  Set P_prev and D_prev to these values.
Initialize u_prev to be the Y axis and v_prev to be the Y and Z axes.
  (Note that (D_prev, u_prev, v_prev) form a mutually-orthogonal 'coordinate frame')

Generate a segment (do this as many times as you want):
{
  Choose a (temporary) direction D within a cone of size T around the previous direction D_prev
  Choose a segment length L_cur = at random from within the range [L-V, L+V].
  Set the current terminal point P_cur to P_prev+D*L_cur - this is the position
  we'll interpolate to
  Set the current terminal direction D_cur to a direction chosen at random from
  within a cone of size T around the previous direction.  (There are good ways
  of doing this - if you look back through gamedev.SE you should find some)
  'Build' the Hermite spline H that goes from (P_prev, D_prev) to (P_cur, D_cur)

  Now, skin that spline:
  for ( i = 1; i <= S; i++ ) {
    find the position P of the hermite spline H at t=i/S
    find the direction D of the spline at t (this will be just the derivative)
    'transport' the orthogonal frame to the new spot: for instance,
      v_new = D x u_prev
      u_new = v_new x D
    (note that this keeps u_new, v_new close to their old values, and orthogonal
    to each other and to D)
    Use the previous and current frames and positions to build a cylindrical 'ring':
    For theta from 0 to 2pi {
      find the points (P+(u_new, v_new, D) * (cos theta, sin theta, 0))
      and connect them to their counterparts from the previous ring
      (note that that multiplication is a matrix-vector multiply)
    }
    update u_prev and v_prev to u_new and v_new
  }
  update the other prev variables to their 'new' values
}

```

This is obviously *very* rough pseudocode; if there's any piece of it that's unclear just let me know and I'll try and explain, but it's going to be hard to cover all the details without just a huge code dump...

---
Tags: unity, 3d, software-engineering, procedural-generation, curves
---


# Question
Title: Can I make a character solid but not lose non-physics behaviour?
My character can walk around in the world, but walks through other objects, for example a cylinder (stand-in for a cannon). To fix this I added a capsule collider to each of the character and cylinder, but that wasn't enough. Apparently I have to add a Rigidbody as well. \[1\] \[2\]

When I add a Rigidbody to either one, they collide as expected. However, when I add a Rigidbody to my character, it falls over when I move forward. When I add a Rigidbody to my cylinder, other functionality fails (it is supposed to shoot cannonballs, and they act strangely). If I enable Kinematics on either, they stop colliding.

Is there any other way to make the character and cylinder solid with respect to each other, without breaking existing non-physics functionality?

# Answer
Add a character controller and use controller.move() with this you can make your character don't walk through the walls, if this wall have a collider.
> 2 votes

# Answer
You can freeze rotations of a `Rigidbody`.
> 1 votes

---
Tags: unity, collision-detection, physics, rigid-body-dynamics
---


# Question
Title: How to create public Arrays of game objects so that they can be assigned through inspector
I am making a unity2D game. I need to declare public array of gameobjects so that I can assign them colliders, textures through inspector by drag n drop. Is there any way to do this? I am using c#.

I found but not able to figure this out.Here is one link that is not useful for me please tell why???

# Answer
> 3 votes
Why do you need a public array for that? If you just want to create `GameObject` by drag and dropping you can do that in the **Scene hierarhcy**.

If you need to access them later in a script then you can declare a public list:

```
public List<GameObject> myList = new List();

```

Then just drag and drop the objects to that list.

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


# Question
Title: LibGDX How to take screenshot and use as background for pause screen
So I am trying to take a screenshot of the current situation during the PlayState of the game and when the player pauses the game I want the game to take a "screenshot" save it in memory and not as a file and use it as the background for the pause screen. Any ideas because I have no clue.

# Answer
Keep rendering the game. just pause the logic!

You can esily just attach a "pause" pass, that will render the framebuffer and then blur it or what not, and after that add some gui! should be really straight forward.

The only reason i can imagine why you would like to take a screenshot is to not use all the gpu power and reduce lag when you are pausing. Which is a valid point, but you should be fairly okay with just removing the cpu power being used. And for this approach, i would just ask for the last rendered frame buffer inside the game loop, and from there just do what ever i want with it. that should give you the desired effect.
> 2 votes

---
Tags: java, libgdx
---


title: Preventing Collusion

text:
# Question
Title: Preventing Collusion
Over on Code Golf Stack Exchange, competitions are run where multiple programmers compete against one another. One particular class of challenges is "King of the Hill". Here is an example of a King of the Hill challenge. The unique aspect of King of the Hill is that the players must interact until a winner emerges. Most of the other competitions are non-interactive.

When interaction is introduced into a game, collusion become an issue. In real life, collusion is often not in the best interest of the players due to social consequences. However, on the Internet, the social factors play an almost nonexistent role. Anonymity allows multiple players to collude in private, or even allow a single person to manipulate multiple players.

I really have two questions, but they both address the same problem from different angles.

* How can collusion be discouraged or prevented in an online, multiplayer, interactive game?
* How can collusion be caught and punished in an online, multiplayer, interactive game?

Things to keep in mind:

* This is not a Kingmaking scenario. "Kingmaker" specifically describes a player who chooses to collude as a result of being doomed to lose.
* One player may unintentionally help another player while trying to win. This is not collusion.
* Simply prefacing every challenge with "No colluding allowed." will lead to an argument over what constitutes collusion. Can it be objectively defined, given the previous bullet point?
* In case anyone is unfamiliar with the culture differences between sites, Code Golf Stack Exchange does not subscribe to the "Question and Answers" format. The format is geared towards "Challenge and Solutions".

I found some information on collusion detection from online poker sites. They detect collusion by flagging accounts who always play at the same table, and either manually or automatically take action. This solution does not translate well to the Stack Exchange format, but it seems like a step in the right direction.

# Answer
My first thought is that generally this is not an easy problem. It's like trying to put swear filters in a game because people will get around that $h1t so many ways. But it's an interesting problem so here's some musings on it that may or may not qualify as an answer.

So for players to collude, they must be able to...

1. Have contact with each other before the game to scheme about colluding.
2. Derive some benefit from collusion.
3. Be in the same game together.
4. Be able to recognize each other in the game so they can collude.

To each of these points...

**Block contact**

For starters, you can't prevent communications by the nature of ... nature.

**Minimize collusion benefits**

Minimizing benefits to collusion gets into the realm of game design, where perhaps there is some clever way to craft the game where collusion ultimately will lead to one of the participants losing, and the other benefiting - and no way for the winner to share the benefits. You don't collude because it's just not worth it.

**Keep collusionists from being in the same game**

Keeping collusionists apart you can kind of prevent by having a huge number of games, or some kind of match maker that automatically creates matches so that players can't predictably be in the same game. If you are only in the same game as your collusion partner a small percentage of games, the benefits of collusion will have to be very high to make it worth while.

**Prevent collusionists from identifying each other**

Last but not least is not letting players identify each other easily, which I think is where it starts to get interesting and closer to the technical realm. If two players do not know if they are in the same game, then they can't collude. And with that, here are some ideas and thoughts. They are in no way perfect, but they might give you some ideas...

* For starters, dynamically create IDs for players that change with every game. Then a player can't join as "Cheater 1" and tell their friend to just look for them by ID.
* Of course then a player could just say, "Hey I'm 969935993 this round", so don't tell a player their *own* ID. Do tell them the ID of the other players though. If you don't know your own ID, you can't share it with others. Your friend may be in the same game, but they have no way (via IDs) to say, "Hey it's me."
* Don't allow chat. Kind of allows players to identify each other. This might put a crimp in the game, but it helps.
* Assume players will come up with novel and alternate ways to make in-game signals to identify each other. E.g., "I just played a 10 - did you see anyone play a 10?" Yes, this will allow identification, however depending on the game's complexity, it may not be a given that players can absolutely identify each other in a single play. This initial uncertainty potentially puts the players at a disadvantage as they are not playing initially to win, but rather to identify each other. That puts them behind the other players, especially if it takes multiple rounds to identify each other. There's got to be a really big benefit to collusion for them to do this, and not be concentrating on the game's goals.
* Change their IDs every game, so each round they must go through the whole "Are you there? Is that you?" cycle.

This isn't all ideal really, and there are probably various holes in the approach. And if done wrong it probably could make for a crappy game experience. Keep in mind that "ID" is something you use to identify someone. It could be a number or a name. Or it could be a dynamically created avatar face that is distinctive from another player.

In the end it seems like making collusion nonproductive so players go, "Why bother it's not worth it" is in a way the best solution.
> 5 votes

---
Tags: game-design, anti-cheat
---


# Question
Title: Copyright and patents on game design and names?
We all know that each game has elements from another game but when does one cross the line of copyright? I have a view particular questions about this since this "line" is very vague.

1. While looking for a name and Googling it usually return some kind of old or unknown game already with the exact same name. Can i use this name? And what about a name like Diablo, since Diablo is the commonly used name for the devil there cannot be a patent on this afaik. So would a different kind of game named Diablo be allowed?
2. Let's say i want to make a game of mechs like in Mechwarrior. Obviously the mech designs have copyright, the name as well since i suppose. But am i crossing any rights if i make a top down tactical squad game that include mechs of different designs/names and call it Clash of Steel?

I understand there are not much lawyers here, but how could anyone create a game these days that does not cross the lines of copyright. Like the Mechwarrior example, there are plenty of games nowadays even movies that use this concept. For what it matters Mechwarrior could have ripped the idea from the Gundam anime series. With so many titles coming out each week including the indies it is next to impossible not to infringe into someone copyright.

# Answer
> 6 votes
## Regarding using names

When one releases a game commercially, they usually register a trademark for that name and product category. When one registers a trademark, nobody else may use that name for their product, when that product falls into the same product category. You can use the patent trademark database of the US patent and trademark office to check if the name you want to use is trademarked or not. The name "Diablo", for example, is such a registred trademark.

But note that unregistred trademarks also enjoy some protection. The usual rationale here is that you must not name a product in a way which makes it appear as if it would be associated to the product of someone else.

Let's say I would create a really crappy game and sell it under the name "Diablo IV". I would immediately benefit from the notoriety of the franchise and my game would sell copies no matter how crappy it is, just because of the "Diablo" name. But Blizzard Entertainment would certainly not like that my game hurts the reputation of their franchise. After people saw my game, their believe in the Diablo franchise would be shattered. They would never again buy a game with the "Diablo" name just based on the reputation. That would cause a tangible financial damage to Blizzard Entertainment for which they could sue me. The next day I would have a cease-and-desist letter in my mailbox.

## Regarding copying game concepts:

There is no business where people copy as much from each other conceptually as in game development. The gameplay of every first person shooter ever can be traced back to Doom, and that of every real-time strategy game back to Dune II.

There are certain companies which build their whole business model on cloning other peoples games. But note that when you clone the game of a big-player too accurately who has the money to go through with a lawsuit, this might backfire.

The line between "inspired by" and "ripped of from" is unfortunately very blurry. Whether your game is too close to another game that it infringes copyright or not is a decision a court has to make in each individual case.

# Answer
> 3 votes
Concepts are not copyright, assets are. Names are also not copyright, but they can be trademarked. Logos are copyright.

In the U.S., you don't have to apply for copyright, it is implicit when you create content. You can make whatever you want as long as you are not copying assets or infringing upon trademarks.

You can rip as many ideas as you like. Ideas are not protected.

---
Tags: legal, copyright, licensing, patents
---


# Question
Title: How can I restrict the rotation of an object to a subset of axes using quaternions?
I've got a question about quaternions in my WebGL application.

How can I rotate an object only around two axes? For example, how can I exclude/nullify rotation about the Y axis?

The problem is that when I rotate something around X axis, and then around Y axis, it rotates around Z axis slightly as well. I have read whole piles of posts about it (for example) but none of them really helped me. Reversal order of multiplication operations doesn't work for me. My actual code below:

// Main rotation function:

```
rotateCamera: function(angleX, angleY) {
    if (angleY !== 0) {
        this.yawRotation.axisToQuaternion(angleY, this.tempVec.make(1, 0, 0)));
        this.rotation.multiply(this.yawRotation);
    }
    if (angleX !== 0) {
        this.pitchRotation.axisToQuaternion(angleX, this.tempVec.make(0, 1, 0)));
        this.rotation.multiply(this.pitchRotation);
    }
    this.rotation.normalize();

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());

```

// Matrix setRotation function:

```
setRotation: function(m) {
    this.element[0] = m.element[0];
    (... some code omitted ...)
    this.element[10] = m.element[10];
},

```

And the ought-to-be-working code based on other posts (which is not working):

```
rotateCamera: function(angleX, angleY) {
    if (angleY !== 0) {
        this.yawRotation.axisToQuaternion(angleY, this.tempVec.make(1, 0, 0));
    }
    if (angleX !== 0) {
        this.pitchRotation.axisToQuaternion(angleX, this.tempVec.make(0, 1, 0));
    }
    this.yawRotation.multiply(this.rotation);
    this.rotation.copy(this.yawRotation);
    this.rotation.multiply(this.pitchRotation);
    this.rotation.normalize();

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
},

```

EDIT: I have added more info about the actual code.

EDIT2: Okeeeey, I almost found a working answer for my problem (adapted it from Rick Hoskinson's post). My updated code below:

```
rotateCamera: function(radX, radY) {
    // Pitch (vertical rotation)
    if (radY !== 0) {
        this.pitch += radY;
        // Prevent camera from flipping upside-down (constrained by vertical "plane")
        this.pitch = Math.clamp(this.pitch, -Math.PI/2, Math.PI/2);

        this.rotation.axisToQuaternion(this.yaw, this.tempVec.make(0, 1, 0));
        this.rotation.multiply(this.tempQuat.axisToQuaternion(this.pitch, this.tempVec.make(1, 0, 0)));
    }
    // Yaw (horizontal rotation)
    if (radX !== 0) {
        this.yaw += radX;

        this.rotation.axisToQuaternion(this.yaw, this.tempVec.make(0, 1, 0));
        this.rotation.multiply(this.tempQuat.axisToQuaternion(this.pitch, this.tempVec.make(1, 0, 0)));
    }

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
}

```

Camera's roll has been eliminated using this method, but strange camera motion appears when rotating from one of the sides and then looking below (or I should say trying to look below, cause it curves away from this direction).

# Answer
> 2 votes
Finally, I have found an ultimate answer for my question. All I had to do it to use rotation from Euler angles instead of rotating around an axis. Working code below:

Inside camera class:

```
rotateCamera: function(radX, radY) {
    this.pitch += radY;
    // Prevent camera from flipping upside-down (constrained by vertical "plane")
    this.pitch = Math.clamp(this.pitch, -Math.PI/2, Math.PI/2);

    this.yaw += radX;
    // Cancel unnecessary looping rotation degree
    if (this.yaw <= -2 * Math.PI)
        this.yaw = 0;
    else if (this.yaw >= 2 * Math.PI)
        this.yaw = 0;

    this.rotation.yawPitchRollToQuaternion(this.yaw, this.pitch, 0);

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
},

```

yawPitchRollToQuaternion function taken from here: reference

---
Tags: javascript, rotation, quaternion, webgl
---


# Question
Title: How do I calculate the z-coordinate for a perspective-camera in 2D?
I'm new to LibGDX and trying to use `DecalBatch` with `PerspectiveCamera`, simply to have Z-coordinate for my sprites, as `SpriteBatch` does not offer that. However, I don't know how to calculate the Z-coordinate for the `PerspectiveCamera` for "pixel-perfect 2D-projection". How do I do that?

# Answer
> 1 votes
What "Pixel perfect" is depends on the size of your textures divided by the mesh's area. First, It's important you keep the aspect ratio between your mesh and textures: If your texture is 64x32, your mesh/quad/Decal will be 2:1 (for example, 2x1).

Now, closer to what you desire, the most important part is to have a consistent and analogous unit measurement. Let's go back to the example before, but let's make the Decal 64x32 (we'll make the 3D unit be equivalent to a "pixel" -notice the quotes, as it's not really the case, just a illusion to help us-). Next, you have to calculate which depth/distance from the general decal plane (assuming your decal's will be coplanar, if not, you can't achieve "pixel perfect" on all -well, you can, but decals with the same resolution should be coplanar-) using the inverse of the equations exposed here: http://docs.unity3d.com/Documentation/Manual/FrustumSizeAtDistance.html (calculating the inverse will be left as exercise for you, or you can always iterate to aproximate)

And, with the distance calculated, you set the camera to look at the plane from that distance: Suposing a XY plane, set z=thisDistance You may need to toy around with the Field Of View depending on the resolution/aspect ratio, or you'll only achieve "Pixel Perfect" on a single dimension.

# Answer
> 1 votes
This is one area that I also found quite lacking. Instead of using `DecalBatch`, I did something much, much simpler: I added a `.z` value to all sprites, and just draw them in order.

Technically, I created my own wrapper/subclass of `Sprite` with a `z` property which I can get and set. When drawing, I have a sorted list of sprites, and just draw them from lowest- to highest-z.

In terms of performance, try to maintain the sorting/ordering outside of the actual drawing (don't re-sort on each draw call, only when you add/remove a sprite).

---
Tags: 2d, mathematics, libgdx, coordinates, perspective
---


# Question
Title: How can I implement scrolling endless road in XNA?
I am developing XNA game like following screenshot.

I created my 3D objects and camera so I have models. But how can I implement scrolling road in XNA?

# Answer
> 1 votes
What you generally see in these games are repeated parts of the level. You can create "chunks" which contain a piece of road and the related props (trees, road markers, signs, etc).

You can create many different of these chunks, just make sure that the end of a chunk matches the next one. Then, when your car is moving forward (or the chunks move backwards to create the illusion of a moving car), make sure you place a new chunk in front of the current. As the car drives, it will go onto the next chunk and you can reclaim the previous chunk by laying it in front again to create an endless loop.

**Implementation** (rough steps)

\[Init\]

* Load road chunks (mesh, texture...). Make sure you have at least two chunks (or create two instances of the same chunk)

\[Render\]

* Render the first chunk under the car (you can place it using the translation part of the world matrix)
* Render the second chunk in front (you can place it using the same world matrix as the first chunk PLUS the size of the chunk in the road's direction)

\[Update\]

* Movement: you can either move the car forward OR move the chunks downward.
* Check if the current chunk has moved out of the camera view. If this is the case, place it in front of the chunk that is under the car.

---
Tags: xna
---


title: Print on the GUI in Unity

text:
# Question
Title: Print on the GUI in Unity
I'm trying to show the players name on the GUI with a label.

```
GUI.Label(new Rect(10,10, 100, 30), playerName);

```

Instead of use the default style I want to use a different font with larger character.

Any suggestion to achieve this?

# Answer
> 2 votes
Use GUI Skins. Create a new skin (go to `Assets -> Create -> GUI skin`), customize it accordingly (you have options for each kind of control), and link it to your script.

```
public class YourScript : MonoBehaviour
{
    public GUISkin Skin;
    ...

    public void OnGUI()
    {
         GUI.skin = Skin;
         GUI.Label(new Rect(10,10, 100, 30), playerName);
    }
}

```

More on GUI Skins in the official documentation here.

# Answer
> 1 votes
```
GUIStyle myStyle;

void Start ()
{
    myStyle = new GUIStyle();
    Font myFont = (Font)Resources.Load("Fonts/comic", typeof(Font));
    myStyle.font = myFont;
    myStyle.fontSize = 50;
}

void OnGUI ()
{
    GUI.Label(new Rect(10,10, 100, 30), playerName, myStyle);
}

```

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


title: What do gameplay programmers do?

text:
# Question
Title: What do gameplay programmers do?
Game development has lots of fronts... gameplay, physics, graphics, etc. and whenever I look up the answer for this question it's always something vague like: "extended knowledge of c++, c# or whatever".

But what exactly does that mean? Does the gameplay programmers know lots of openGL, directX? maybe lots of vectors, matrices? Do they need to know some network programming?

So what kind of coding and other tasks do gameplay programmers do?

# Answer
> 11 votes
Gameplay programmers are responsible of the "game" part of the software. What this means is that they're usually responsible, depending on the type of game, for the 3Cs:

* Character - the playable character
* Camera - how the player sees the world
* Controls - how the player interacts with the world

These tasks include a lot of dependencies with the engine, such as playing animations, reacting to collision, making sure the actions are replicated properly over the network, etc...

The creation of mission items for level designers / mission scripters is also often done by the gameplay programmers.

Some teams will have AI programmers, but if it's not the case, gameplay programmers do the AI as well, which includes behaviors, navigation, player feedback, etc...

It's a pretty broad field and depends a lot on the game type you're working on.

Gameplay is often programmed in the "native language" of the engine, but can also be scripted using a higher level language, such as Lua, Python, Unreal Script, etc...

# Answer
> 1 votes
As was noted in comments, what "Gameplay Programmer" means varies wildly from company to company. In my own experience, the most useful way I've found of thinking about gameplay programming is this aphorism:

> Gameplay programming is a tools programming job supporting designers

In the same way that a 'traditional' tools programmer works on the tools and systems that allow content creators like 2d and 3d artists and audio people to get their work into the game, the gameplay programmer works with designers on the tools — and particularly, the **systems** — that help those designers showcase their own creative talents.

I've found that thinking about the job this way helps me with both understanding the work better (I tend to think best in terms of systems - e.g., Combat, Traversal, Camera, etc.), but also helps me understand who my 'customer' is and how I should be focusing my efforts.

---
Tags: game-industry, software-engineering
---


# Question
Title: How can I move keyframes further apart in ToonBoom?
I've created an animation entirely out of screen capture fragments and keyframes, and I haven't allowed enough time for one portion. I'd like to simply stretch out the time between two keyframes, pushing all other keyframes and exposures out to the right, but I can't see how to do it.

Here's a screenshot that shows my situation:

How do I do this?

# Answer
Hmm, I did eventually manage to figure this out. It turns out that if you SELECT all the stuff you want to move, you can just drag it all, and it'll move keyframes and everything. The keyframes will move along with the frame sequences that contain them, if those sequences are selected (turn them purple, if I remember right).
> 0 votes

---
Tags: animation, tools
---


title: Smooth input handling in Java

text:
# Question
Title: Smooth input handling in Java
I am writing a Java game.

My problem is to get a really smooth input. If I hit the key `W` the character has to go forwards, but if I hit `A` and release the `W` key, the character doesn't go left ways :( .

It isn't smooth. Which ways are given in common game developing for a smooth input?

**My current source code** (Input.java): http://pastebin.com/9Z9qtXik (MainLoop.handlingInputs): http://pastebin.com/Vx8BzSpL

# Answer
> 0 votes
In your `public void keyReleased(KeyEvent arg0)` method you are marking all keys as released, not just the one which actually was released. The result is that when the player releases one key while still holding another, the other key will also be considered released.

You need to check `arg0` for the key which actually was released, just the way you already do in `keyPressed`.

Another thing which could cause problems is that you implemented both `keyPressed` and `keyTyped`. These two events behave very similar, so when you implement one, you usually have no reason to also implement the other. The main difference is that keyPressed reports modifier-keys like shift as separate events, while keyTyped reports visible characters entered. When you type a capital-A, `keyPressed` is called twice, first for `shift`, then for `a`. `keyTyped` is called for a single event `A`. For game input, `keyPressed` is usually more appropriate.

# Answer
> 0 votes
I would suggest using KeyBindings for smooth input handling! Right now it is true you have an error in your code as stated by @Phillipp, but KeyListening is not recommended to be used in games.

KeyBindings are a much newer update to Java and handle input much better that KeyListeners do. A quick Google search will provide you with more than enough sample code to learn it :)

---
Tags: java, 2d, input
---