# Question
Title: What's the optimal balance of story and combat in a game?
A good movie must balance the action and storytelling so that it keeps the pace without boring the audience with too much story.

Now the questions is how should the action and story be balanced in a video game?

Should there be more story or more action?

I would like to see some research papers about this topic if they exist.

# Answer
> 1 votes
I believe this question has a flawed assumption at its very core:

It assumes story and "combat" are separate.

That was often the case of games of eras passed. Just remember games like Final Fantasy, where you had separate cinematic/dialogue moments and a very clunky combat system. But what was good enough then, aint necessairly good enough now. The approach to handling narrative in games changes a lot. Just look at Telltale Games, like the Wolf Among Us or Walking Dead. The story and decisions made by the player are part of the gameplay and gameplay facilitates story.

The problem with dissecting gameplay and stroy into two separate things is that players that are into your story will treat combat gameplay like an irritating break in the narrative - an artificial pause, making them wait for what they want (which is learning what happens now in the story). It's true the other way around too. If I'm mostly into kicking some orc ass, I'll skip all your story and dialogue with a "blah blah blah" in the back of my head.

A better solution would be to blend the two. Incorporate decision making into the gameplay mechanic. Make the story a part of the gameplay, not a book that is being read to you in breaks between gameplay sequences.

So my advice for you is: maybe you should ask how to incorporate storytelling into your gameplay mechanics?

If you want to know more on the topic, I kindly suggest starting with this Extra Creditz video

---
Tags: game-mechanics, balance
---


# Question
Title: Can the GUI be used to create game objects?
I want to be able to position 10 various game objects (sprites) within the area of the screen which will be dynamically sized accordingly to the screen size of the device. The area in which I want to position the items will be about 70% of the screen. The objects will be rectangles with irregular size (slightly irregular). The object should be positioned randomly (or in grid) within this area but they should not overlap. The objects will be a drop targets for other object which I will drag onto them.

To summarize I need:

1. The area in which I can place objects.
2. Random object position-er.

As I have been reading and watching various tutorials I have become very confused about how should I approach this.

Should I use a Rect to draw the area on which I will then place the objects, or should I use GUI/UI elements i.e. panel? Are the GUI/UI elements suitable for achieving this or are they meant to be only used to create games menus not for actual game play?

# Answer
In case if everybody will be looking for something similar, I have found what I have been looking for in the youtube tutorial made by Stuart Spence "Unity3D - Unity 4.6 UI Objects Created at Runtime". Also the release of Unity 4.6 brought the functionality which I wanted. Hope it'll help somebody.
> 0 votes

# Answer
GUI and 2D game objects are fundamentally different.

Generally speaking, a GUI element is a 2D element (texture/text) that will accept some input and could potentially live in some screen hierarchy (e.g. a panel in a container).

A 2D game object/element is... well, it's whatever a game object is in your game. It can move on its own, it could react to input, it could react to other objects, it could rotate for absolutely no reason other than a funky idly animation.

Most GUI systems will be geared at simplified behavior of a GUI element as described above, which means that if you want to do something a bit more complex than just show/react to input, you will find a GUI system to constrained for game elements.

With that said, there's nothing to prevent you from treating your game objects as GUI elements.
> -1 votes

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


# Question
Title: How can I make Network.RPC call a method with params object[]?
Why do I need to do this? The game I'm working on fully conforms to a component style design. Every component that a game object uses is placed on the object and is disabled/enabled based on it's state machine's current state. This means if I have two components that share a base class that has an RPC method, they won't work due to this:

"RPC function names should be unique accross the scene, if two RPC functions in different scripts have the same name only one of them is called when RPC is invoked"

http://docs.unity3d.com/ScriptReference/NetworkView.RPC.html

This means an arbitrary component will be the "this" of the RPC method that actually gets called. So, to fix this I've added a unique name to every component and have to do some relatively slow searching and reflection in order to have a safe RPC call. So, now every RPC call should go through my RPC method. This method simply serialises the parameters into a string and sends them to unity's RPC method.

This works great, except one tiny thing. Serialising the entire array results in Unity doing no serialisation in NetworkView.RPC. That's fine, except as far as I can tell, Unity's NetworkView.RPC method is the only thing in the universe that knows how to serialise a NetworkViewID properly.

So, serialising the whole array of objects isn't an option. So, I now I serialise them IF they're not a NetworkViewID, then send the entire object array to Unity, which it does interpret correctly:

```
protected void ComponentRPC( string methodName, RPCMode mode, params object[] args )
{
    object[]                serialisedObjects       = new object[args.Length + 2];

    serialisedObjects[0] = uniqueName;
    serialisedObjects[1] = methodName;
    for( int i = 2; i < serialisedObjects.Length; ++i )
    {
        if( args[i - 2].GetType() == typeof( NetworkViewID ) )
        {
            serialisedObjects[i] = args[i - 2];
            continue;
        }
        serialisedObjects[i] = base.Serializer.Serialize<object>( args[i - 2] );
    }

    // Serialise arguments and call our RPC method through Unity.
    networkView.RPC( "ComponentRPCNetwork", mode, serialisedObjects );
}

```

I also put the unique component name and method name in the array. The only problem now is, Unity won't put the objects it serialises into my params object\[\] parameter. The RPC method:

```
[RPC] private void ComponentRPCNetwork( params object[] args )
{
    // First we have to deserialise the method arguments.
    string              uniqueID                    = ( string )args[0];
    string              methodName                  = ( string )args[1];
    object[]            deserialisedArgs            = new object[args.Length - 2];
    for( int i = 0; i < deserialisedArgs.Length; ++i )
    {
        if( args[i + 2].GetType() == typeof( byte[] ) )
        {
            deserialisedArgs[i] = args[i + 2];
            continue;
        }
        deserialisedArgs[i] = base.Serializer.Deserialize<object>( ( string )args[i + 2] );
    }... // More stuff.

```

So, my question is, can I get Unity's NetworkView.RPC method to put it's serialised objects into this "args" parameter? If not, can anyone see anyway around this?

By the way I'm using Vexe's framework, so you might see unusual things like "base.Serializer" etc.

# Answer
I regularly use RPC like the following:

```
{
    //Send all the ship components to other clients
    NetworkViewID viewID = ship.GetComponent<NetworkView>().viewID;
    foreach(ModuleDefinition module in ship.GetAllModuleDefinitions()) {
        networkView.RPC ("AddShipModule",
                         RPCMode.Others, viewID, netOwner,
                         ModuleDefinition.WriteByteStream(module));
    }
}

[RPC]
public void AddShipModule(NetworkViewID newPlayerView,
                          NetworkPlayer netPlayer,
                          byte[] moduleInitializer) {
    if (netPlayer != Network.player) {//don't update ourselves
       //deserialize moduleInitializer into module and add it to local instance
    }
}

```

This is when using my own serializer to create the `moduleInitializer` out of an object and its components. That `byte[]` array could just as easily be full of JSON or any other binary data.

If your allocated ID is not being found on the other end, it could be because the object you're trying to communicate was created incorrectly, giving it a different `NetworkView.viewID`. You can always use `Network.Instantiate` or you can send a message to clients that an object needs to be instantiated and send the `NetworkView.viewID` along with it.
> 1 votes

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


# Question
Title: How can I draw curves above a mesh surface?
I am making an animation of a deformed sphere that represents some aspects of the wave function in a hydrogen atom. I am starting with an octahedron that i push through a tessellation shader. The tessellation evaluation shader then first deforms the octahedron into something more sphere-like and then applies the deformation stuff.

Now, to further improve the visual impression of the deformation, I would like to place lines on top of the sphere and also deform those, to achieve something resembling level curves. What would be a good way to achieve this? Generating circles on the cpu side and then sending them to GL and having them deformed separately seems rather odd, but I cannot figure out another way.

If I want to achieve this in one shader run I am also limited to drawing triangles (patches) and making these appear as lines also seems rather unwieldy.

# Answer
> 3 votes
Rather than using a geometry shader as mentioned in another answer, I managed to implement the lines very cleanly in the fragment shader, by passing the spherical coordinates before the deformation from the tessellation shader to the fragment shader. There I could then use uniforms that describe the number of level curves to calculate position and line width etc. which then can be transformed to colour...

# Answer
> 1 votes
You can use a geometry shader to generate those lines.

There are a few tutorials/examples on how to generate sprites with geometry shaders, you can base yourself off of these to create thick lines with triangle strips from line strips.

http://www.geeks3d.com/20140815/particle-billboarding-with-the-geometry-shader-glsl/

---
Tags: opengl, shaders, graphic-effects
---


title: Drawing a Line in 3D using DirectX 11

text:
# Question
Title: Drawing a Line in 3D using DirectX 11
I had a lot of problems to draw a line in a 3D and had a weird results.. The 3D Lines are projects in 2D and that's so weird. They only work with that view matrix configuration:

```
XMVECTOR Eye = XMVectorSet(0.0f, 3.0f, -6.0f, 0.0f);
XMVECTOR At = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX g_View = XMMatrixLookAtLH(Eye, At, Up);

basicEffect->SetView(g_View);

```

but when I use my camera view matrix they get projected in 2D.. however I have my terrain rendered correctly and other things..

Here is my Camera class:

```
void cCamera::Initialize()
{
Reset();
}

void cCamera::Reset()
{
// config for left hand camera system
m_Position = XMFLOAT3(0.0f, 0.0f, 0.0f);
m_Forward = XMFLOAT3(0.0f, 0.0f, 1.0f);
m_Up = XMFLOAT3(0.0f, 1.0f, 0.0f);
m_Right = XMFLOAT3(1.0f, 0.0f, 0.0f);

UpdateViewMatrix();
}

const XMFLOAT3& cCamera::Position() const
{
return m_Position;
}

const XMFLOAT3& cCamera::Forward() const
{
return m_Forward;
}

const XMFLOAT3& cCamera::Up() const
{
return m_Up;
}

const XMFLOAT3& cCamera::Right() const
{
return m_Right;
}

float cCamera::AspectRatio() const
{
return m_AspectRatio;
}

float cCamera::FieldOfView() const
{
return m_FieldOfView;
}

float cCamera::NearPlaneDistance() const
{
return m_NearPlaneDistance;
}

float cCamera::FarPlaneDistance() const
{
return m_FarPlaneDistance;
}

XMMATRIX cCamera::ViewMatrix()
{
return XMLoadFloat4x4(&m_ViewMatrix);
}

XMMATRIX cCamera::ProjectionMatrix()
{
return XMLoadFloat4x4(&m_ProjectionMatrix);
}

XMMATRIX cCamera::ViewProjectionMatrix()
{
XMMATRIX viewMatrix = XMLoadFloat4x4(&m_ViewMatrix);
XMMATRIX projectionMatrix = XMLoadFloat4x4(&m_ProjectionMatrix);

return XMMatrixMultiply(viewMatrix, projectionMatrix);
}

void cCamera::SetPosition(const XMFLOAT3& position)
{
m_Position = position;
}

void cCamera::SetPerspective(float fov, float aspect, float nearPlane, float farPlane)
{
m_FieldOfView = fov;
m_AspectRatio = aspect;
m_NearPlaneDistance = nearPlane;
m_FarPlaneDistance = farPlane;

XMMATRIX projectionMatrix = XMMatrixPerspectiveFovLH(m_FieldOfView, m_AspectRatio, m_NearPlaneDistance, m_FarPlaneDistance);
XMStoreFloat4x4(&m_ProjectionMatrix, projectionMatrix);
}
void cCamera::SetOrthographic(float viewWidth, float viewHeight, float zn, float zf)
{
XMMATRIX projectionMatrix = XMMatrixOrthographicLH(viewWidth, viewHeight, zn, zf);
XMStoreFloat4x4(&m_ProjectionMatrix, projectionMatrix);
}
void cCamera::LookAt(const XMVECTOR &target)
{
XMVECTOR p = XMLoadFloat3(&m_Position);
XMVECTOR look = target - p;
XMStoreFloat3(&m_Forward, look);
}

void cCamera::UpdateViewMatrix()
{
XMVECTOR eyePosition = XMLoadFloat3(&m_Position);
XMVECTOR direction = XMLoadFloat3(&m_Forward);
XMVECTOR upDirection = XMLoadFloat3(&m_Up);

XMMATRIX viewMatrix = XMMatrixLookToLH(eyePosition, direction, upDirection);
XMStoreFloat4x4(&m_ViewMatrix, viewMatrix);
}

void cCamera::Update(float dt)
{
if (GetAsyncKeyState('W') & 0x8000)
    Walk(45 * dt);

if (GetAsyncKeyState('S') & 0x8000)
    Walk(-45 * dt);

if (GetAsyncKeyState('A') & 0x8000)
    Strafe(-45 * dt);

if (GetAsyncKeyState('D') & 0x8000)
    Strafe(45 * dt);

if (GetAsyncKeyState('Z') & 0x8000)
    MoveUp(-45 * dt);

if (GetAsyncKeyState('X') & 0x8000)
    MoveUp(45 * dt);

UpdateViewMatrix();
}

void cCamera::MoveUp(float d)
{
// mPosition += d*Up
XMVECTOR s = XMVectorReplicate(d);
XMVECTOR u = XMLoadFloat3(&m_Up);
XMVECTOR p = XMLoadFloat3(&m_Position);
XMStoreFloat3(&m_Position, XMVectorMultiplyAdd(s, u, p));
}

void cCamera::Strafe(float d)
{
// mPosition += d*Right
XMVECTOR s = XMVectorReplicate(d);
XMVECTOR r = XMLoadFloat3(&m_Right);
XMVECTOR p = XMLoadFloat3(&m_Position);
XMStoreFloat3(&m_Position, XMVectorMultiplyAdd(s, r, p));
}

void cCamera::Walk(float d)
{
// mPosition += d*Forward
XMVECTOR s = XMVectorReplicate(d);
XMVECTOR l = XMLoadFloat3(&m_Forward);
XMVECTOR p = XMLoadFloat3(&m_Position);
XMStoreFloat3(&m_Position, XMVectorMultiplyAdd(s, l, p));
}

void cCamera::Pitch(float angle)
{
// Rotate up and forward vector about the right vector.

XMMATRIX R = XMMatrixRotationAxis(XMLoadFloat3(&m_Right), angle);

XMStoreFloat3(&m_Up, XMVector3TransformNormal(XMLoadFloat3(&m_Up), R));
XMStoreFloat3(&m_Forward, XMVector3TransformNormal(XMLoadFloat3(&m_Forward), R));
}

void cCamera::RotateY(float angle)
{
// Rotate the basis vectors about the world y-axis.

XMMATRIX R = XMMatrixRotationY(angle);

XMStoreFloat3(&m_Right, XMVector3TransformNormal(XMLoadFloat3(&m_Right), R));
XMStoreFloat3(&m_Up, XMVector3TransformNormal(XMLoadFloat3(&m_Up), R));
XMStoreFloat3(&m_Forward, XMVector3TransformNormal(XMLoadFloat3(&m_Forward), R));
}

```

That's the result of a drawing a line in 3D Cords

# Answer
Your problem is the difference between XMMatrixLookToLH and XMMatrixLookAtLH.

The DirectX TK SimpleSample is using `XMMatrixLookAtLH` which is computing:

```
XMVECTOR Eye = XMVectorSet(0.0f, 3.0f, -6.0f, 0.0f);
XMVECTOR At = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX g_View = XMMatrixLookAtLH(Eye, At, Up);

```

Here "At" is the *position* 0, 1, 0 and is used as the **focus position** (i.e. it computes the eye direction from Eye and At).

Your camera code is using `XMMatrixLookToLH`, which is failing to get the right result because you are passing (0,1,0) as the **EyeDirection** and **UpDirection** which naturally fails.
> 1 votes

---
Tags: shaders, directx
---


title: Android notifications with Unity

text:
# Question
Title: Android notifications with Unity
I'm working for the first time on a game for Android using Unity and I need to use Google Cloud Messaging to receive push messages.

I've already done the integration of my Unity project with GCM, using this project, and of now I can receive and read messages sent to my phone while the game is running. However, I want to be able to receive them while the app is closed. Currently, if I send a message and the app is not running, I get an error stating that my app stopped working.

So, in essence, I want to know: what are the steps to handle incoming push messages when my app is closed, display them as a notification in Android and launch my game app when I open such notification? What else should I do outside Unity so my project can handle Android notifications while closed?

# Answer
> 0 votes
I'm not sure what your problem is. If you have successfully integrated GCM messaging, then it wouldn't matter if your app is running or not, as you will get the message anyways. And from your answer, I believe you are getting the message -even when the app is not running- but something within your GCMIntentReceiver is making your app crash. I would suggest you run the app with logcat on and check what error is thrown when your app crashes -my money is on the class name within the intent in the GCM receiver.

You ask what should you do when you get the message. Well, displaying a notification is the obvious answer, otherwise the user will not know what happened, and this way they have the option to click on the notification and perform whatever action you want. All of these needs to be within the GCMIntentReceiver that listens for the GCM messages.

Anyways, this is a complex topic, and a lot of it is up to you as well. **If you want to avoid all the hassle** of implementing a system from scratch, I have an asset in the Unity Store that handles this very behaviour -and extends it to android as well:

**Easy Cross-Platform Notifications**

It comes with a full step-by-step guide that will help you all the way through -and in the end you will have a truly cross-platform notification system that can handle messages in between iOS and android devices!

# Answer
> 0 votes
It sounds like the problem you're encountering is due to a bug or implementation error in the GCM plugin you're using. If your app throws an error when it recieves a GCM notification while not active, that means that it's having an issue displaying the message correctly.

I see that the plugin was recently updated, so perhaps the latest version will solve your issue.

However, in my opinion, the easiest way to set up push notifications is to use a 3rd party service that provides both a plugin and notification delivery system.

There are a few reasons for this:

* Many 3rd party push notification services provide plugins and instructions on how to get things set up correctly that are up to date and well tested.
* Delivering a large number of notifications requires a significant amount of backend engineering work, and most open source solutions are unreliable or begin to fail after a high enough notification volume.
* 3rd party push notification service provides are relatively inexpensive, or even free in many cases.

Here are some good 3rd party services that you can check out that have Unity push notification support for Android and iOS:

---
Tags: android, unity
---


title: Push Notification to start a scene

text:
# Question
Title: Push Notification to start a scene
I was wondering whether I can use APNs in iOS to trigger an event in my game, like start a scene without user clicking the notification. Is it possible to use remote push notifications for events like this?

# Answer
Yes, this is possible. Many push notification plugins will execute a callback inside your game if a notification is received while the game is running.

Inside this callback you can load your desired scene.
> 1 votes

---
Tags: unity, ios, scene, server-push
---


title: Texture2D.SetData Method Overload

text:
# Question
Title: Texture2D.SetData Method Overload
Been reading up on various methods in the XNA framework, and found this one.

I've done some Google searching, but I can't seem to find any information on how to use this particular method overload. Parameters 3-5 are easy enough to understand, since they are used in another overload, but I'm not so sure about the first two.

I'm fairly sure that the first parameter is the mipmap level we are setting data to, but the second one has me completely lost.

However, I'm not exactly sure what I should be passing in here. I know it can be a null object, or a valid Rectangle object, but I'm not sure whether it is being used to specify the size of the mipmap texture like this:

Or whether it is supposed to be its position and size inside the Texture2D object like this:

Can someone shed some light on this please, and maybe provide a parameter sample or two so I can better understand? (I'm one of those people that can spend 2 hours trying to understand a theory and make absolutely no progress, and get it in about 5 minutes after a few examples \[or half dozen for more complex stuff\])

# Answer
It is the the position and size within the `Texture2D` object. Set data can only alter the color data within the minimap. It can not alter the size or create new ones.

The `Nullable<Rectangle> rect` is the destination within the Texture2D and the `int startIndex, int elementCount` is the source from the dataColors array.

Here are a few examples.

The Texture is generated with the below code

```
texture2D = new Texture2D(graphics.GraphicsDevice, 32, 32);

var dataColors = new Color[32 * 32];
for (var i = 0; i < dataColors.Count(); i++) {
    dataColors[i] = new Color(Color.Red.R, i % 225, 0);
}

```

---

Having a Rectangle the size of the Texture2D is the same as if the Rectangle is null. Worth nothing is that the Width * Height of the rectangle must be the same as the elementCount. Also the startIndex + elementCount must be less or equal than the size of the Color array and the Texture2D.

```
texture2D.SetData(0, new Rectangle(0, 0, 32, 32), dataColors, 0, 32 * 32);

```

---

Here I change the destination rectangle and sample from the beginning of the Color array.

```
texture2D.SetData(0, new Rectangle(6, 6, 8, 15), dataColors, 0, 8 * 15);

```

---

Here I use the same destination rectangle as before and sample starting at an off set for the of the Color array.

```
texture2D.SetData(0, new Rectangle(6, 6, 8, 15), dataColors, 112, 8 * 15);

```
> 5 votes

---
Tags: xna, textures, mipmaps
---


title: Emit light from items

text:
# Question
Title: Emit light from items
In order to create a day/night cycle in my game, I decreased the r,g and b values of the Color variable after a certain amount of time has passed. This worked as expected. I am wondering in order to create light from an item, like a fire or lamp, could I create a circle around the item and set the color in that circle to be white? Or is there a better way for accomplishing this in 2d?

# Answer
If you are not already, you should use a shader to make all the pixels on your screen darker for night. You can draw a white circle (or a nice gradient circle) in a new render target at the appropriate position, then pass that render target as a Texture2D into the shader. In the shader you can use the extra texture as a "mask" (or whatever you would like to call it). The shader would make the pixels "less dark" where the mask has more alpha. In this way you could even have multiple lighted objects -- just draw more than one mask into that render target.

If you do not know how to make shaders I highly recommend looking into that. http://rbwhitaker.wikidot.com/shaders-in-xna

Otherwise, you could do one of these:

1) Draw a large texture centered around the light source. The texture would be all black, except for a hole in the center. You should not be able to see the edges of this texture. This may not work for what you are trying to accomplish though.

2) Loop through all the objects in the scene and make them darker if they are farther away from the light source. A hint:

```
float multiplier = 1.0f / (light.position - obj.position).Length();

```

Hope this helped!
> 1 votes

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


# Question
Title: Should the render system know the entity manager?
In an entity-component based game architecture, I think the entity manager is a "high-level" system, and the render system a "low-level" system.

When I edit the position component of the entity, should the render system be aware of the entity manager, and get the position over it, or should there be no low-level system communicate with a high-level system?

I think that this should not be the case. Instead, if an entity is moved, the scene manager (also "high-level") should call a "move" function of the render system, and the render system updates the position. That means that every entity interaction has to be a function in my render system.

I'm afraid that I get cyclic dependencies in the first case. Is this the right way to go?

# Answer
> 1 votes
The typical ECS way to handle this is to abstract a level in your systems layering. Your design looks something like this:

```
render <--> transform <--> physics
                |           /
                |          /
               gameplay logic

```

Anything that needs to know where entities are at will pull that information from the transform system. Physics updates or game logic that move the entities will push the results into the transform system.

If you really need to know if an entity moved this frame (you need this less often than you might think) then you can either keep a secondary list of transforms from the last frame to compare against, set a dirty bit on the transform data which is cleared at the end of the frame, or insert the entity's id into a sorted set or bitmap of moved entities that's cleared each frame.

More complex engines will indeed give the renderer its own completely separate idea of scene nodes and transforms that isn't tied into the ECS at all, and some system in the ECS is responsible for synchronization high-level transform updates with the renderer's scene nodes. The diagram above would look almost identical in this case except that the `render` entry would be split between an ECS `render_system` which interfaces with `transform` and a separate `render_scene` module that interfaces with `render_system`.

---
Tags: architecture
---


# Question
Title: Label not properly centered in TextButton
I'm using LibGDX v1.1.0 and I see that the label of a TextButton is not properly centered. I have the following code:

```
m_resumeButton = new TextButton("resume", skin);
m_resumeButton.addListener(new ChangeListener() {
    public void changed(ChangeEvent event, Actor actor) {
        m_state = GameState.RUNNING;
        getGame().getWorld().pauseWorld(false);
    }
});

```

The default TextButtonStyle is defined as:

```
"com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle": {
    "default": {
        "up": "menu-button",
        "down": "menu-button-down",
        "checked": "menu-button-down",
        "disabled": "menu-button-disabled",
        "font": "font24",
        "fontColor": "white"
    }
}

```

The menu button images are simple 240x48 bitmaps saved as 9-patch images. An image can be found here to illustrate the problem:

https://www.dropbox.com/s/cwuhu5xb9ro5w6m/screenshot001.jpg

Am I doing something wrong? Or is there a problem with the button images I'm using?

# Answer
To solve the alignment problem of the label text I found some information on the internet (where else?). It is possible to add some additional padding to the label inside the text button:

```
TextButton button = new TextButton(text, skin, styleId);
button.setSize(width, height);
// Add some padding to the label in the button to shift it up a bit
button.getLabelCell().padBottom(padding);

```
> 3 votes

---
Tags: libgdx
---


title: How to determine this kind of vector?

text:
# Question
Title: How to determine this kind of vector?
Take a look at the picture.

I've got a camera(brown) and its ray(red). As I know ray has a direction and unlimited length(if you don't set it yourself). But now I need to determine ray's vector that starts at camera point and ends when it crosses a floor. How can I do that?

# Answer
I assume you know the ray direction, otherwise there are infinite rays that cross the floor. It crosses the floor when your camera pos (x,y,z) offset by a scaled ray direction k\*(a,b,c) has zero height, so:

y + k\*b = 0 =\> (we only care about the y component)
k = -y/b

so the vector that you need to add to the camera is

(-y/b)\*(a,b,c)

Of course, it goes without saying that you need to check for special case when b == 0, where the ray is parallel to the xz plane, so it will never cross it, unless on it (y==0)
> 0 votes

# Answer
The equation of the ray is `p = camerapos + t*ray` which is 3 equations (after splitting it up the coordinates):

```
p.x = camerapos.x + t*ray.x
p.y = camerapos.y + t*ray.y
p.z = camerapos.z + t*ray.z

```

then we know we want the point with `p.y = 0` so lets fill it in:

```
0 = camerapos.y + t*ray.y
t = -camerapos.y / ray.y

```

then just fill in the `t` in the first equation: `p = camerapos + (-camerapos.y / ray.y)*ray`
> 0 votes

---
Tags: java, jmonkeyengine
---


# Question
Title: Undefined reference error when trying to access a component using ECS
I'm trying to access the x and y values from `PositionComponent` in my `MovementComponent` but I get this error and I just can't figure out why I get this.

in my `Entity` class I've got a function `GetComponent()` that looks like this:

```
template<typename ComponentType>
ComponentType* Entity::GetComponent() {
    for(unsigned int i = 0; i < m_components.size(); i++) {
        if(ComponentType* cmp = dynamic_cast<ComponentType*>(m_components[i])) {
            return cmp;
        }
    }
    return NULL;
}

```

m\_components is a vector of `Component*` that looks like this:

```
std::vector<Component*> m_components;

```

My MovementComponent looks like this, and I get an error for some reason here:

```
void MovementComponent::MoveRight() {
    m_ContainingEntity->GetComponent<PositionComponent>()->x++; //I get the error at this line.
}

```

**Error:** undefined reference to \`PositionComponent\* Entity::GetComponent()'

What did I do wrong? I've got a feeling that the solution is really simple and that I just didn't pay much attention.

**Entity.h:**

```
#ifndef __ENTITY_H__
#define __ENTITY_H__

#include <vector>
#include <cstddef>

class Component;
class ECSManager;

class Entity {
public:
    void AddComponent(Component* cmp);

    template <typename ComponentType>
    ComponentType* GetComponent();

private:
    friend class ECSManager;
    std::vector<Component*> m_components;
};

#endif // __ENTITY_H__

```

**Entity.cpp:**

```
#include "Entity.h"
#include "Component.h"

void Entity::AddComponent(Component* cmp) {
    m_components.push_back(cmp);
    cmp->m_ContainingEntity = this;
}

template<typename ComponentType>
ComponentType* Entity::GetComponent() {
    for(unsigned int i = 0; i < m_components.size(); i++) {
        if(ComponentType* cmp = dynamic_cast<ComponentType*>(m_components[i])) {
            return cmp;
        }
    }
    return NULL;
}

```

**MovementComponent.h:**

```
#ifndef __MOVEMENTCOMPONENT_H__
#define __MOVEMENTCOMPONENT_H__

#include "Component.h"

class MovementComponent: public Component {
public:
    void MoveRight();
    void MoveLeft();
private:
};

#endif // __MOVEMENTCOMPONENT_H__

```

**MovementComponent.cpp:**

```
#include "MovementComponent.h"
#include "Entity.h"
#include "PositionComponent.h"

void MovementComponent::MoveRight() {
    m_ContainingEntity->GetComponent<PositionComponent>()->x++;
}

void MovementComponent::MoveLeft() {

}

```

# Answer
> 1 votes
Your template definition needs to be in the header file. More specifically:

```
template<typename ComponentType>
ComponentType* Entity::GetComponent() {
    for(unsigned int i = 0; i < m_components.size(); i++) {
        if(ComponentType* cmp = dynamic_cast<ComponentType*>(m_components[i])) {
            return cmp;
        }
    }
    return NULL;
}

```

should be in Entity.h

Explanation is here. The compiler needs to have access to the template implementations at the point where you're instantiating the method with PositionComponent as an argument.

# Answer
> 1 votes
Move the definition of Entity::GetComponent to the header, Entity.h. In general, template definitions must be put into header files. See this related question:

https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file

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


# Question
Title: Rotating a 3d vector around an axis using sines and cosines
I am trying to represent a 3d cone light's direction using only 2 variables. Right now I represent it with two points (6 variables) but I know that the direction in 3d space can be represented by two angles, rotating an arbitrary vector (e. g. pointing upwards) around two fixed axes step-by-step.

These calculations would be done in a shader, so I need a formula similar to the one in this question, that would allow me to perform such rotations. Could anyone suggest it?

UPDATE:

Following the Babis' answer I made a simple console project that computes phi and theta from two 3d points and then recomputes the normalized direction vector using the angles. However, the algorithm seem to always give me the wrong dir.Y value for some reason:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xna.Framework;

namespace DirectionIn2Angles
{
    class Program
    {
        static void Main(string[] args)
        {
            Vector3 first = new Vector3(1000, 1200, 85.245f);
            Vector3 second = new Vector3(1150, 85, 750);

            Vector3 distance = second - first;
            float length = distance.LengthSquared();
            distance.Normalize();
            Console.WriteLine(distance.ToString());

            float cosFSinY = distance.X;
            float sinFSinY = distance.Y;
            float cosF = distance.Z;
            float F = (float)Math.Acos(distance.Z);
            float Y = (float)Math.Asin(distance.X / distance.Z);

            float SinY = (float)Math.Sin(Y);
            float CosF = (float)Math.Cos(F);
            distance.X = CosF * SinY;
            distance.Y = (float)Math.Sin(F) * SinY;
            distance.Z = CosF;

            Console.WriteLine(distance.ToString());
            Console.ReadKey();
        }
    }
}

```

The values written in the console are:

x: 0,1147876; y:-0,8532547; z: 0,5087044

x: 0,1147876; y:0,1942689; z: 0,5087044

UPDATE:

This really is very wierd, I tried computing phi and theta using formulas from this article, but it now gives me the wrong dist.X! What could I be doing wrong?

UPDATE:

OK, that was just me being blind, I misread the formula. Here is the solution:

SOLUTION:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xna.Framework;

namespace DirectionIn2Angles
{
    class Program
    {
        static void Main(string[] args)
        {
            Vector3 first = new Vector3(1000, 1200, 85.245f);
            Vector3 second = new Vector3(1150, 85, 750);

            Vector3 direction = second - first;
            direction.Normalize();
            Console.WriteLine(direction.ToString());

            float CosYSinF = direction.X;
            float SinFSinY = direction.Y;
            float CosF = direction.Z;

            float F = (float)Math.Acos(direction.Z);
            float Y = (float)Math.Atan2(direction.Y, direction.X);

            float SinF = (float)Math.Sin(F);
            direction.X = (float)Math.Cos(Y) * SinF;
            direction.Y = SinF * (float)Math.Sin(Y);
            direction.Z = (float)Math.Cos(F);

            Console.WriteLine(direction.ToString());
            Console.ReadKey();
        }
    }
}

```

# Answer
> 1 votes
A normalized direction is a point on the unit sphere, so you need 2 angles. I assume you have a coordinate system where Y is up. Your two variables are phi (0 \<= phi \<= pi) and theta (0 \<= theta \<= 2pi). You obtain the normalized direction vector as follows:

```
dir.x = cos(theta)*sin(phi)
dir.y = cos(phi)
dir.z = sin(theta)*sin(phi)

```

Source for more info here, look up "Equations in R^3"

---
Tags: mathematics, rotation, vector
---


# Question
Title: What is the best practice for handling touch events on different GameObjects in Unity2D?
First of all I want to describe what I have in my scene. 1. Joystick. 2. Main character that has link to joystick and handles touch events from joystick. 2. Buttons. 3. Other GameObjects that must handle touch events.

But that's not all. When player is touching any part of screen **(except of the above objects)** main character must start fighting. The problem is in that I cant correctly handle all touch events on these game objects. When the player is touching to the joystick the main character starts moving but before this he is performing a single fight action. Can anyone give me some ideas how to correctly handle touch events on different gameobjects? Perhaps my question is confusing, I am sorry for this.

# Answer
You have to route the input by priority or z-order. First check HUD or GUI elements (on top) and the actual world ground at last (beneath). If a valid touch target is found/hit then you have to consume the input ond *not* routing it any further.

Think of it as layers, for example

```
[Touch] -> [Button] -> [Character] -> [Ground]

```

Every touch will at least hit the ground. When a touch event occurs you start start with all GUI elements like buttons. If no button was hit then you check all characters and then where on the ground the touch hit the level.

If a button was hit you trigger its action and do *not* check the others (characters and ground). The input is consumed by the first object being hit.
> 2 votes

# Answer
If your touchables overlap, what you are "touching" is ambiguous unless you process the input by the z-order or user-defined precedence of the touchables (Code Clown's solution). You would have to handle this ordering of touch event receivers in a higher level of your code so that the touch event can be stopped by the first receiver in the hierarchy.

The simpler solution is to just not let your touch zones overlap. Instead of reacting immediately to the "touch begin" event on the full screen zone, check to see if the coordinates of the touch overlap any other touchables. If they do, then this isn't an event that your full screen zone should respond to.
> 1 votes

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


# Question
Title: Why does this code not update my object's position?
I am trying to move the object in my frame in `Time.deltaTime`. I have not taken care the speed yet but the problem is, the object is almost at position (0,0) after I have multiplied the x & y axis with Time.deltaTime. I want it to appear randomly on the screen in a given range. The update function is given below:

```
function Update ()
{

  var x = Random.Range(-4.37,4.34) * Time.deltaTime;

  var y = Random.Range(4.45,-4.66) * Time.deltaTime;

  var velocity = Vector3(x, y, 0);

  transform.position = velocity;

}

```

# Answer
> 0 votes
You're setting your position equal to your velocity. Your velocity is very small because it's multiplied by delta time. This results in very small changes to your position, constrained to a very small area. Your object is moving, it's just not noticeable because the changes are so small. Additionally, all the small changes are not adding up because you're setting the position each time, instead of adding to it.

What you really want is to change your position with respect to time.

```
var x = Random.Range(-4.37,4.34);
var y = Random.Range(4.45,-4.66);
var velocity = Vector3(x, y, 0);
transform.position += velocity * Time.deltaTime;

```

This creates a random velocity, then changes the position of the object based on that velocity.

EDIT

Sorry I misread your question. I saw your velocity variable and thought you wanted to move the object over time. But your description says you want it to appear at random locations. Simply change this line: `transform.position += velocity * Time.deltaTime;` to `transform.position = velocity;` To make it appear at a random location (I'd also suggest renaming the variable from `velocity`, because that indicates a change in position over time).

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


# Question
Title: Replace each white spot of image to radial gradient
Recently, I read an article about a sun shader (XNA Sun Shader) and decided to implement it using OpenGL ES 2.0, but I encountered a problem with the shader:

I have two textures, one of them is the fire gradient texture:

The other one is a texture which will have each white part filled using the gradient;

So, I'm going to have a result similar to the image below (do not pay attention to the texture being rendered on a sphere mesh):

I really hope that somebody knows how to implement this shader.

**As an alternative, how do I make it in photoshop?**

# Answer
> 3 votes
If the source image is bi-level (1-bit black/white), a direct mapping of greyscale to gradient will not suffice.

A possible solution to the problem is to compute a distance field (preferably as an offline task), where each texel encodes the distance to the nearest white texel. You can then use that distance to sample the gradient map.

The images below show a source image and a corresponding signed distance field I had lying around:

# Answer
> 1 votes
As the article states, in the shader you use the luminance value (between 0 and 1, or between black and white) to index the "fire" texture horizontally. This should give you the color that the pixel shader returns:

1. Index the noise texture. This returns a grey color
2. Take any component from the grey color (r, g and b should be the same)
3. Use that value to index the fire texture as x, with y being any value (e.g. 0.5)
4. Return the color from the fire texture

If you're not going to use the addition technique the article describes, it would make more sense to bake the reds and yellows into the texture, so you can save some GPU cycles. I'm not sure how to do this with the Photoshop noise generator, but I suppose you could always draw the edges by hand :)

---
Tags: shaders, opengl-es2
---


# Question
Title: If I release code under GPLv3, can I specify what parts of users' code can be released under a new license?
I have a few questions about what users of my engine could copyright in their own project. The way the engine would work would be that it would be a standalone program in Java that would load all of the scripts/assets/data from a folder that the game takes place in. The code could be written in Python or compiled to Java.

Onto my questions, the code that they write would access some parts of my engine through Jython, and so I assume those would have to be released under the GPL. But what about the rest of the game other than the code? Like could they copyright their own art?

I guess what I really want is that modifications of the code of the engine must be released under the GPL, but projects created using my engine can be released under any copyright, as long as they obey they distribute the engine itself under the GPL.

# Answer
No.

The GNU Public License is intentionally a *viral license*, which means *derivative works* must be distributed under the GPL also. Using your code as a library is a derivative work. Hence users of your game engine would need to release their game under the GPL also.

If you want to let your users choose a different license for their derivative work, but otherwise keep your code (and *modifications* to it) under a similar license, maybe you'd prefer the Lesser GNU Public License?

(IANAL.)
> 1 votes

# Answer
> the code that they write would access some parts of my engine through Jython, and so I assume those would have to be released under the GPL

I do not understand what makes you think so. Jython is *not* covered by GNU GPL and never was; its current release is under terms of Python Software Foundation License, which seems to be a lax permissive non-copyleft license, so just by using Jython you are not obliged to apply any specific license to your project (you even could make it non-free/proprietary).

According to your description:

> ...what I really want is that modifications of the code of the engine must be released under the GPL, but projects created using my engine can be released under any copyright...

the license that you really want apply to your work is GNU *Lesser* GPL.
> 1 votes

---
Tags: legal, licensing
---


# Question
Title: Yeild waitForSeconds(5.0) is not working
I am trying to call another function continuously from my Update() function. So, I have used yield WaitForSeconds(5.0); but, the it stops for the first 5 seconds and it does not stop the next time it goes inside the movement function. Basically, I want to stop for 5 seconds before every movement.

```
function Update ()
{
    movement();
}

function movement()
{

    yield WaitForSeconds(5.0);
    //some blocks of code

}

```

Thank you.

# Answer
In your code, movement() is being called every single update resulting in repeatedly calls completing after the first five seconds - this is not what you want. You want to call movement once and have movement repeat itself. There might be a better pattern which if someone else can show would be great, but something like the following should work and get you pointed in the right direction -

**JavaScript:**

```
function Start () {
    StartCoroutine("movement");
}

function movement() {
    while (true) {
        yield WaitForSeconds(5.0);
        // some blocks of code
    }
}

```

**C#:**

```
void Start()
{
    StartCoroutine("movement");
}

IEnumerator movement()
{
    while (true) {
        yield return new WaitForSeconds(5.0f);
        //some blocks of code
    }
}

```
> 1 votes

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


# Question
Title: Insufficient memory on creating vertex buffers
I'm building a voxel world generator with XNA where the voxels are rendered as polygonal cubes. The world is divided into 1024 chunks of 32x32x256 cubes each (as 32 chunks by 32 chunks), and each chunk has its own index and vertex buffer. Since each chunk is different, vertex buffer size is determined on runtime.

To prevent massive stalling on opening the program, only one chunk is re-built per frame until all chunks are built. Occasionally the program crashes with an "insufficient memory" related error that is caused by the line that creates the vertex buffer. Here is how I set them up:

```
 vb = new VertexBuffer(
      device,
      VertexPositionColorNormal.VertexDeclaration,
      nextIndex,
      BufferUsage.None
 );

 ib = new IndexBuffer(
      device, IndexElementSize.ThirtyTwoBits,
      nextIndex,
      BufferUsage.None
 );

```

My vertex structure is not very large, using only a Vector3 for position and Byte4 for color and normal lookup info:

```
public struct VertexPositionColorNormal : IVertexType
{
    public Vector3 Position;
    public uint Data;

    public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
        new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement(12, VertexElementFormat.Byte4, VertexElementUsage.TextureCoordinate, 0)
    );

    VertexDeclaration IVertexType.VertexDeclaration { get { return VertexDeclaration; } }
}

```

NextIndex is the number of vertices and indices allocated to the buffers (always 1 index per vertex).

Am I making too many buffers? It crashes despite the GC showing only about 12 MB of usage so I guess memory fragmentation is a problem when creating lots of buffers in a short time? Should I use a smaller amount of buffers that store more data and have several chunks share them?

EDIT: I estimate roughly 0.75 to 1 GB of memory used in the vertex buffers. My graphics card has 2GB of VRAM. Though I also know sometimes not all the vertex data may be stored in VRAM at one time.

# Answer
I've never had this problem before, but I've also noticed you're using `BufferUsage.None`. This enum has two possible states: `None` and `WriteOnly`. In all my coding, I've always used `WriteOnly`.

From the documentation for BufferUsage, it states that `WriteOnly` does the best memory location for writing/rendering, but the downside is you can't read the data from the buffer. It might be worth while trying out `WriteOnly`, and seeing if it solves the problem, especially if you don't plan on reading from the buffers.

Your Vertex Declaration also looks odd, using a `uint` to store Color and Normal data. I dunno what your reasons behind this is, but because its not the standard way of doing it, it might be causing a problem. My VertexPositionNormalColor is usually set up like this. Don't think its likely, but I know from experience how an innocent looking line of code can be a major bug monster.

Lastly, in the creation of both vertex and index buffers, you seem to be assuming that the vertexCount = indexCount. Don't know what circumstances would cause this to be true unless you're rendering a triangle.

Another possibilty is that during the creation of your VertexBuffer, you are hitting the internal limit. I know from previous experience with terrain generated from a heightmap that VertexBuffers will only hold so many elements. There is the possibility (especially if your voxels are generated at run time dynamically) that one chunk has a few too many voxels in it.

A good way to test this cause would be to bump your game world down to 512 chunks, and then test repeatedly to see if the error occurs.

**EDIT:**

I've had a bit of a look around, and this link here might offer an explanation. They are reporting a near identical error (might actually be the same given the age of the thread and changes in C#/the XNA API), and have a discussion about VRAM memory allocation with multiple vertex buffers.

Chances are, you try to create a VertexBuffer in VRAM, but there isn't a free block big enough to store it, and your application errors with an 'InsufficentMemory' exception. You can work around this by creating smaller VertexBuffers by reducing the complexity of the data in them or creating fewer VertexBuffers by increasing the size of your chunks so each buffer gets allocated more fairly in VRAM.

**Further explaination:**

Note that memory allocation for object is random, so if it finds a large enough chunk of free memory, it'll store it in there somewhere. This means you could have 256MB of memory free in total, and have a 64MB object to store, but your largest free chunk is 32MB. Even though the total memory exceeds the size of your object, the largest free chunk that we could use is smaller than the requested object size, so we report an OutOfMemory or InsufficentMemory error (or something similar) to the application
> 3 votes

---
Tags: xna, graphics, vertex-buffer
---


# Question
Title: How can a team work together to assemble a large world map?
I recently played a open world FPS game with a large and dense game world, in a single map like this.

It contains many objects, roads, rivers, trees, houses, rocks, hidden places, NPCs, etc... all carefully placed relative to each other. The game was made in two years (which is pretty fast regarding the content).

How can a team work at the same time on such a huge map?

3D models and textures can have been done separately and in parallel as I understand. The question is about how to put all this content on the map and model the map itself (lowering or raising some parts since it is a huge heightmap).

---

Several things solutions I have in mind:

* The map could be divided into big chunks, with each person (or small team) working on a small part. Then (at the end) everything is reassembled. I seriously doubt this, because of the map topology. Or maybe the height of the map was fixed first (no more change possible after some point), then map cut in squares, then reassembled (which would work because height was not changed).
* Developers created a multi user editor where it is possible to connect to a server (using LAN) then any change in editor would be directly visible and propagated to other editors connected to the same server. Something like Minecraft.

How can this be done? Has anybody worked on a similar game?

# Answer
> 1 votes
What can be done with many engines out of the box is to:

1. Settle down the heightmap for the whole world, as you usually cannot split this one up easily
2. Use layers to divide the entities into well encapsulated sets (e.g. road network, buildings of city1, buildings of city2, npcs of city1, ...) and save layers in separate files (CryEngine does that, other probably as well). Make sure non-modified layers are not saved.
3. Make sure there is clean ownership of layers so that people don't mess up other's work. Having the format in XML or something version-control friendly helps, as noted in the comment to the original question by david van brink.

---
Tags: first-person-shooter, heightmap, map-editor, teamwork
---


# Question
Title: Implementing monte-carlo tree search in a tile based game with units
I have this simple risk-like game I would like to develop an AI for. `Players` move their `Units` on the map and a simple fight resolution is done. There is a time constraint of 100ms for each round, the AI has complete information and fight resolution is deterministic but units move simultaneously each round.

As far as I understand the monte carlo approach, I need to copy the state of a current round and generate a tree with new game states, play it out randomly or do an evaluation.

Currently my `zones` keeps a list each `unit` and they're moved around by storing `orders`. They're kept in a dictionary for each turn and are applied at the end of the round. Deep copying this takes around 3ms and I guess is too slow to use effectively considering the time constraint. I was wondering if I could use this order-system to generate the tree faster by applying and undoing them, but I can't yet wrap my head around how I would do it.

This is my current class design:

How can I effectively add MCTS for this kind of game?

# Answer
> 1 votes
In my experience with AI planning, copying the state was indeed very slow and your suggested idea (maintaining a single copy of the state and undoing the actions when you go "up the tree") worked much better. But that really depends on the size of your state and language you use: in C++ you could probably use custom allocators to fit the whole state into a continuous block of memory which would be copied extremely quickly with memcpy. Copying into preallocated memory/objects also helps a lot.

If copying state is slow even with preallocation, the simplest solution would probably be to add a `OrderUndo` interface and every `Order` implementation would have a `createUndo()` method to produce the undo instance. The implementations of `OrderUndo` would then preserve a minimal subset of the game state (different orders result in different modification of state, hence the polymorphism) and they would have an `apply()` method that would restore the particular part of state.

Upon search, you simply execute orders and put undo's on a stack and when traversing back apply the undo's on top of the stack.

For speed you should also preallocate memory / create an object pool for the undo objects (memory allocation tends to be veeeery slow regardless of language). So the `createUndo` method would have a signature similar to `createUndo(UndoPool pool)`.

# Answer
> 0 votes
The simplest method is to implement a "copy" primitive. Copy the game at the root of the search and run forward using the existing machinery. Repeat.

---
Tags: architecture, ai, python
---


title: Developing game progress screen

text:
# Question
Title: Developing game progress screen
I'm developing an application for iPhone with a screen where the user will track his progress. Something like so, as seen in the Two Dots game:

Currently I plan on creating this using constraints and size classes. But I feel its too much of work for each screen size. I've set a background `UIImageView` and I place different circles, manually hardcoding the position. The curved path in my case is made of a texture. So I can't plot it using Bezier Curves either.

Is there an easier way to do it? Perhaps using SpriteKit or Cocos2D-x?

# Answer
I am not familiar with SpriteKit, or Cocos2D, so I can't answer that question. However you should be able to accommodate any screen size if you use percentages. If you calculate the percent of pixels where each circle is placed in regards to your original image, you can use this value to calculate the placement of each marker in the target resolution.

For example, in the image you posted, the top left corner of circle 35, looks to be at (roughly) 55% of the screens width, and 45% of the screens height. If these values are accurate, you can calculate the screen position in any resolution very easily.

```
x = screenWidth * circlePositionWidthPercantage;
y = screenHeight * circlePositionHeightPercantage;

```
> 0 votes

---
Tags: ios, iphone, levels, spritekit
---


# Question
Title: How can I make sure custom XNA content processors find included files with relative paths?
MSDN has an example of a custom HLSL effect importer and processor. Here is the importer's code:

```
public override PSSourceCode Import(string filename,
    ContentImporterContext context)
{
    string sourceCode = System.IO.File.ReadAllText(filename);
    return new PSSourceCode(sourceCode, System.IO.Path.GetFileNameWithoutExtension(filename));
}

```

In the processor they do this:

```
    EffectContent effectSource = new EffectContent();
    effectSource.EffectCode = input.SourceCode;
    EffectProcessor processor = new EffectProcessor();
    compiledEffect = processor.Process(effectSource, context);

```

The sample works okay, however, when you try to import and process an effect file that has `#include "otherEffect.fx"` directive in it, the build process throws an error "Failed to open source file 'otherEffect.fx'". I presume that is because the relative path of the file is not specified correctly but I don't know where to specify it. Does anyne know this?

# Answer
> 1 votes
For those having the same trouble, you should add two lines in the processor:

```
EffectContent effectSource = new EffectContent();
effectSource.EffectCode = input.SourceCode;
//Add these two lines:
effectSource.Identity = new ContentIdentity();
effectSource.Identity.SourceFilename = input.name;
//End of correction
EffectProcessor processor = new EffectProcessor();
compiledEffect = processor.Process(effectSource, context);

```

---
Tags: xna, xna-content-pipeline
---


# Question
Title: Why should I use separate initialization and clean up methods instead of putting logic in the constructor and destructor for engine components?
I'm working on my own game engine, and I am currently designing my managers. I've read that for memory management, using `Init()` and `CleanUp()` functions are better then using constructors and destructors.

I have been looking for C++ code examples, to see how those functions work and how I can implement them into my engine. How does `Init()` and `CleanUp()` work, and how can I implement them into my engine?

# Answer
It's pretty simple, actually:

Instead of having a Constructor which does your setup,

```
// c-family pseudo-code
public class Thing {
    public Thing (a, b, c, d) { this.x = a; this.y = b; /* ... */ }
}

```

...have your constructor do little or nothing at all, and write a method called `.init` or `.initialize`, which would do what your constructor would normally do.

```
public class Thing {
    public Thing () {}
    public void initialize (a, b, c, d) {
        this.x = a; /*...*/
    }
}

```

So now instead of just going like:

```
Thing thing = new Thing(1, 2, 3, 4);

```

You can go:

```
Thing thing = new Thing();

thing.doSomething();
thing.bind_events(evt_1, evt_2);
thing.initialize(1, 2, 3, 4);

```

The benefit there is that you can now use dependency-injection/inversion-of-control more-easily in your systems.

Instead of saying

```
public class Soldier {
    private Weapon weapon;

    public Soldier (name, x, y) {
        this.weapon = new Weapon();
    }
}

```

You can build the soldier, give him an equip method, where you *hand* him a weapon, and THEN call all of the rest of the constructor functions.

So now, instead of subclassing enemies where one soldier has a pistol and another has a rifle and another has a shotgun, and that's the only difference, you can just say:

```
Soldier soldier1 = new Soldier(),
        soldier2 = new Soldier(),
        soldier3 = new Soldier();

soldier1.equip(new Pistol());
soldier2.equip(new Rifle());
soldier3.equip(new Shotgun());

soldier1.initialize("Bob",  32,  48);
soldier2.initialize("Doug", 57, 200);
soldier3.initialize("Mike", 92,  30);

```

Same deal with destruction. If you have special needs (removing event listeners, removing instances from arrays/whatever structures you're working with, etc), you would then manually call them, so that you know exactly when and where in the program that was happening.

**EDIT**

---

As Kryotan has pointed out, below, this answers the original post's **"How"**, but doesn't really do a good job of a "Why".

As you can probably see in the answer above, there might not be much of a difference between:

```
var myObj = new Object();
myObj.setPrecondition(1);
myObj.setOtherPrecondition(2);
myObj.init();

```

and writing

```
var myObj = new Object(1,2);

```

while just having a larger constructor function.
There is an argument to be made for objects which have 15 or 20 pre-conditions, which would make a constructor very, very hard to work with, and it would make things easier to see and remember, by pulling those things out into the interface, so that you can see how the instantiation works, one level higher.

Optional-configuration of objects is a natural extension to this; optionally setting values on the interface, before making the object run.
JS has some great shortcuts for this idea, which just seem out of place in stronger-typed c-like languages.

That said, chances are, if you're dealing with an argument list that long in your constructor, that your object is too big and does too much, as is. Again, this is a personal-preference thing, and there are exceptions far and wide, but if you're passing 20 things into an object, chances are good that you could find a way to make that object do less, by making smaller objects.

A more-pertinent reason, and one which is widely-applicable would be that the initialization of an object relies on asynchronous data, which you don't have, currently.

You know that you need the object, so you're going to create it anyway, but in order to have it function properly, it needs data from the server, or from another file which it now needs to load.

Again, whether you're passing the needed data into a gigantic init, or building out an interface isn't really important to the concept, so much as it's important to the interface of your object, and the design of your system...

But in terms of building the object, you might do something like this:

```
var obj_w_async_dependencies = new Object();
async_loader.load(obj_w_async_dependencies.async_data, obj_w_async_dependencies);

```

`async_loader` might get passed a filename, or a resource name or whatever, load that resource -- maybe it loads sound files, or image data, or maybe it loads saved character stats...

...and then it would feed that data back into `obj_w_async_dependencies.init(result);`.

This sort of dynamic is found frequently in web-apps.
Not necessarily in an object's construction, for higher-level applications: for example, galleries might load and initialize right away, and then display photos as they stream in -- that's not really an async-initialization, but where it's seen more frequently would be in JavaScript libraries.

One module might depend on another, and so the initialization of that module might be deferred until the loading of the dependants is complete.

In terms of game-specific instances of this, consider an actual `Game` class.

Why can't we call `.start` or `.run` in the constructor?
Resources need to be loaded -- the rest of everything has pretty much been defined and is good to go, but if we try running the game without a database-connection, or without textures or models or sounds or levels, it's not going to be a particularly interesting game...

...so what, then is the difference between what we see of a typical `Game`, except that we give its "go ahead" method a name which is more interesting than `.init` (or conversely, break the initialization even further apart, to separate loading, setting up the things which have been loaded, and running the program when everything has been set up).
> 12 votes

# Answer
Whatever you read that said Init and CleanUp is better, should have also told you why. Articles that don't justify their claims are not worth reading.

Having separate initialisation and shutdown functions can make it easier to set up and destroy systems because you can choose what order to call them in, whereas constructors get called exactly when the object is created and destructors called when the object is destroyed. When you have complex dependencies between 2 objects you often need them both to exist before they set themselves up - but often this is a sign of poor design elsewhere.

Some languages don't have destructors that you can rely on, since reference counting and garbage collection make it harder to know when the object will be destroyed. In these languages you almost always need a shutdown/cleanup method, and some like to add the init method for symmetry.
> 17 votes

# Answer
I think the best reason is : to allow pooling.
if you have Init and CleanUp, you can, when an object is killed, just call CleanUp, and push the object onto a stack of object of the same type : a 'pool'.
Then, whenever you need a new object, you can pop one object from the pool OR if the pool is empty -too bad- you have to create a new one. Then you call Init on this object.
A good strategy is to pre-fill the pool before the game begins with a 'good' number of objects, so you never have to create any pooled object during the game.
If, on the the other hand, you use 'new', and just stop referencing an object when it is of no use to you, you create garbage that must be recollected at some time. This recollection is especially a bad thing for single-threaded languages like Javascript, where the garbage collector stops all the code when it evaluates it needs to recollects the memory of the objects no longer in use. The game hangs during a few milliseconds, and playing experience is spoiled.
\- You allready understood - : if you pool all your objects, no recollection happens, hence no more random slow-down.

It is also much faster to call init on an object coming from the pool than to allocate memory + init a new object.
But the speed improvement has less importance, since quite often object creation is not a performance bottleneck... With a few exceptions, like frantic games, particle engines, or physic engine using intensively 2D/3d vectors for their computations. Here both speed and garbage creation are greatly improved by using a pool.

Rq : you might not need to have a CleanUp method for your pooled objects if the Init() resets everything.

Edit : replying to this post motivated me to finalize a little article i made about pooling *in Javascript*.
You can find it here if you're interested :
http://gamealchemist.wordpress.com/
> 3 votes

# Answer
Your question is reversed... Historically speaking, the more pertinent question is:

**Why *is* construction + intialisation conflated, i.e. why *don't* we do these steps separately? Surely this goes against SoC?**

For C++, RAII's intent is that resource acquisition and release be tied directly to object lifetime, in the hopes that this will assure resource release. Does it? Partly. It is 100% fulfilled in the context of stack-based / automatic variables, where leaving the associated scope automatically calls destructors / releases these variables (hence the qualifier `automatic`). However for heap variables, this very useful pattern sadly breaks down, since you are still forced to explicitly call `delete` in order to run the destructor, and if you forget to do so you will still be bitten by what RAII attempts to solve; in context of heap-allocated variables, then, C++ provides limited benefit over C (`delete` vs `free()`) while conflating construction with initialisation, which negatively impacts in terms of the following:

Building an object system for games / simulations in C is strongly recommended in that it will shed a great deal of light on the limitations of RAII and other such OO-centric patterns through a deeper understanding of the assumptions that C++ and later classical OO languages make (remember that C++ started out as a an OO system built in C).
> 0 votes

---
Tags: architecture, software-engineering
---


title: Float increment give wrong result

text:
# Question
Title: Float increment give wrong result
I found something weird with my unity code :

```
public class heroesscript : MonoBehaviour {

    float counter = 0;

    void FixedUpdate()
    {
        counter += 0.02f;
        print (counter);
    }
}

```

When I'm executing this code, I get this in my console :

* 0.2
* 0.4
* 0.6
* 0.8
* 0.9999999

Anybody can explain this? How to avoid this?

# Answer
It's simply a floating point precision error and the reason why you shouldn't use `float` whenever you really care about precision (and try to avoid using direct comparison with them). Use `double` instead (but it has limited precision as well!).
> 2 votes

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


# Question
Title: How do I resolve asynchronous client actions against an authoritative server state?
I have a multiplayer card game which I am in the process of developing.

The game is relatively simple; players have a certain number of cards which they can activate, sell, or use in various other ways.

The game isn't turn based. Instead, it is asynchronous so that players (**A**, **B**, **C**, and **D**) all make their choices at the same time. Certain actions will affect the game state. For example, removing a card from the game or adding a card to the game. Players should always be in sync with each other so that, for instance, **Player A** cannot use a card that **Player B** has just removed, as it is no longer present.

Obviously there are situations in which **Player A** may remove a card at nearly the same time that **Player B** tries to interact with the same card. *How would the server handle this sort of situation?*

My original thought is that each client could hash their game state and send it with their command to the server, for example:

**Player A** \- #MYHASH# - Command = Pick Up Card Z

**Player B** \- #MYHASH# - Command = Remove Card Z

The server would then action the first command and regenerate the hash. Upon trying to execute the second command it would notice the hash sent by **Player B** differs from the current hash, so the server would reject the request.

In the above example **Player A** would notice nothing and the game would continue normally, but **Player B** would have to be informed that their action failed.

# Answer
> 2 votes
A hash of the state is the right general idea, but the wrong specific implementation; two different states could hash to the same value, and while that might be a rare occurrence (depending on your hash algorithm), it's still a case you want to handle.

Instead, consider a sequence ID. A sequence ID starts at some initial value and is updated by the server after every validated change to the game state. When the server sends an update to all clients, part of that update includes the new state sequence ID. When the client sends a request to change something to the server, it includes the sequence ID that goes along with the state it currently has.

When the server gets a request from the client, if the included client sequence ID is not the same as the current sequence ID, the update is rejected because the client had a stale state; the server should inform the client (along with the new state and sequence ID). Otherwise the server accepts the move, updates its state and sequence ID, and broadcasts the change to all clients.

Obvious this update on the server has be synchronized, but that's true anyway since you're modifying the game state anyhow.

The downside to this approach is that the client cannot dispatch multiple state change requests to the server; after sending one, it has to wait to get confirmation and a sequence ID update. There are several solutions to this, but I think the ideal solution is to simulate the successive moves locally as if the server said "yes" to everything, but keep them queued in memory. As the server confirms each move, send the next queued action until the server state catches up with the client. If at any point you get a response from the server that wasn't a confirmation of that client's own action (that is, an update from another client), discard the remaining queued up actions and resynchronize the game state, displaying an appropriate error message to the user if needed.

This system can be used as the basis for fault-tolerate (that is, crash-tolerant) persistence systems as well -- if you have a storage backend with transactional guarantees, like a database, you can persist update requests and sequence IDs and be able to resume the same sequence of transactions after a crash. It can allow for idempotent operations, also; what I've described is a simplified view of the basis for item transfer systems in the MMOs we build where I work.

# Answer
> 3 votes
Just send in the commands. If B asks for a card that A already took, the server can send a YoureOutOfLuck event in response. That simple.

Your bigger worry is the UI. You need to immediately provide feedback for clicks, but have to wait to do any real action until confirmation. Making a good click effect that is not too long/annoying but gives enough time for typical RYT/acknowledgement is tricky.

# Answer
> 0 votes
You'd want to check out optimistic locking.

For a practical implementation, if you are using HTTP for your communication, check out how HTTP uses ETag and If-Match HTTP header for conflict detection. If you don't use HTTP for your communication or if you use HTTP only as an envelope to your own request, try to base your design like ETag and If-Match.

In your particular situation, what would happen is that the server should attach an entity tag representing the game state to all game state updates that are sent to the client. The client would then have to attach the received tag in its move requests, the server checks that if the tag in the request does not match the current gamestate tag, then the request is refused; if the tag matches the current gamestate hash, the request is processed by the server and an update is pushed to all clients who will then have to update their game state and tag. If the client's request is refused then the refused client will also update its game state and tag, but also inform the user that they cannot do the requested action.

To calculate an entity tag, you can use a hash of the gamestate, a random number, or a sequence number as long as you generate it consistently. The advantage of a hash is that you don't need an extra database field to store the tag as you can easily regenerate it from the current game state. Whichever method you choose shouldn't matter for the client, since the entity tag is opaque for the client.

---
Tags: server, client-server
---


# Question
Title: Are there such things as online development projects?
I would like to practice a bit as a programmer in the gaming field but know of no one making games in my proximity. I was wondering if there is an online community or something where people look for other developers for their projects? I mean as in simple independent stuff, not paid of course, it would be just to get practice and maybe be able to complete something. Any pointer appreciated.

# Answer
A well-known community to bring programmers together is GitHub.

It is primarily a website to host Git repositories for open source projects, but makes it easy to collaborate by allowing to create forks of the projects of other people and then offering them to pull the improvements you made.

It is not only a community specifically for *game* programmers, but I know several open source game projects which collaborate via GitHub.
> 1 votes

---
Tags: software-engineering, project-management
---


title: Lua Implementation

text:
# Question
Title: Lua Implementation
I'm struggling to get Lua implemented into my game engine. I've read dozens of blogs and articles revolving around how to wrap C++ classes and I seem to have hit a wall. No matter how I structure the code I can't figure out a logic path that doesn't involve creating global variables in my project so the Lua helper functions can access the core of my engine.

Let me start off by explaining the end goal. I want to have an `entities` folder which holds scripts that describe unique spawnable entities within the game. A typical file would look like this:

```
function ENTITY:Initialize()
    --Do stuff when the entity is initialized
    self:SetModel("models/2x2x2-plate.obj")
    self:SetPosition(Vector3D(100,100,100))
end

function ENTITY:Think()
    --Do stuff every time the entity thinks
    self:SetVelocity(Vector3D(0,0,100))
end

```

The file name of this .Lua file would be a unique identifier to create an entity of this type from within other scripts.

```
local MyEnt = Entities.Create("MyCustomEntity")
MyEnt:Spawn()

```

What would seem like an easier way to accomplish this task would be to set it up so scripts look like this:

```
Entities.Add( "MyCustomEntity", {
    PrintName = "My Custom Entity",

    Initialize = function( self )
        --Do stuff when the entity is initialized
        self:SetModel("models/2x2x2-plate.obj")
        self:SetPosition(Vector3D(100,100,100))
    end,

    Think = function ( self )
        --Do stuff every time the entity thinks
        self:SetVelocity(0,0,100)
    end
} )

```

However I feel like I would loose some functionality if it were setup like that.

On the C++ side of things a class called BaseEntity would be where these entity scripts would inherit all their functions from.

I've been able to figure out the following on my own so far

```
#include <lua.hpp>
#include "LuaActor.h"
#include "BaseActor.hpp"

BaseActor* Check_BaseActor(lua_State* L)
{
    luaL_checktype(L, 1, LUA_TUSERDATA);
    return (BaseActor*)reinterpret_cast<BaseActor*>(lua_touserdata(L, 1));
}

int LuaActor_Create(lua_State* L)
{
    BaseActor** Actor = (BaseActor**)lua_newuserdata(L, sizeof(BaseActor*));
    *Actor = new BaseActor();
    luaL_getmetatable(L, "Actors");
    lua_setmetatable(L, -2);

    return 1;
}

int LuaActor_Destroy(lua_State* L)
{
    // Do something when Actor is removed from the lua environment
    BaseActor* Actor = Check_BaseActor(L);
    return 0;
}

int LuaActor_SetIndex(lua_State* L)
{
    BaseActor* Actor = Check_BaseActor(L);

    luaL_checktype(L, 2, LUA_TNUMBER);
    const int Index = lua_tointeger(L, 2);
    Actor->SetIndex(Index);

    return 0;
}

int LuaActor_GetIndex(lua_State* L)
{
    BaseActor* Actor = Check_BaseActor(L);

    lua_pushnumber(L, Actor->GetIndex());

    return 1;
}

static const luaL_reg LuaActor_Funcs[] =
{
    { "Create", LuaActor_Create },
    { NULL, NULL }
};

static const luaL_reg LuaActor_Methods[] =
{
    { "__gc", LuaActor_Destroy },
    { "SetIndex", LuaActor_SetIndex },
    { "GetIndex", LuaActor_GetIndex },
    { NULL, NULL }
};

void Register_LuaActor(lua_State* L)
{
    luaL_newmetatable(L, "Actors");
    lua_pushstring(L, "__index");
    lua_pushvalue(L, -2);
    lua_settable(L, -3);

    luaL_openlib(L, 0, LuaActor_Methods, 0);
    luaL_openlib(L, "Actors", LuaActor_Funcs, 0);
}

```

This gives me the ability to do things such as `local MyActor = Actors.Create()`

I can't find any information about doing what I described in the 2nd paragraph. I also understand that I should let the garbage collector manage deletion of any C++ objects created through Lua which confuses me on how I should track my entities on the C++ side. I have an `ActorHandler` class which holds a `std::vector` of all my entities. This class loops through each entity every game tick calling their `Update()` functions, the entities are also accessed from other classes such as physics and networking via their unique entity id's to apply positional and collision updates. I am very confused on how I should keep track of entities on the C++ side which were created on the Lua side and still be able to call their Lua callback functions from within C++.

I've found out that you can create references to your Lua objects within C++ to quickly access the Lua object again but I can't find any articles describing how to advantageously use this feature.

Any help would be greatly appreciated and I can give more information if needed.

# Answer
> 3 votes
This is not exactly an answer - rather a suggestion. A lot of game developers are shifting from LUA (it is slow and it forces you to push data back and forth). For example Star Citizen is using Runtime compiled C++ (actually they use Kythera which runs RCC++). RCC++ lets you script in C++ and reload your modified code on the fly, which - I guess - would solve a lot of your issues. I however have no first hand experience with RCC++.

In my workplace, we are trying to keep LUA usage at minimum and we use our custom behavior tree implementation for most of the work (and we are getting some very nice performance results)

**EDIT:** To answer the comments, RCC++ is probably not a good solution if you want to support game mods. I reiterate that I have no first hand experience with RCC++. The main point is still that there are alternatives to LUA, which may be better for many use cases. Another example is Unity's support for C# as scripting language - it is often faster to execute than LUA and strong typing and existence of ready made tools let's you bring developer support to a next level (code completion, refactoring, ...).

# Answer
> 0 votes
> No matter how I structure the code I can't figure out a logic path that doesn't involve \> creating global variables in my project so the Lua helper functions can access the core \> of my engine.

That's *basically* inevitable, given the required signature of functions registered to the Lua API. Data can only get in to the scope of a free function body via globals or function arguments. What I do to get around this, or at least make myself feel better, is to use Lua upvalues, or the Lua registry, to store C-side data that I want to pass to my bound Lua functions.

That said, the rest of the question is too broad to answer, as I address in my article about binding Lua to C++. Bi-directional binding is very complex to do in any useful way. So, I wouldn't recommend reinventing the wheel. Let someone else play in the dirt.

From a functionality perspective, Luabind is pretty much the best, in my experience, but it comes at a hefty price of performance on all fronts. Slow compiles and slow bound code.

OOLua is also very good. Faster compiles than LuaBind, better performance, but it doesn't swing both ways, only C++ -\> Lua.

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


# Question
Title: Make camera move constantly upwards in box2d world
Im using libGdx to develop a 2d game, which has the following:

* The world moves in an upward direction by having a camera follow the player's y position.
* The user only controls player's x movement, the y is a constant speed.

What i want to do now is let the user control the players x and y movement and let the camera move constantly up without following the player.

What is the best way to do this?

This is what i tried:

in Render()

```
player.body.setTransform(fingerPosition.x, fingerPosition.y, player.body.getAngle());

box2dCamera.position.y = box2dCamera.position.y + cameraSpeed;
box2dCamera.update();
box2dSpriteBatch.setProjectionMatrix(box2dCamera.combined);

```

This worked but all my collisions stopped working with other box2d bodies. Do i need to update each body in my game with the recalculated camera some-how? How would I do this?

# Answer
There is no need to update each body when modifying the camera. Bodies' positions stays the same when you move the camera around. `batch.setProjectionMatrix(cam.combined);` already offsets your batch to the right position. The problem must result of this line :

```
 player.body.setTransform(fingerPosition.x, fingerPosition.y, player.body.getAngle());

```

Assuming you are rendering after this line of code and updating your world before, your player will always be positioned to `fingerPosition`, since the world has not been updated between this and rendering.

To make an object follow your mouse/finger, you should use a joint. Get an eye on the MouseJoint class used in the libgdx box2D testbed. You can find how to implement that here.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: How can I draw a ray from the camera in world space?
How can I construct a ray from the camera position to where it looks at, in world space. My previous method is draw a line by using two points. The first point is the camera position, and the other is calculated like `camera position + lookdirection`. And then I draw the line using `GL_LINE_LOOP`. But using 'lookdirection' of the camera is wrong, since the result is supposed to be a line that extends from the camera and extends forward.

My method in my program is use the camera position `pos` `(0,10,0)` and face a certain `direction`. Then the endpoint is calculated as `(pos+direction) * 100.0f`, and the starting point is `pos`. I used `glDrawArrays(GL_LINE_LOOP,0,2)` to draw the ray. But this produces the wrong result.

What's the correct way to draw a ray from the camera position to where it looks at in world space?

# Answer
It seems like you're confused about what constitutes a ray, which is a point with direction. Put another way, it's half of an infinite line. Here's an example:

```
struct ray
{
    vec3 origin;
    vec3 direction;
};

```

Setting a ray to point in the direction of your camera would look like this

```
ray.origin = camera.position;
ray.direction = camera.forward;

```

Since rays extend to infinity in one direction, you'll have to define the segment you want to render:

```
lineSegment.start = ray.origin;
lineSegment.end = ray.origin + ray.direction * length; // a point that is "length" distance from origin

```

All you need to do then is draw a line between those points.
> 2 votes

---
Tags: opengl
---


# Question
Title: Dealing with multiple 2d sprite animations for the same object
I am using libGDX for a 2d game. Some of my in-game objects have animations, for example a soldier in top-down view that has a walking animation. That is working fine.

Now, while walking, this soldier could do other things as well, for example firing his gun. So both, walking and firing, can happen at the same time.

My question now is: How does one usually deal with these multiple simultaneous animations for the same object? Do I need different animations (one for just walking, one for just shooting, and one animation for both at the same time), or do I rather split the object into several sprites (eg. the soldier's body separated from his arm with the gun), to animate these parts separately? Or is there even another way to achive this?

# Answer
> 1 votes
The easiest way to accomplish what you're asking is to split the objects up into different parts and animate them separately. From there you can either use a bone and joint system (similar to what Flash developers do) or, as you said, each part has its own animations.

---
Tags: 2d, libgdx, animation, sprites
---


# Question
Title: How to access an animation properties from the animator?
I'd like to change the property `speed` of an animation from the animator. For example, I'd like the player to be able to reload faster with upgrades. So I have a basic reload animation on the gun animator, and I would like to change its speed depending on the reload speed level the player has. But I can't find how to change this property in C#.

Here is what I have so far :

```
void Start() {
    gunAnim = gun.GetComponent<Animator> ();
}

void Update() {
    if (Input.GetKeyDown (KeyCode.R)) {
        gunAnim.Play("reload");
        reloadSound.Play();
    }
}

```

# Answer
You can use Blend Trees to change animation speed.

First of all you should add float parameter to Character Controller. Then create Blend Tree and double click on it. It'll open Blend Tree editor. Select Blend Type `1D` and select created float parameter. Add 5 same animations of reloading. Each animation in Blend Tree has two parameters: Threshold and Speed. Set speed of animations in accordance on your skill. For example: 1.0, 1.25, 1.5, 1.75, 2.0. Threshold is a value of float parameter when animation will have preffered speed. You can set it in accordance on skill level number (1, 2, 3, 4, 5) or animation speed (1.0, 1.25, 1.5, 1.75, 2.0). When you want to change animation speed in script you should use method `SetFloat` with name of parameter and new value.

Be careful if you set value between two thresholds you can get unexpected result. There are no linear interpolation between two thresholds. For example if you have 2 animations with threshold (1, 2) and speed (1, 2) and set parameter to 1.5 animation will have speed 1.3.
> 1 votes

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


title: Generate planet like heightmaps

text:
# Question
Title: Generate planet like heightmaps
I would like to procedurally generate planets, but I don't know how to wrap a heightmap around a sphere. I already know how to generate plane heightmaps, but not how to generate spherical ones. Can someone push me in the right direction?

# Answer
Typically the strategy is not to produce a spherical height map, but instead to produce a normal height-map and wrap it around a sphere. You can find some questions on the site already about this process.

There are a number of strategies for doing this, some of them as simple as mapping the Cartesian coordinates to spherical coordinates, or warping the 6 faces of a cube into a sphere (similar to this). There are plenty of ways to represent your map.

Care needs to be taken to ensure your height-map properly wraps so that the terrain meets up where your height-map touches itself. Creating tileable noise is a start, but you can also use techniques like the diamond square algorithm to easily generate wrapped noise.
> 7 votes

---
Tags: software-engineering, procedural-generation
---


# Question
Title: Why would OpenGL ignore GL_DEPTH_TEST setting?
I cannot figure out why some of my objects are being rendered on top of each other. I have Depth testing on.

```
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

```

Do I need to draw by order of what is closest to the camera? (I thought OpenGL did that for you.)

Setup code:

```
 private  void setUpStates() {
    glShadeModel(GL_SMOOTH);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightModel(GL_LIGHT_MODEL_AMBIENT, BufferTools.asFlippedFloatBuffer(new float[]{0, 0f, 0f, 1f}));
    glLight(GL_LIGHT0, GL_CONSTANT_ATTENUATION,BufferTools.asFlippedFloatBuffer(new float[]{1, 1, 1, 1}) );

    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT, GL_DIFFUSE);
    glMaterialf(GL_FRONT, GL_SHININESS, 50f);
    camera.applyOptimalStates();

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    glEnable(GL_TEXTURE_2D);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);

    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}

```

Render Code:

```
private void render() {

    // Clear the pixels on the screen and clear the contents of the depth buffer (3D contents of the scene)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Reset any translations the camera made last frame update
    glLoadIdentity();
    // Apply the camera position and orientation to the scene
    camera.applyTranslations();
    glLight(GL_LIGHT0, GL_POSITION, BufferTools.asFlippedFloatBuffer(500f, 100f, 500f, 1));
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    for(ChunkBatch cb : InterthreadHolder.getInstance().getBatches()){
        cb.draw(camera.x(), camera.y(), camera.z());
    }

}

```

The draw method in ChunkBatch:

```
    public void draw(float x, float y, float z) {
    shader.bind();
    shader.setUniform("cameraPosition", x,y,z);
   for(ChunkVBO c : VBOs){
        glBindBuffer(GL_ARRAY_BUFFER, c.vertexid);
        glVertexPointer(3, GL_FLOAT, 0, 0L);
        glBindBuffer(GL_ARRAY_BUFFER, c.colorid);
        glColorPointer(3, GL_FLOAT, 0, 0L);
        glBindBuffer(GL_ARRAY_BUFFER, c.normalid);
        glNormalPointer(GL_FLOAT, 0, 0L);
        glDrawArrays(GL_QUADS, 0, c.visibleFaces * 6);
    }
    ShaderProgram.unbind();
}

```

# Answer
> 1 votes
I had forgotten to ask for a depth buffer when creating my window:

Before:

```
Display.create(new PixelFormat(4,0,0,4));

```

After

```
Display.create(new PixelFormat(4,24,0,4));

```

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


# Question
Title: Simplified aerodynamics for 2d (top-down) airplane
I am writing a top-down 2d game, in which the player can control an airplane via the `WASD` keys. The `W` key should move the plane upwards (north), the `A` key to the west, and so on.

Now I need a simplified aerodynamics model to control the flight direction and speed of the plane. Pressing `W` should accelearte the plane a bit to reach full speed, then while the player continues to press `W` the plane should continue to move upwards on the screen (remember, top-down view).

When the player releases the `W` key and presses the `D` key now, the plane should behave similar to the real world. That is, it must not immediately move to the right (east), instead it should continue to fly to the north, but gradually start to move to the east. Then if the player continues to press the `D` key, the plane eventually has to fly solely to the east. So all in all in this example the airplane has to fly a curve from north to east.

In general the plane must not change its direction immediately and directly when the player presses another key, but instead fly using a simplified inertia (?) model. This should of course also work correctly if the player presses two keys at the same time, for example `W` (north) and `A` (west).

How would I achive this general in a 2d top-down game?

# Answer
> 1 votes
Assuming you are not going for a full out physics simulator:

Your plane needs to have a position, velocity, direction(angle), acceleration and various maximum values. On each game step:

```
velocity += acceleration * dt;
velocity = clamp(velocity, 0, max_velocity);
acceleration = 0;
position += velocity * dt;

```

On (de)acceleration:

```
acceleration = getVecFromMagnitudeAndDirection(accelerationRate, direction);

```

On moving north/s/e/w:

```
direction += (desired_direction - direction)*rotationRate;

```
* note that you probably want a calcAngleDifference function to handle various edge cases.
* pressing multiple keys etc just requires that you set the desired\_direction correctly.

---
Tags: 2d, physics
---