# Question
Title: Are any scripting languages designed to be reloaded at runtime?
I'm currently working on my first game engine. So far, I have a cross-platform rendering framework and support for numerous file types, but game development is still a hard slog when I'm having to wait for resources to reload and then follow the game flow to the point I need to test.

Ideally, I'd like to be able to develop the game while it's running, through a scripting language that could be reloaded at runtime without compromising the game's state.

However, my biggest problem with this plan has been with pointers-to-functions appearing in the state. Whenever a script gets reloaded, these pointers either point to an old copy of the bytecode, or worse, if the old bytecode gets garbage-collected, they end up dangling!

I've found this in two of the most common (and appealing) scripting languages - Python and Lua, and I know that Javascript is similarly capable of this same issue. All the cases I've tested have been JIT-compiled - I've thought about running interpreted-only, but I've been worried about the performance hit. I've also considered trying a stateless language, but I like object-oriented syntax, especially if my game actors in the script are going to mirror entities in the renderer.

So my question is, is there any scripting language that gives me the best of all worlds? A scripting language with OO syntax that's designed to be reloaded at runtime, or at least **limits** the ability for pointers-to-code to get stored in the runtime state?

Right now, my best option looks like taking a batteries-not-included scripting engine, like TinyPy, and modifying it myself!!!

**EDIT:**

In one last vain appeal, I'm going to try a slightly different question...

Does anyone know of *any* scripting languages that **DON'T** treat functions as first-class objects???

# Answer
> 6 votes
Where I come from, we see the upgrade problem as subsumed by the persistence problem. In this case, that means:

Most games need **saved games**; you will want some way to save the entire state of the game and resume it later. Get that implemented now, and define your hot-reload as follows:

1. Save game to a temporary buffer.
2. Discard all game state and loaded scripts.
3. Load new version of scripts.
4. Load game from buffer.

In this way, **you don't have to implement any additional architectural features** to support the development feature of hot reload: you only need the game-save feature that you will likely be writing anyway, and your development process will thus also **give a thorough workout to the save feature** — including loading old saves in new “versions” of the game, something which is tricky and likely to annoy players if done wrong!

# Answer
> 4 votes
You don't have to throw the baby out with the bathwater. Your issue with these interpreters can easily be solved: Don't directly store pointers to the functions!

Either look them up dynamically every time you invoke, or cache the pointer and invalidate all of the pointers when you reload the scripts. All you have to do is add this one level of indirection.

# Answer
> 0 votes
I suppose you only need hot-swap when developing a game; you probably could build a system which wraps pointers-to-functions in an object that behaves in two different ways:

1. If this is a release build, store a bytecode pointer and invoke it directly. No hot-swapping is possible.
2. If this is a development build, don't store a raw bytecode pointer; instead store the name (and other details), allowing you to to find it again. Every time you need to call the stored function, find it again (to get a temporary function pointer) - then you can be sure your code is correct. The behaviour is transparent to the users, at the cost of performance.

If the performance in development builds is too low, you might consider a hybrid approach - your wrapper objects should contain both a bytecode pointer and a function name. If the script changes and is hot-swapped, all your wrapper objects should refresh their bytecode pointers. You'll need to have a list or something or all the wrapper objects (some smart pointers are implemented in a similar fashion).

# Answer
> 0 votes
I agree with Kevin Ried's answer in part: if you intend to be able to save and reload your game arbitrarily, then you'll need to solve this problem in addition to many more. However, if your game simply doesn't need this (for whatever reason), then you can employ less invasive measures.

The best way to solve it for such a game is to be disciplined in what is considered actual data and what is not.

For example, let us say you're making a top-down 2D space shooter game. And you want to test the AI of an entity. So you have a script that governs the control over that entity.

Your script should contain and manage all of the data needed to control it, but your actual code should only be calling the `UpdateControllerAction` function, which calls the script. This function will tell the game what the entity is doing: accelerating in direction X, firing in direction Y, etc. That is, there is a very rigid interface between external code and the script. The script can go out and detect things (being targeted by unit X, was hit last frame by unit Y, etc). But everything it does happens in here.

When it comes time to reload this script, you simply take the Controller object (the AI that knows about scripts, the thing that holds the script itself). And you tell it to reload its script, which will have the script do all of its necessary preamble work and return the new main function. From that point on, the `UpdateControllerAction` will call the new script function.

You let garbage collection take care of the old data. Since the script was responsible for keeping track of targets and such, reloading the script clears those. So the downside is that reloading will mean that the entity will basically be starting from a neutral state.

This mechanism works because of the separation of responsibility and having a minimal interface between the script and the outside world. The C++ world only keeps track of the main script function, not a bunch of script data and such. The script world can call into the C++ world (to find targets, etc), but all of its persistent data stays within the script world. It is therefore bound to the script function; when that dies, everything goes with it. New scripts, even new instances of the same script, can't access that data.

Here's how this would work in a language like Lua. This script would represent a minimal behavior script. It's just an example, so don't take it too seriously in terms of AI logic.

```
--Arguments to this script are this ship's information and a list of its allies.
local shipData, alliedList = ...

local targetList = {}

--Updates and prioritizes the targetList.
local function FindTargets()
  --...
end

--The AI function.
return function()
  FindTargets();

  if(#targetList ~= 0) then
    local currTarget = targetList[1]
    AttackTarget(currTarget);
  else
    --No target.
    FlyStraight();
  end
end

```

Each time you run this script, you pass it a list of allies and data on it's ship. And it returns the function you will call from `UpdateControllerAction`.

Now, you could use multiple functions instead of one. Maybe an update controller function and a message processing function for when certain events happen to the entity (it gets hit, someone targets it, allies change, etc). But the point is to keep the interface both minimal and hidden from C++.

# Answer
> -1 votes
I guess you're going to have to take the bite and design such a system yourself.

Basically that means that you have to "watch" your files and react to events like a file has been updated etc. (via ReadDirectoryChangesW in Windows).

If one of your scriptfiles gets updated, you'll need to recompile / reinterpret it and refresh your function pointer.

---
Tags: scripting, hot-reload
---


# Question
Title: Collision detection against specific sprite shape using XNA with Farseer Physics?
I am making a 2D XNA Game, using Farseer Physics for collisions.

I need collisions to be resolved against the actual shape of the sprite image, ignoring transparent pixels, rather than against the edge of the bounding rectangle.

# Answer
> 2 votes
I am not sure what you mean by rendering... I think you meant how you would create a specific shape using Farseer Physics. Using this code:

```
   public static Body CreateBodyFromImage(Game game, World world, string textureName)
    {
        //Load the passed texture.
        Texture2D polygonTexture = game.Content.Load<Texture2D>(textureName);

        //Use an array to hold the textures data.
        uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];

        //Transfer the texture data into the array.
        polygonTexture.GetData(data);

        //Find the verticals that make up the outline of the passed texture shape.
        Vertices vertices = PolygonTools.CreatePolygon(data, polygonTexture.Width);

        //For now we need to scale the vertices (result is in pixels, we use meters)
        Vector2 scale = new Vector2(0.07f, 0.07f);
        vertices.Scale(ref scale);

        //Partition the concave polygon into a convex one.
        var decomposedVertices = BayazitDecomposer.ConvexPartition(vertices);

        //Create a single body, that has multiple fixtures to the polygon shapes.
        return BodyFactory.CreateCompoundPolygon(world, decomposedVertices, 1f);

    }

```

-https://stackoverflow.com/questions/7189691/create-a-body-of-a-irregular-2d-sprite-in-farseer

You will be able to create a custom Body that has the shape of your desired sprite(you can see this in Farseer's Debug View). If you let Farseer handle the collisions then you should get the desired collision as you have described above.

I also recommend taking a look at their documentation: http://farseerphysics.codeplex.com/documentation

---
Tags: xna, xna-4.0, rendering, physics
---


# Question
Title: How to find which dirction to move in a 3D space
In my game you are controlling a person walking(X and Y) and they can:

```
Rotate view - -180 to +180
Move a direction - Forward, Backwards, Left, Right.

```

I want the Move to get closer to a goal position by using the Forward, Backward, Left and Right. https://i.stack.imgur.com/OcDr1.png

The player can be looking anywhere on the -180 to 180 rotation and the direction of the Forward, Backward, Left and Right is changed by Rotation.

# Answer
> 2 votes
So your problem is: You have 4 different directions (vectors) and you want to make a linear combination of them, to reach some point "x". Observation 1: You can make that in 2D using only 2 directions (vectors), (for math people: marix rank is 2).

So first, choose 2 linearly independent vectors (Forward - (1,0), Right - (0,1)) and rotate them with your rotation (multiply with rotation matrix).

Then, all you have to do is solve the system of 2 linear equations with 2 variables. You can probably write that in 1 line of code.

Another way is to rotate your point "x" with negative rotation, then you will get the solution straight away.

---
Tags: java, path-finding
---


# Question
Title: Constant Buffer size mismatch on PS, fine on VS and GS
I have the following C/C++ struct:

```
struct ShadowMapCB {
        Math::Matrix4 cropMatrix[4];
        Math::Matrix4 textureMatrix[4];
        float splitPlane[4];
    };

```

and my HLSL constant buffer:

```
cbuffer CBShadowMap : register(b4)
{
    matrix g_CropMatrix[4];
    matrix g_TextureMatrix[4];
    float g_fSplitPlane[4];
};

```

When i bind it to pixel shader i get an error:

> D3D11: WARNING: ID3D11DeviceContext::DrawIndexed: The size of the Constant Buffer at slot 4 of the Pixel Shader unit is too small (528 bytes provided, 576 bytes, at least, expected). This is OK, as out-of-bounds reads are defined to return 0. It is also possible the developer knows the missing data will not be used anyway. This is only a problem if the developer actually intended to bind a sufficiently large Constant Buffer for what the shader expects. \[ EXECUTION WARNING #351: DEVICE\_DRAW\_CONSTANT\_BUFFER\_TOO\_SMALL \]

and infact the last 4 floats (array\[4\]) are messed up, the weird thing is that on the VS and GS it works fine..., and yes i did bind them with PSSetConstantBuffers and update it ofcourse.

What could be causing this?

# Answer
IIRC, in a constant buffer, each element of an array must start on a 4-float boundary. That didn't affect the matrices since each matrix already starts on a 4-float boundary, but it caused the `float g_fSplitPlane[4]` to get an extra 3 floats of padding between array elements.

The constant buffer layout rules are the same for all kinds of shaders, so if it doesn't work in the PS, it shouldn't work in the VS and GS either. Was the `g_fSplitPlane` member not used in the VS and GS, perhaps? If so, the shader compiler might have stripped it out of those, preventing the error from firing.
> 3 votes

---
Tags: c++, hlsl, directx11
---


# Question
Title: RK4 integration and Continuous Collision Detection
I'm using this method to detect collision between two AABBs. The algorithm is simple, fast and works great. It uses the relative velocity between the two objects to calculate TOI. This works fine with Euler, but now i'm trying to switch to RK4, which makes it hard for me to determine the TOI since i can't just divide the distance between the two AABBs by their relative velocity. Since RK4 is so popular, how do people deal with this issue? How to calculate a TOI for a swept AABB with RK4?

# Answer
> 2 votes
Integration should have nothing to do with calculating the TOI. I'm not sure where your problem is as RK4 only allows for more accurate results by allowing a more accurate acceleration curve during each time step. Remember acceleration is just the change in velocity over the time step.

Thus vel = accel / dt or vel = accel * inverse\_dt

The swept box algorithm you provided calculates it's own velocities inside itself based on the new and old positions. To find the position of each box at the TOI just multiply that velocity by the TOI for each box, not what RK4 has found.

I'm also assuming your only using linear motion as your swept box detection does not provide a contact point.

---
Tags: collision-detection, physics, physics-engine, rk4
---


# Question
Title: How do I draw a texture to a MSTerrain object?
I'm using Velcro Physics (Formerly Farseer Physics) to make a game in XNA and I can't seem to figure this out.

I've decided to use `MSTerrain` for making my game's terrain because I wanted destructible terrain and `MSTerrain` seemed like the best bet. Unfortunately, I'm stumped on how to actually show the terrain. When I generate the terrain it's visible in debug view, but `MSTerrain` does not have a `Draw` method, so I'm wondering how it is supposed to be drawn to the screen? Is it worth pursuing?

I'm starting to think that `MSTerrain` is more trouble than it's worth, is there another better way to do this with bodies?

# Answer
> 1 votes
MSTerrain works by using the Marching Squares algorithm which expects a bit field to determine whether terrain exists or not. Normally you would pass in a black and white texture that defines where the terrain exists and then MSTerrain triangulates it. The handy part of this whole process is that you can then apply changes to this terrain and only have to rebuild those small parts.

Drawing an MSTerrain is left to the user as each terrain will likely be rendered differently. The most basic method would be to use the AlphaTest effect and use the texture that defines the terrain as the template for the graphical version of the terrain. This would allow holes and chunks to be changed without changing the initial graphical representation of the terrain.

---
Tags: xna, farseer-physics-engine
---


# Question
Title: Moving an object around the the circle to the specific location in circumference
Well I have run out of ideas how to approach this particular problem.See the picture below:

So the idea is that the object (dot in black) has to get to a point mark X (red X mark).However the limitation is that it has to get there without crossing the circle (i.e going in the straight line the the X mark).I was reading on some steering algorithsm but seems rather too complicated for this problem.Also I should mention that the object has the speed and velocity and position attributes which controls how its moving.

Now I was reading some ideas on how to move an object around a circumference here:

Here

However this doesn't entirely answer my question.The thing is I first need to get to the circle in order to be able to move around it.What I was thinking,was to allow the object to move towards the position in a straight line until it hits the circle and then start moving along the circumference of the circle.Also the "X" mark can be anywhere on the circle even right in-front of it (not behind on the other side of the as in this example shown in the image)

I am not a game developer and thus never came across issues like so.The idea is that there will be more than one black object trying to get to their own "X" mark on the circle from random positions.(They idea is that they will be surrounding some objects in the middle). Here is an image to show what I mean,where each black object has an X position that they need to attend to without directly going through the circle.(Sorry for my bad drawings,was using laptop track-pad to do these images)

Anyway I am kinda lost with this and would to see different on tackling this particular problem.

# Answer
> 3 votes
I can think of a couple ways to approach this problem.

(Figure 1) Find the closer tangent point to aim towards, then steer along the edge of the circle. This should be the path with the shortest distance.

(Figure 2) In polar coordinates, plot a path that interpolates the angle `Θ` and radius `r` from the starting point to the desired point. These points are not equidistant, so use them as intermediate waypoints for travel. Since `r`point never goes below `r`circle, you are guaranteed it will not cross the circle boundary.

# Answer
> 2 votes
It sounds like your desired motion consists of two stages: first move directly toward the target point (x) until you hit the circle; then, move around the circle to the target point, if necessary.

Since there are two stages, you could use a state machine with two states indicating which kind of motion you're currently doing.

In the first state, just set the velocity using the vector from the object to the target point, scaled to the desired speed.

You can detect if you're about to run into the circle by checking whether the next frame position (after physics updates) would be inside the circle. If that occurs, adjust it so you don't enter the circle - this could be done by simply clamping to the nearest point on the circle, or by doing a ray-circle intersection test to find the exact point of contact (but you may not need to be that accurate). In any case, once you've hit the circle, switch to the second state.

Then apply the answers to the question you linked to to move around the circle to the target point.

---
Tags: ai, path-finding
---


# Question
Title: Cant set up ANDENGINE GLES2-AnchorCenter Examples & Extensions
I am trying to setup the GLES2-AnchorCenter in my eclipse Downloaded andengine , extension and examples listed in Anchor center branch .But not yet succed .

Andengine examples missing an extension named

> andengine cocosbuilder extension CC Rotating Sprite extension

But i am not able to find it anywhere.If i am missing the extension please give me a link to get the extension.

In extensions Multitouch extension shows some error with import statement

```
import org.anddev.andengine.util.SystemUtils;

```

Actually i am not able to find org.anddev package it self in andegine,

in andengine scripting extensuion it shows error with the statement

import org.andengine.util.color.Color; What are the things I am missing. Do i need to install all thse extensions to get the eample get working?

Please Help me ..........

# Answer
1) Here's the CocosBuilder Extension.

2) `org.anddev.andengine` is an old package name. Are you using the good branch of the Multitouch extension? It should be `import org.andengine.util.system.SystemUtils;`.

3) You may not use the good branch where there's the error with Color package. It should be `import org.andengine.util.color.Color;`.
> 3 votes

---
Tags: andengine
---


# Question
Title: How to Bind Multiple Shapes/Models to One Vertex Buffer?
If I have two Vertex Arrays, one for Square, and one for Triangle; what is the best way to bind them to the VertexBuffer?

What are the patterns used to write multiple vertices to the VertexBuffer? Streams? Vectors? Is there an Add, (+) overload that can be used like .pSysMem += anotherMesh.GetVertices()?

1. Is this possible with objects that have different numbers of Vertices?
2. Is this possible with objects that have different buffer element descriptions, (one with `float4` position data, and another with `float3` and texcoords, etc)?

Currently, I am binding one Shape, (a triangle), to the subresource like this:

```
ModelRenderer::StaticBufferDescription.ByteWidth = bufferSize;
ModelRenderer::StaticBufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER;

ModelRenderer::StaticSubResourceData.SysMemPitch = 0;
ModelRenderer::StaticSubResourceData.SysMemSlicePitch = 0;
ModelRenderer::StaticSubResourceData.pSysMem = model->GetVertices();

DeviceManager::Device->CreateBuffer(
    & ModelRenderer::StaticBufferDescription,
    & ModelRenderer::StaticSubResourceData,
    & ModelRenderer::StaticBuffer);

```

# Answer
In the example below, individual mesh/instance data is being copyied into a big memory buffer, which is then assigned to the subresource. Alternatively, the instance data could already be in a memory buffer so this wouldn't have to be done every "draw".

Also, a vector is guaranteed to be contiguous in C++11 so you can assign the vector to the subResource.pSysMem = vector, rather than a fixed size array.

If you want to go further than this, you can can stream into the memory buffer being used from a flat file. Just be careful of buffer overruns.

```
void ModelRenderer::UpdateInstanceBuffer()
    {
        NS::InstanceStateFactory<int> * stateFactory = nullptr;
        stateFactory = (NS::InstanceStateFactory<int> *) NS::ModelFacade::GetInstanceStateFactory();

        // std::vector<NS::Vertex> instances;

        unsigned int memoryAllocationSizeInBytes = sizeof(Position) * 10;

        std::vector<int8_t> buffer(memoryAllocationSizeInBytes);

        int instanceCount = 0;
        int stride = sizeof(Position);

        for(auto & kv : stateFactory->Instances)
        {
            // Push vector arrays into Memory Buffer
            memcpy(&buffer[0] + instanceCount * stride, & kv.second->Position, stride);

            instanceCount ++;
        }

        D3D11_MAPPED_SUBRESOURCE resource;

        HRESULT hResult = DeviceManager::DeviceContext->
            Map(ModelRenderer::InstanceBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);

        // resource.pData = instances.data();
        memcpy(resource.pData, buffer.data(), sizeof(Position) * instanceCount);

        DeviceManager::DeviceContext->Unmap(ModelRenderer::InstanceBuffer.Get(), 0);

        // ModelRenderer::BindInstanceBuffer();

        // delete instances.data();
    }

```
> 0 votes

# Answer
You can definitely put multiple objects in a vertex buffer, even with different numbers of vertices. A vertex buffer doesn't know or care where the "objects" are in it - it's nothing more than a list of vertices. If you have a fixed set of objects you want to draw, you can simply concatenate all your vertices together and put them in one big vertex buffer; when you do your `Draw()` call, you'll specify the range of vertices to draw from the buffer. Or if you use index buffers and `DrawIndexed()`, the same applies.

All the vertices in a buffer have to be the same format, though (i.e. the same size and order of components like position, normal, UV etc). You can't mix and match different vertex formats in one buffer. Well, technically perhaps you could, but you'd have to re-call `IASetVertexBuffers()` with different strides and offsets, and do a separate draw call, for each format. That would pretty much negate the point of putting everything in one big vertex buffer; it would be simpler just to have several buffers.

Now, you brought up instancing, so I'll say a little about that. Instancing is designed to let you repeat an "inner" vertex buffer many times, each time pairing it with a different "outer vertex" (i.e. an instance). Across all the instances drawn in a single draw call, the inner vertex buffer must be the same. So if you have triangles in one buffer and squares in another, you would not be able to draw multiple instances of both of them in one draw call, using hardware instancing. You would have to do one draw call for all the triangles, and one for all the squares.

You have a couple options here. First, you could do the instancing manually, by constructing a huge vertex buffer and copying in the triangle vertices as many times as you have triangles, and the square vertices as many times as you have squares, etc.

The other option, which is advanced, is to use some tricks in the vertex shader to look up the inner vertices from a different place in the buffer depending on a value set in the outer vertex data. This requires all the different instance meshes to be padded out to a common vertex size by adding degenerate triangles. This approach was used in Just Cause 2. For more information see Emil Persson's presentation Graphics Gems for Games (slides 19-24).
> 1 votes

# Answer
The easiest solution for you is to just settle on a common vertex type for all of your objects, which would be a superset of all the different vertex types you currently have. Yes, I know that right about now you're thinking something like "but that would waste memory!" but always remember - this is a tradeoff, and what you're losing in memory usage you're gaining by not having to call IASetVertexBuffers multiple times with different strides and offsets. Memory isn't everything, buffer changes can be potentially expensive (if nothing else you'll need to break the current batch to do one), and avoiding so many buffer changes can potentially give you much more performance than saving a few lousy kilobytes.

From there you just need to adjust the parameters of your Draw () call as appropriate.
> 0 votes

---
Tags: directx, directx11, vertex-arrays, instancing
---


# Question
Title: How To Buffer Many Vertex, Geometry, and Pixel Shaders
What is the best way to buffer Vertex Shaders, Pixel Shaders, etc into the Device/Device Context without having to reload them from the filesystem every time?

ID3D11Device::CreateVertexShader http://msdn.microsoft.com/en-us/library/windows/desktop/ff476524(v=vs.85).aspx

ID3D11DeviceContext::VSSetShader http://msdn.microsoft.com/en-us/library/windows/desktop/ff476493(v=vs.85).aspx

Does Device::CreateVertexShader buffer a single instance of the shader in System, (not GPU), memory? Can I buffer more than 1?

DeviceContext::CreateVertexShader buffer a single instance of the shader in the GPU, (not System), memory? Can I buffer more than 1?

What are the recommended methods for buffering shaders within the system?

Thanks!

# Answer
> 3 votes
I'm not 100% certain that I fully understand the thinking behind your question, but this should cover everything:

```
ID3D11VertexShader *vs1;
ID3D11VertexShader *vs2;

device->CreateVertexShader (..., &vs1);
device->CreateVertexShader (..., &vs2);

```

We now have two vertex shaders, and this only needs to be done once, during startup.

```
context->VSSetshader (vs1, ...);

```

We're now using vertex shader 1; no need to call CreateVertexShader again, no need to load it from the filesystem again.

```
context->VSSetshader (vs2, ...);

```

And we're now using vertex shader 2; no need to call CreateVertexShader again, no need to load it from the filesystem again.

---
Tags: directx, shaders, directx11, c++
---


# Question
Title: How to organise an XNA client/server solution
I was wondering what would be the best way to go about organizing the projects for the XNA project I have been working on. It is a simple game that uses a client/server architecture.

Currently everything is in one solution that I open in Visual Studio. This solution consists of multiple projects. The client project, server project, content project, the game API project, and the networking library. It works this way, but it all feels cluttered it doesn't seem right from an architectural stand-point to have both the client and the server in the same solution.

Does it make sense to keep everything in one giant solution or should I have a separate solution for the client application and a separate solution for the server application. If I go about separating them how could I continue to use a shared API project between both solutions?

# Answer
> 3 votes
In my experience it is **highly preferred to work with all your projects in a single solution**. There is one highly important reason for this: IntelliSense and the refactoring tools in Visual Studio.

Architecturally, your client and server almost certainly *should* rely on shared code that exists in one or more shared projects. And if you use any of the refactoring tools (especially: Rename, and Find All References) within one of those shared projects, you want that tool to take into consideration code in both the Client and Server projects that depends on it.

---

If you wish to work on the Client and the Server in two separate instances of Visual Studio - that is still possible. You can simply open the one solution twice. Visual Studio is still reasonably well behaved in this scenario.

Alternately, if you want to have only one instance of Visual Studio open - but still debug both the client and the server at the same time - you can run one or both projects without the debugger. If you have the full version of Visual Studio (not Express) you can attach and detach the debugger to either process at any time.

(An more creative alternative would be to organise your project such that a single process can act as both client and server at the same time.)

---

Of course - it's fairly easy to add and remove projects to solutions. So feel free to experiment and choose what works best for you.

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


title: Multiple viewports

text:
# Question
Title: Multiple viewports
\[Problem solved !
I canno't answer with the response because i have less than 10 reputations. I have to wait 8 hours.\]

Currently, i'm trying to display 3 viewports.

1st : This viewport is the entire screen (with `camera1` transformation, like zoom)

```
        viewportDefault = GraphicsDevice.Viewport;

```

2nd : This viewport is over the 1st viewport, but only width:400 height:200 at left bottom of the screen (with `camera2` transformation)

```
        viewport2 = new Viewport(0, 520, 400, 200);

```

3rd : This viewport is over the others, the entire screen, fond Color.Transparant. Just to display some text all over the screen, for me. (without camera transformation)

```
        viewportDevStrings = viewportDefault;

```

Here is my code :

```
    protected override void LoadContent()
    {
        //viewports
        viewportDefault = GraphicsDevice.Viewport;
        viewport2 = new Viewport(0, 520, 400, 200);
        viewportDevStrings = viewportDefault;
    }

    protected override void Draw(GameTime gameTime)
    {

                GraphicsDevice.Viewport = viewportDefault;
                DrawScene(camera1.transformation);

                if(ThisIsABool)
                {
                    GraphicsDevice.Viewport = viewport2;
                    DrawScene(camera2.transformation);
                }

                GraphicsDevice.Viewport = viewportDevStrings;
                DrawStrings();
    }

```

The problem is, when `ThisIsABool == true`, viewport2 is the entire screen... When i look the "Watch added", here they are :

`viewportDefault {X:0 Y:0 Width:1280 Height:720 MinDepth:0 MaxDepth:1}
viewport1 {X:0 Y:520 Width:400 Height:200 MinDepth:0 MaxDepth:1}
viewportDevStrings {X:0 Y:0 Width:1280 Height:720 MinDepth:0 MaxDepth:1}`

Do you have some suggestions ? :( Hope you can help...

--------------------------EDIT---------------------------

```
    public void DrawScene(Matrix transform)
    {
       DrawScene1(transform);
       DrawScene2(transform);
       DrawScene3();
    }

    public void DrawScene1(Matrix transform)
    {
       spriteBatch.Begin(
       SpriteSortMode.Deferred,
       BlendState.AlphaBlend,
       SamplerState.LinearClamp,
       null,
       null,
       null,
       transform
       );

       GraphicsDevice.Clear(Color.Black);
       map_background1.Draw(spriteBatch);
       map_background2.Draw(spriteBatch);
       map_background3.Draw(spriteBatch);

       spriteBatch.End();
    }

    public void DrawScene2(Matrix transform)
    {
       spriteBatch.Begin(
       SpriteSortMode.Deferred,
       BlendState.AlphaBlend,
       SamplerState.LinearClamp,
       null,
       null,
       null,
       transform
       );

       character.Draw(spriteBatch);
       door.Draw(spriteBatch);
       monster.Draw(spriteBatch);

       spriteBatch.End();
    }

    public void DrawScene3()
    {
        BlendState blendState = new BlendState();
        blendState.ColorSourceBlend = Blend.DestinationColor;
        blendState.ColorDestinationBlend = Blend.SourceColor;

        spriteBatch.Begin(
        SpriteSortMode.Immediate,
        blendState,
        SamplerState.LinearClamp,
        null,
        null,
        null
        );

        spriteBatch.Draw(RenderTargetForShadows, Vector2.Zero, Color.White);

        spriteBatch.End();
    }

```

# Answer
Well...
There was a conflict with the shadow RenderTarget2D. (Nobody could fixed this problem without the shadow RenderTarget2D code i have...)

But, in doubt :
on the 1st viewport, the renderTarget2D was at the screen size, but on the 2nd viewport, i had to create an other renderTarget2D with the 2nd viewport size.

After this, i had to "generate" the 2 renderTarget2D before any draw() in viewports.
> 0 votes

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


# Question
Title: Staggered Isometric Map: Calculate map coordinates for point on screen
I know there are already a lot of resources about this, but I haven't found one that matches my coordinate system and I'm having massive trouble adjusting any of those solutions to my needs. What I learned is that the best way to do this is to use a transformation matrix. Implementing that is no problem, but I don't know in which way I have to transform the coordinate space.

Here's an image that shows my coordinate system:

How do I transform a point on screen to this coordinate system?

# Answer
> 25 votes
First, here is the code. An explanation will follow:

```
/*
 * tw, th contain the tile width and height.
 *
 * hitTest contains a single channel taken from a tile-shaped hit-test
 * image. Data was extracted with getImageData()
 */

worldToTilePos = function(x, y) {

    var eventilex = Math.floor(x%tw);
    var eventiley = Math.floor(y%th);

    if (hitTest[eventilex + eventiley * tw] !== 255) {
        /* On even tile */

        return {
            x: Math.floor((x + tw) / tw) - 1,
            y: 2 * (Math.floor((y + th) / th) - 1)
        };
    } else {
        /* On odd tile */

        return {
            x: Math.floor((x + tw / 2) / tw) - 1,
            y: 2 * (Math.floor((y + th / 2) / th)) - 1
        };
    }
};

```

Note that this code won't work out of the box for the map shown in your question. This is because you have the odd tiles offset to the left, whereas the odd tile is more usually offset to the right (As is the case in the tiled map editor). You should be able to easy remedy this by tweaking the x value returned in the odd-tile case.

**Explanation**

This may seem to be a slightly more brute-force method of accomplishing this task, but it does at least have the advantage of being pixel perfect and slightly more flexible.

The trick is in viewing the map not as a single staggered grid, but as two grids overlayed on top of one another. There's the odd-rows grid and the even-rows grid, but let's call them red and green instead so that we can create a pretty diagram...

Notice on the right of that image I've marked a point with a purple dot. This is the example point we'll try to find in our original tile-space.

The thing to notice about any point in the world is that it will always lie in exactly two regions - a red one and a green one (Unless it's on an edge, but you'll likely be clipping within the jagged edge boundary anyway). Let's find those regions...

Now to pick which of the two regions is the correct one. There will always be exactly one answer.

From here we could do some more simple arithmetic and work out the squared distance from our sample point to each centre point of the two regions. Whichever is the closest will be our answer.

There is an alternative way however. For each test region, we sample a bitmap that matches the exact shape of our tiles. We sample it at a point translated into local coordinates for that single-tile. For our example it would look something like this:

One the left we check the green region and get a hit (Black pixel). On the right we test the red region and get a miss (White pixel). The second test is of course redundant since it will always be exactly one or the other, never both.

We then arrive at the conclusion that we have a hit in the odd tile at 1,1. This coordinate should be simple to map to the original tile coordinates using a different transformation for odd and even rows.

This method also allows you to have simple per-pixel properties on the pixel test bitmap(s). E.g. white is off-tile, black is a hit, blue is water, red is solid.

# Answer
> 1 votes
I think the problem you're having is with your coordinate space. The coordinates you've given the tiles are not really an isometric projection - You need to think of the xAxis as going diagonal down-right and the yAxis as going diagonal down-left (or some variant of that)

right now if you move along the illustrated coordinate axes you'll be traveling in a diagonal direction in "tile space" so the squares end up as diamonds (and everything will be more complex)

The transformation matrix you're looking for is one built out of those x and y axes. It is effectively the same as doing the following calculation.

```
screenOffsetXY = screenPointXY - tileOriginXY;
tileX = dot(screenOffsetXY, xAxis) / tileWidth;
tileY = dot(screenOffsetXY, yAxis) / tileWidth;

```

Edit: I just came across a similar question (but with the coordinate system I was talking about) and someone gave a much more thorough answer here:

How to convert mouse coordinates to isometric indexes?

# Answer
> 0 votes
Basically you want to get the position of the mouse in the window using an event listener, you need to remove the offset of the canvas position in the window from the mouse positions, so the mouse position is then relative to the canvas.

```
function mouseTwoGridPosition(e){

var mousex = e.pageX; //mouse position x
var mouseY = e.pageY;  //mouse position y
var canvas_width = 1000; //pixels
var offset_left = 100; //offset of canvas to window in pixels
var offset_top = 150; //offset of canvas to window in pixels

var isotile = 64; //if iso tile is 64 by 64

//get mouse position relative to canvas rather than window
var x = mousex - canvas_width/2 - offset_left;
var y = mousey - offset_top;

//convert to isometric grid
var tx = Math.round( (x + y * 2) / isotile) - 1;
var ty = Math.round((y * 2 - x) / isotile) - 1;

 //because your grid starts at 0/0 not 1/1 we subtract 1
 // this is optional based on what grid number you want to start at

   return [tx,ty];
}

```

I will assume you know how to do event listening on canvas' for mousemove, otherwise you might want to learn more JS before you consider isometric game design :D

# Answer
> 0 votes
I solved this by changing the coordinate space. It now starts without a offset in the first row and for that I found a working example which I was able to adjust a bit.

```
    hWidth = this.tileset.tileSize.width / 2;
    hHeight = this.tileset.tileSize.height / 2;

    pX = point.x - halfWidth;
    pY = point.y - halfHeight;

    x = Math.floor((pX + (pY - hHeight) * 2) / this.tileset.tileSize.width);
    y = Math.floor((pY - (pX - hWidth) * 0.5) / this.tileset.tileSize.height);

    tx = Math.floor((x - y) / 2) + 1 + this.camera.x;
    ty = y + x + 2 + this.camera.y;

```

---
Tags: mathematics, javascript, matrix, isometric, coordinates
---


# Question
Title: In a regular grid, how can I tell which tile a position is in?
I have a position on the screen, how do I calculate which grid tile that position is inside?

I know the number of tiles in the grid, and the size of the screen (including how many tiles fit on it horizontally and vertically).

# Answer
> 4 votes
Ok this code is based on all tiles being shown on the screen.

```
x = (int) (posX / tileWidth)
y = (int) (posY / tileHeight)

```

If you don't have all tiles on screen then you would offset the x,y from above by the lowest x,y cell you are displaying.

---
Tags: mathematics, grid
---


# Question
Title: How to emulate knob turning, based on x/y movement?
I'm doing a game where one component is that you turn a knob. I'm having trouble getting good "knob behavior".

I know the current touch/mouse X,Y location, and I keep track of the previous X,Y location, so I can determine if I'm going left or right and/or up or down.

It works, but it's crude. I suspect I have to take an average of any given direction over a period of time (say, last quarter second) to eliminate jitter because people don't move uniformly in the same movement every moment.

I can't really use touchdown/release because you should be able to put the touch down, then move left/right up/down continuously without release, and the knob would turn, just as if you had a free-spinning audio control or video shuttle (say).

Any thoughts in this direction on how to even it out?

# Answer
> 2 votes
Instead of just using deltas, have you considered just linearly mapping the distance from the start of the touch to some rotation value?

So let's say you start at position `(x,y)` and your knob is currently rotated to point to angle `theta`. As long as your finger is held down, you update the current angle of the knob. At position `(x+z,y+w)` you figure that you moved `z+w` distance (using manhattan distance so you can go negative), which you then multiply by some scalar value `r` to give you how much you should rotate the knob. Say 1 radian of rotation equals 100 pixels movement (so `r` = 100 in this case). So `current rotation = theta + ((w+z) / r )`

I probably would do something like that first before going for angle checks and things like that since, as a user, if I want a knob to increase I'd probably just want to drag it to the right instead of having to drag around in a circle. If you went with the angle, the user might get into a situation where dragging "more" doesn't increase the knob as expected, assuming your knob rotates more than 180 degrees.

---
Tags: android, physics, mouse, touch
---


title: Memory issues with new game on s3

text:
# Question
Title: Memory issues with new game on s3
I am building a new game with AndEngine and for some reason i keep getting this debug statement in the Logcat:

> 01-31 21:29:50.503: I/Choreographer(697): Skipped 152 frames! The application may be doing too much work on its main thread.

Im not really sure what is causing this error exactly during my game. I am checking a lot of collisions, but they arent initiated until after the game play scene has started.

I also noticed on my Galaxy S3 the game causes my phone to "flicker" when swiping changing home screens and pulling down the task bar at the top.

I think this error has something to do with it, but I am not sure. What do you guys think?

Also each time the user goes to another level I initialized the collision detectors all over again. But I don't unregister or stop the last collisions that were started. I thought they would be automatically cleaned up when the new one is initialized.

What do you guys think?

# Answer
> 1 votes
The android platform is a heavily multi-threaded environment designed to distribute the workload. Whenever assets or systems are not being used in the game, they should always be released or deleted unless there is a very specific reason why they need to remain active. Cleaning up your collision process and freeing up used memory at the end of a scene should be a standard practice for you.

The error message you post leads me to believe that the app is skipping frames to maintain a specific rate of functionality. Further research has lead me to the following link. I suggest starting the rest of your investigation here.

https://stackoverflow.com/questions/11266535/what-is-android-choreographer

---
Tags: android, andengine
---


# Question
Title: Camera movement using WASD on x/z plane only
I've been wearing my enter key down on google searches - I have a camera script based on the MouseOrbit.js asset. That's all working fine, but in addition to the basic orbiting and the zooming that I've added, I would like to use the WASD keys to move the camera around the world.

The W key would move the camera straight forward, however it would ignore the y axis. For example, using

`transform.Translate(Vector3.Forward*Time.Delta*20);`

moves the camera forward relative to the camera. This results in you quickly hitting the ground. Moving back obviously does the opposite. The desired effect is sliding across the world without getting any closer/farther to it, regardless of the angle the camera is at.

The closest I can get is using the Space.World parameter of Translate(), but this does not take into account the rotation of my camera. I think if I could take that into account, this would be solved but I'm not clear on how to do that.

# Answer
You don't need to use `transform.Translate`. Just calculate how much the camera should move forward for a given frame (something like if the W key is held down do `deltaPos = transform.forward * Time.deltaTime * 20`), set the Y value of that `Vector3` to zero, then add that delta vector to the original position by adding it to the current position `transform.position += deltaPos;`
> 3 votes

---
Tags: unity, camera
---


# Question
Title: Simulating flight dynamics in two dimensions
I have decided that in order to improve my math skills and game programming skills I am going to work on a two-dimensional space simulator. The view of the player or camera will be from inside the cockpit of a spaceship. This presents quite a few challenges which I am looking to the gd.net community for help with. I'm not asking for any code or any specific answers, just suggestions on what subjects to research.

My first challenge is going to be related to perspective correction. Since I'm only working with two-dimensions I need to fake flight dynamics. If you imagine that you are sitting in a cockpit of a spaceship, when you move the flight stick to the right or left the ship would yaw in either direction. Simulating this in two dimensions is much more difficult than in three dimensions, as you have to apply some sort of perspective correction.

The same is true if you were to pitch the nose of the spacecraft up or down. Simply moving the camera along the x / y axes won't be enough. I need to correct the perspective of my camera so that it appears that the aircraft is actually yawing / pitching in the desired direction and not just panning upwards / to the side.

What is the basic mathematical formula for applying this kind of perspective correction? If a formula is too much to ask for, where can I read about examples of this being done / read about the basic concepts I need to understand to accomplish this?

Thanks!

# Answer
> 4 votes
**Almost all 3D games are fake 3D**. At the end of the day, you're projecting a 2D image into the screen. The standard way to project a 3D scene onto a 2D scene is using a Projection Matrix. In every 3D game, the programmer has to think in 3D "world-space" and 2D "screen space" (and sometimes, 3D "camera space")

*but sir, I know the difference between SNES Zelda and SNES Mario Kart! One was 2D and one was 2D with fake 3D!*

**In the past**, doing the calculations required for this projection was **too expensive** for standard processors. This is why "fake 3D" technologies like **Mode 7** and Doom-style **raycasting** were invented. Nowadays, with dedicated graphics hardware and 3D libraries, It's more work to implement Mode 7 than to simply draw a textured quad on the screen.

There's this common idea that when you make a 2D game, you can use 2D coordinates for everything, and then add a "fudge factor" for perspective. Commonly, a game using 2D graphics will use this fudge factor to provide parallax effects as well as shrink objects that are farther away. However, this doesn't really change the nature of what you are doing. **the "fudge factor" is how you represent the Z-axis**. You're really just calculating positions in 3D space anyways, so "faking" yaw and perspective in a (X,Y,fudge) system. is more difficult that calculating real yaw and perspective in a (X,Y,Z) coordinate system.

---

TL;DR: Games such as Wing Commander use 3D math for all game logic such as calculating the position of an asteroid or enemy, then finally use perspective equations to calculate where to draw on the screen. You can then draw sprites at the calculated position, and this is how it looks "2D"

---
Tags: 2d, software-engineering, projection
---


title: Anti- Aliasing a small image?

text:
# Question
Title: Anti- Aliasing a small image?
As you can see above, I have an image of a game I've been working on using Java. Using AWT I added the following:

```
public static void drawImageRotated(
        Graphics2D g2d, BufferedImage img, double x, double y, int scale, double angle) {

    BufferedImage image = new BufferedImage(
                                     (int)(img.getWidth() * 1.5D),
                                     (int)(img.getHeight() * 1.5D),
                                     2);
    Graphics2D g = (Graphics2D)image.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2);
    g.drawImage(img,
                image.getWidth()  / 2 - img.getWidth() / 2,
                image.getHeight() / 2 - image.getHeight() / 2,
                null);
    g2d.drawImage(image,
                 (int)x-(image.getWidth()*scale/2),
                 (int)y-(image.getHeight()*scale/2),
                 image.getWidth()*scale,
                 image.getHeight()*scale,
                 null);
    g.dispose();
}

```

This is the code which draws the ships onto the screen. As you can see there is a blue and a cyan ship on the screen, the blue ship's rotation being 0 and the cyan having a rotation of just over 270 degrees. The cyan ship is distorted and that's what I want to get rid of. Is there an anti-aliasing for small images like that one (16x16)?

# Answer
That code seems more complicated than necessary, what you need is to just draw your image with the right transformation matrix.

I don't speak Java so there may be mistakes in this, but it should look something like:

```
AffineTransform transform = new AffineTransform();
transform.rotate(angle,img.getWidth()/2,img.getHeight()/2);
transform.scale(scale,scale);
transform.translate(x,y);
g2d.drawImage(img,transform,null);

```

The first 4 lines build a translation matrix, you don't need to worry much about how that works, except that the construction order matters.
> 2 votes

---
Tags: java, antialiasing
---


# Question
Title: Assigning bone transform in every draw a good idea?
In my `Draw` method, I am doing the following:

```
thisMesh.CopyAbsoluteBoneTransformsTo(transforms);

```

Is this a good idea? Or should I do this once at the `constructor` level?

# Answer
If the bones are static and so are the transforms, you only need to apply the transforms once. You can do that in the constructor.

However, if you're using the bones to position the model or animate the model, you'll need to update them more often. How often depends on how you're using them. For example, you may be reusing the same model and bones to draw multiple instances of a single model. In this case you'd have to update the transforms every frame. If you're just animating one model, you only need to update the transforms on a pose change. That could be at the same speed as your frame rate or it could be slower, it depends on your animation speed and run speed.
> 0 votes

---
Tags: xna, matrix
---


# Question
Title: How to limit steering force at low velocities
Sorry if this is posted before, but I didn't find an answer for this. I've been banging my head on this for a day now and I seems to be stuck.

I've implemented (see below) the 2D steering arrival behaviour described in http://www.red3d.com/cwr/steer/ which all works fine until there is a characters which wants to turn 180°. The character simply slows down, flips 180° and starts accelerating. I tried to illustrate this in Figure 1 (a).

*Figure 1 - where red is the velocity and green the desired direction*

What I would ideal like is a smoother path as seen in Figure 1 (b). I was thinking of using the `clipped_speed` in combination with steering 'left' or 'right', however I can't seem to figure out how to do this with vectors. If anyone could point me in the right direction, that would be great.

The implementation (using libgdx)

```
Vector2 target_offset = target.sub(position);
float dist = target_offset.len();
float clipped_speed = Math.min(max_speed * (dist / (20 * mass)), max_speed);

desiredVelocity = target_offset.mul(clipped_speed / dist);
steeringForce = desiredVelocity.sub(this.velocity);

truncate(steeringForce, max_force);
Vector2 acceleration = steeringForce.mul(1 / mass * 60 * delta);

velocity.add(acceleration);
truncate(velocity, max_speed);

position.add(velocity.mul(60 * delta));

```

And the code for truncate:

```
public void truncate(Vector2 v, float max) {
    float i = v.len() != 0 ? max / v.len() : 0;

    if(i < 1) {
        v.mul(i);
    }
}

```

EDIT: Using bobobobo input I think I'm there. So for those interested:

```
Vector2 target_offset = target.position().sub(position);

float dist = target_offset.len();
float clipped_speed = Math.min(max_speed * (dist / break_dist * mass), max_speed);

desiredVelocity = target_offset.mul(clipped_speed / dist);
steeringForce = desiredVelocity.sub(velocity);

truncate(steeringForce, max_force);
forward = steeringForce.mul(1 / mass * 60 * delta);

float a = (float) (Math.acos(velocity.nor().dot(forward.nor())) * MathUtils.radDeg);
if(Float.isNaN(a)) a = 0;

if(a > max_rot) {
    if(velocity.nor().crs(forward.cpy().nor()) < 0) {
        forward.setAngle(velocity.angle() - max_rot);
    } else {
        forward.setAngle(velocity.angle() + max_rot);
    }
}

velocity.add(forward);
truncate(velocity, dist < break_dist * mass ? dist / (break_dist * mass) * max_speed : max_speed);

```

Breaking is done by just scaling the velocity linearly, which isn't really all that nice implementation wise, but it give better stopping results. So we don't overshoot.

# Answer
> 5 votes
Just clip the maximum allowable *rotation angle* of the *heading* vector for the agent to something like 5 degrees/frame. (ie the red vector in your diagrams).

Right now your agents kind of have this omnidirectional capability to steer. You need to change that.

To get the agent to behave more like a car, an agent should only be able accelerate in the FORWARD direction. So you need to store an extra vector for the FORWARD vector of the agent.

The steering behaviors seek to modify the FORWARD vector. But if you *clamp changes to the forward vector* to a max of 5 deg /frame, turning will be smooth.

---
Tags: 2d, ai, steering-behaviors
---


# Question
Title: XNA partially extending the content pipeline using a ModelContent
I am trying to extend XNA's content pipeline in order to import a model in .obj format (a very simple and text-based format, see here for details). Writing a full extension library seems like an overkill to me so I decided I would only create a custom importer and a processor which returns a ModelContent so that I could use the default writer and reader.
My processor sort of works but not exacly as expected: what should look like an aircraft is actually a bunch of triangles stick together! Before writing this I had a simple class derived from DrawableGameComponent which loaded the model in its LoadContent, but that's not exacly XNA-ish. The point is that the code worked, so there must be a problem in the construction of the MeshContent.
I have followed the pattern I found in this question during my researches.

Here's the relevant part:

```
[ContentProcessor( DisplayName = "dotObjProcessor" )]
public class dotObjProcessor : ContentProcessor<dotObjContent, ModelContent> {
    public override ModelContent Process( dotObjContent input,
        ContentProcessorContext context ) {

        var mc = new MeshContent( );
        foreach ( dotObjContent.Vertex p in input.Vertices )
            mc.Positions.Add( new Vector3( p.X, p.Y, p.Z ) );

        var gc = new GeometryContent( );
        foreach ( dotObjContent.Face f in input.Faces ) {
            gc.Vertices.Add( f.V1 );
            gc.Vertices.Add( f.V2 );
            gc.Vertices.Add( f.V3 );

            gc.Indices.Add( f.V1 );
            gc.Indices.Add( f.V2 );
            gc.Indices.Add( f.V3 );
        }

        mc.Geometry.Add( gc );
        MeshHelper.CalculateNormals( mc, true );

        return context.Convert<MeshContent, ModelContent>( mc, "ModelProcessor" );
    }
}

```

A dotObjContent is the output of my importer, it simply contains two collections for vertices and indices.

# Answer
Alright, brand new here, so I couldn't comment to try and draw out information to help you out better...

I'm assuming your mesh looks like a bunch of triangles roughly at the right places but with some unsightly gaps? The shader hasn't been given the hint that it needs to draw the tri's continuously, so that is likely what is happening.

XNA has a class specifically for what you are trying to do, they call it MeshBuilder. MSDN page is here:

http://msdn.microsoft.com/en-us/library/bb197972%28v=xnagamestudio.40%29.aspx

This will take the triangles your OBJ has defined and stitch them together in the way you're expecting. You just need to call StartMesh(), add the vertexes basically the same way you were in your code but with AddTriangleVertex(), and then FinishMesh() will return the MeshContent you want.

Hope this helps.
> 3 votes

---
Tags: xna, models, xna-content-pipeline, import
---


# Question
Title: Making a player move to my mouse when clicked?
How can I get my player to move to the mouse when it is clicked (like in Warcraft)?

So far I have tried:

```
if (Mouse.isButtonDown(0)) {

    if (X < Mouse.getX()) {
        X += Speed;
    }
    if (X > Mouse.getX()) {
        X -= Speed;
    }
    if (Y < Mouse.getY()) {
        Y += Speed;
    }
    if (Y > Mouse.getY()) {
        Y -= Speed;
    }
}

```

But that only does what I want if I hold the mouse down.

# Answer
What I'd do is create 2 new variables that will hold the Mouse.Y() and Mouse.X() and set them when you click. Say we call them previousMouseX and previousMouseY.

Now, in your update method, we need to get the distance between your coördinates. That'll be Mouse.Y() - Y, same thing for the X distance.

After this we will get the angle of the movement so it moves in a straight line to the previousMouse X and Y. We will use sinus and cosinus for this. Then we multiply this by the speed so the object moves at the speed you want.

Example:

```
previousMouseX;
previousMouseY;

differenceX = previousMouseX - X;
differenceY = previousMouseY - Y;

angle = (float)Math.Atan2(differenceY, differenceX) * 180 / Math.PI;

X += Math.cos(angle * Math.PI/180) * Speed;
Y += Math.sin(angle * Math.PI/180) * Speed;

```
> 4 votes

# Answer
Right, so you can't move at a set speed on both the X and Y axis. What you're doing now will mean that objects move faster moving diagonally then in the X or Y direction.

What you're better off doing is finding the angle between your player location and mouse location and then moving the player with a certain speed in that direction.
> 2 votes

---
Tags: java, movement
---


title: How do I load tmx files with Slick2d?

text:
# Question
Title: How do I load tmx files with Slick2d?
I just started using Slick2D and learned how simple it is to load in a tilemap and display it. I tried atleast a dozen different tmx files from numerous examples to see if it was the actual file that was corrupted. Everytime I get this error:

```
Exception in thread "main" java.lang.RuntimeException: Resource not found: data/maps/desert.tmx
    at org.newdawn.slick.util.ResourceLoader.getResourceAsStream(ResourceLoader.java:69)
    at org.newdawn.slick.tiled.TiledMap.<init>(TiledMap.java:101)
    at game.Game.init(Game.java:17)
    at game.Tunneler.initStatesList(Tunneler.java:37)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:164)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:390)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
    at game.Tunneler.main(Tunneler.java:29)

```

Here is my Game class:

```
package game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TiledMap;

public class Game extends BasicGameState{
    private int stateID = -1;
    private TiledMap map = null;

    public Game(int stateID){
        this.stateID = stateID;
    }
    public void init(GameContainer container, StateBasedGame game) throws SlickException{
        map = new TiledMap("data/maps/desert.tmx","maps");//ERROR
    }
    public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException{
        //map.render(0,0);
    }
    public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException{
    }

    public int getID(){return stateID;}
}

```

I've tried to see if anyone else has had similar problems but haven't turned up anything. I am able to load other files, so I don't believe it's a compiler issue. My menu class can load images and display them just fine. Also, the filepath is correct.

Please let me know if you have any pointers that might help me sort this out.

# Answer
> 1 votes
This answer is consolidated from my comments on the original question.

I have used that very same constructor to load maps several times before. That, along with the error message of the exception, leads me to believe that it simply cannot find the file.

Since your comments state that you can load other resources (images and sounds) but not this map that is an even stronger indication that this is the case. In Slick2D Images, Sounds, TiledMaps etc. are all loaded using this same method (the method ResourceLoader.getResourceAsStream).

Did you refresh your project in Eclipse after you created the map file? Can you see the map file from within Eclipse? Make sure you perform the refresh operation on the top of the hierarchy, on the project itself. (Right-click on the project and use refresh.) If that doesn't work, try re-creating the project. (I've never needed to do that tho.)

# Answer
> 0 votes
I have had a similar problem. but have figured out how to make sure it will load. first thing you would do is create the TiledMap object like so

```
public TiledMap map = null;

```

now you just need to tell it not to load the tilesets unless you want it to but in my game i have loaded the tilesets differently

```
public void load(){
     map = new TiledMap("filepath", false);
}

```

# Answer
> 0 votes
Right click on the java app that is giving you the error message. Go to \>RUN CONFIGURATION. Take a look at the MAIN CLASS line. The MAIN CLASS should be the class that has your main class method in it. If it doesn't, look at the left panel and find the main class that is calling your java app. Click on it and make sure that it is set as the main class in the MAIN CLASS line.

---
Tags: java, slick
---


# Question
Title: Create a variety a sprites from a single image in XNA?
I want to be able to take a single image and cut them up into a lot of images to make the sprites. How would I do that in XNA since I only know how to load the texture then use it without changing it?

# Answer
> 3 votes
If you want to cut up a single texture into multiple textures in 2D you can just use the 'SourceRectangle' overload from SpriteBatch.Draw. The SourceRectangle specifies which part of the texture to draw at 'DestinationRectangle'. This is especially useful when using sprite sheets.

See MSDN for further details: http://msdn.microsoft.com/en-us/library/ff433992.aspx

# Answer
> 0 votes
Here is some code that illustrates how to do what you want. As the others have suggested it uses the SourceRectangle overload on the SpriteBatch Draw method.

Imagine you have a square texture 120px x 120px and it contains 9 sprites, each 40px x 40px. We want to draw the one in the bottom right hand corner.

Within the texture, the (x, y) coordinate of the top left corner of this sprite would be (80, 80). Also, we know the width and height of the sprite is 40 pixels.

First we need to define a new instance of Rectangle that holds this top left position along with the width and height.

A rectangle constructor takes in (x, y, width, height) so we would define the source rectangle as follows:

```
Rectangle mySourceRect = new Rectangle(80, 80, 40, 40); //x=80, y=80, width=40, height=40

```

You also need a Texture2D into which you have loaded your 9x9 texture. Finally you need a Vector2 which holds the position.

Then you simply make your Draw call as follows:

```
spriteBatch.Draw(myTexture, myPosition, mySourceRect, Color.White);

```

This should draw the bottom right 40 pixel square of the larger texture. To draw the other sections of the texture you would simply change the x and y coordinates used in the source rectangle.

---
Tags: xna, 2d, xna-4.0, textures
---


# Question
Title: Cocos2D: Upgrading from OpenGL ES 1.1 to 2.0
I have recently starting upgrading my ios game to the latest Cocos2D (2.0 rc), and I am having some difficulties upgrading my texture generation code to OpenGL 2.0.

In the old version I generated images with this code:

```
CCRenderTexture *rt =
[CCRenderTexture renderTextureWithWidth:WIDTH height:HEIGHT];

[rt beginWithClear:bgColor.r g:bgColor.g b:bgColor.b a:bgColor.a];

glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

glVertexPointer(2, GL_FLOAT, 0, verts);
glColorPointer(4, GL_FLOAT, 0, colors);
glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)nVerts);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);

[rt end];

```

But since OpenGL 2.0 works differently this code won't work. What is the best way to use the new OpenGL?

# Answer
> 1 votes
**At First**

* Learn the basics of OpenGL ES 2
* Learn the difference OpenGL ES 2 vs OpenGL ES 1

**Resources**

**Then try sample working examples with Cocos2d & OpenGL ES v2**

# Answer
> 0 votes
You say you are working on texture generation code and the function is called `renderTextureWithWidth`, but the arguments are never used and it looks to me like you're rendering a mesh without a texture.

Very odd.

What you want to do is convert your code to use Vertex Buffer Objects (VBO's). You can find a good tutorial on them here.

---
Tags: cocos2d-iphone, opengl-es, ios
---


# Question
Title: How do I avoid obstacles on a predefined path?
I want is a character to walk along a path defined as a waypoint sequence. For example, a soldier patrolling around a castle.

However, I want the soldier to avoid (dynamic) obstacles, without deviating from the path too much.

How can this be done?

# Answer
> 4 votes
Remove from the path any waypoints that lie inside the obstacle and then use your favorite pathfinding routine to connect the waypoints remaining on each side.

---
Tags: algorithm, path-finding
---


# Question
Title: Collision detection with XNA and TiledLib
I recently started learning XNA and after getting annoyed with creating individuals rectangles each time I wanted to add something I went with TiledLib so I could more easily create levels using the Tiled map editor. My problem is, though, I have no idea how to check for collision using TiledLib. There is very little documentation on it and where people have solved the problem it seems like the code they provide is outdated.

For those who do not know TiledLib: https://bitbucket.org/nickgravelyn/tiledlib

I'm using mostly the code that comes in the demo (such as Map.cs/MapProcessor.cs) because I don't know too much how it works, but it does the job.

I've heard to detect for collision I should use a seperate layer that contains all the tiles I want to collide with, but aside from updating the map to accomdate that I don't know how to actually check for that in my code and make those tiles collide with things. Also, attempting to add a layer to my tile map and then running my game provides this error:

```
Error   1   Building content threw ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException()
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at PlatformerContentPipeline.MapProcessor.Process(MapContent input, ContentProcessorContext context) in e:\Platformer\Platformer\PlatformerContentPipeline\MapProcessor.cs:line 94
   at Microsoft.Xna.Framework.Content.Pipeline.ContentProcessor`2.Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor.Process(Object input, ContentProcessorContext context)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAssetWorker(BuildItem item)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAsset(BuildItem item)
   at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.RunTheBuild()
   at Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent.RemoteProxy.RunTheBuild(BuildCoordinatorSettings settings, TimestampCache timestampCache, ITaskItem[] sourceAssets, String[]& outputContent, String[]& rebuiltContent, String[]& intermediates, Dictionary`2& dependencyTimestamps, KeyValuePair`2[]& warnings)   e:\Platformer\Platformer\Platformer\PlatformerContent\level1.tmx    Platformer

```

I'm at a loss at what to do. If anyone could help me with this, or perhaps let me know of a more updated and more well documented 2D engine for C#/XNA, that would be great.

# Answer
TiledLib will not do collision for you it only converts tmx files into a set of in memory objects that you can use.

I had the same problem as you when using the MapProcessor in the TiledLib example. According to the following forum

The demo code expects that maps do not have null or missing tiles.

You can identify an empty tile by the tileId. The call `TiledHelpers.DecodeTileID` will return a tileId of 0 if that location has no tile. In this case you should not attempt to load the tile at that index.
> 1 votes

---
Tags: xna, c#, collision-detection, tiles
---


# Question
Title: How can I make a shader effect that looks like a lightly shaded pencil drawing?
I want to make a shader effect using OpenGL ES 2.0 that looks like this image:

I'm not sure if this image was painted or is the result of some filter, but I want to create a shader that produces images looking similar. I want to know a Shader algoritm to produce this kind of output!

# Answer
> 18 votes
I can't tell if that specific image you linked was painted that way originally or not, but the resulting effect looks *similar* to an edge detection filter.

Edge detection post-processing is often done using a Sobel filter implementation. For example, as seen here (a CPU-side implementation). The effect can be achieved in shaders as well (here is an HLSL example that is trivially adaptable).

# Answer
> 7 votes
To complete what Josh said, Convolution Matrix is what you want:

Convolution in Gimp
Another link

What you probably are looking for:
Convolution Kernels in OpenGL

# Answer
> 1 votes
If you dont mind having little bit more expensive shader (but it has same number of texture fetches as sobel filter), you can implement frei-chen edge detector.

It provides smoother image than sobel filter.

Great article with example implementation: http://rastergrid.com/blog/2011/01/frei-chen-edge-detector/

---
Tags: shaders, opengl-es2, post-processing
---


title: Can I mix OpenGL and swing?

text:
# Question
Title: Can I mix OpenGL and swing?
I'm working on a small game library for me and some people I know that just handles the window and nothing special that we weren't gonna use. I know how to use OpenGL and stuff I just don't like having to deal with more then one library at a time like OpenGL and Swing so I want to combine them into something basic. Anyway my question is, is there any way I can use OpenGL's rendering onto Swing? I need a simple answer. I also don't want to have to include other libraries into my library, I just want it to be the only jar in the program that isn't program specific.

# Answer
> 3 votes
Yes, JOGL (Java™ Binding for the OpenGL® API) allows exactly that. See also this post for more information about OpenGL and Swing interoperability. Also see XTrans demo on JOGL demos page.

Mixing Swing and OpenGL has a little performance penalty though, so you should consider other options if realtime 3D is your primary feature and Swing is just a small user interface in the game.

---
Tags: opengl, java
---


# Question
Title: Basic isometric projection in Javascript
I've been working on porting an old closed source game to Javascript with Canvas and I've come to a slight problem.

Right now, to display the land, I just have a pretty basic loop that just draws the 44px by 44px diamond-shaped tiles using `ctx.drawImage()`.

It essentially looks like the left side of the image, while I need them to "stretch" to fill the entire tile (like on the right). The tiles have a Z axis which is just in the +j direction on the screen and it's supposed to look like a hill or incline.

Anyway, this leads to my question: Is there a way to correctly do this without using webgl? If not: would it be better to use webgl directly to do this, or use a library to handle it for me?

**EDIT 2:** Well, after thinking for a while, I remembered that affine transformations are only linear (duh), so I won't be able to use certain transformations like transforming corner tiles... so I guess I can use the transformation matrices for the "light green" tiles, but not the pink tile in this example.

**EDIT**: With Phillips answer, I was able to create a few matrices to apply an affine transformation to the tile. However, I pretty much did "guess and check" to calculate the values for *only one* Z-value, **but I can't seem to create a general form of it**.

I'm guessing for different angles (like when there is an incline going from east-\>west, west-\>east, north-\>south, south-\>north), I will have to use a ton of if-statements for each scenario, but that's not much of a big deal.

I have the JSFiddle here: http://jsfiddle.net/awwPP/1/

```
<script>
window.onload = function(e) {
    multiply = function(a, b) {
        return [a[0]*b[0] + a[1]*b[2],
               a[0]*b[1] + a[1]*b[3],
               a[2]*b[0]+a[3]*b[2],
               a[2]*b[1]+a[3]*b[3]];
    };
    multiplyAll = function() {
        var result = arguments[0];
        for(var i = 1; i < arguments.length; i++) {
            result = multiply(result, arguments[i]);
        }
        return result;
    };
    drawDiamond = function(ctx, x, y) {
        ctx.beginPath();

        ctx.moveTo(x, y);
        ctx.lineTo(x+22, y+22);
        ctx.lineTo(x, y+44);
        ctx.lineTo(x-22, y+22);
        ctx.lineTo(x, y);
        ctx.stroke();
        ctx.fill();
    };

    var canvas = document.getElementById('c');
    var ctx = canvas.getContext('2d');
    var z = 2 * 3; // each z is like 2px up
    ctx.mozImageSmoothingEnabled = false;

    ctx.fillStyle = 'rgba(50, 50, 50, 0.5)';
    ctx.strokeStyle = 'rgba(255, 50, 50, 0.5)';

    //left:
    drawDiamond(ctx, 44, 22);
    drawDiamond(ctx, 66, 44);
    drawDiamond(ctx, 88, 66);

    var cos = Math.cos(Math.PI/4);
    var sin = Math.sin(Math.PI/4);

   // just negate
    var nCos = Math.cos(-Math.PI/4);
    var nSin = Math.sin(-Math.PI/4);

    var result = multiplyAll(
      //rotate it so the tile is a square:
      [cos, sin,
      -sin, cos],

      // scale the x axis (although it's actually the Y)
      // to make it look longer
      [50/44, 0,
      0, 1],
      // scew the opposite axis by factor K
      [1, -0.12,
      0, 1],

      //negate the rotation
      [nCos, nSin,
      -nSin, nCos]);

    ctx.setTransform(result[0], result[1],
                     result[2], result[3],
                //dunno why there is an x/y offset
                     0, 10);

    //middle:
    drawDiamond(ctx, 66, 0 - z);
    drawDiamond(ctx, 88, 22 - z);
    drawDiamond(ctx, 110, 44 - z);

    //right:
    ctx.setTransform(1, 0,
                         0, 1,
                         0, 0);
    drawDiamond(ctx, 88, -22 - z);
    drawDiamond(ctx, 110, 0 - z);
    drawDiamond(ctx, 132, 22 - z);
}
</script>

<canvas id="c" width="200" height="200"></canvas>

```

# Answer
> 6 votes
It is not possible to apply an affine transformation to the tile and get the result you want, because affine transformations preserve coplanarity, whereas the shape you need is not flat in the 3D world. Even if you got the outline to match (which can be done), the texturing would be all wrong and cause seams at the junctions.

I suggest splitting the tile in two triangles first. There are two ways to do so, but the first one (vertical split) will probably be easier later on:

The good thing is that it can be done without any additional calculations. You just need to render twice and put **transparency** in the unused part of the images. You can then reuse exactly the same transformation as for your light green tiles:

# Answer
> 2 votes
This is how I'd do it without matrices, sines and divisions. Just integer math. Optimized for clarity, but it can obviously be optimized for speed with few changes:

```
// (0, 0) is at the top of the diamond. This is where we'll start drawing
sourceX = 200;
sourceY = 20;

// How much we move on the X axis for each tile
tileWidth = 30;
// How much we move on the Y axis for each tile
tileHeight = 15;
// How much we move on the Y axis for each unit of depth
tileDepth = 10;

// The size of the field, and the field itself
width = 5;
height = 5;
depths = [
    [0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 1, 2, 2, 2],
    [0, 0, 2, 3, 1],
    [0, 0, 0, 1, 0]
];

function getDepth(x, y)
{
    // Clamp to the borders, but can be modified for wrapping
    if (x < 0)
        x = 0;
    else if (x >= width)
        x = width - 1;
    if (y < 0)
        y = 0;
    else if (y >= height)
        y = height - 1;
    return depths[y][x];
}

function getDrawingPos(x, y)
{
    // Get the drawing position for a given point
    var destX = sourceX + ((x - y) * tileWidth);
    var destY = sourceY + ((x + y) * tileHeight) - (tileDepth * getDepth(x, y));
    return {"x": destX, "y": destY};
}

function drawDiamond(ctx, x, y)
{
    // Just find the points for all the corners..
    var point0 = getDrawingPos(x, y);
    var point1 = getDrawingPos(x + 1, y);
    var point2 = getDrawingPos(x + 1, y + 1);
    var point3 = getDrawingPos(x, y + 1);

    ctx.beginPath();

    // And draw them
    ctx.moveTo(point0.x, point0.y);
    ctx.lineTo(point1.x, point1.y);
    ctx.lineTo(point2.x, point2.y);
    ctx.lineTo(point3.x, point3.y);
    ctx.lineTo(point0.x, point0.y);
    ctx.stroke();
    ctx.fill();
};

function drawField(ctx)
{
    for (var x = 0; x < width; x++)
    {
        for (var y = 0; y < height; y++)
        {
            drawDiamond(ctx, x, y);
        }
    }
}

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
ctx.mozImageSmoothingEnabled = false;

ctx.fillStyle = 'rgba(50, 50, 50, 0.5)';
ctx.strokeStyle = 'rgba(255, 50, 50, 0.5)';

drawField(ctx);

```

http://jsfiddle.net/a4ZbG/

# Answer
> 1 votes
You could solve this in a pure 2d way by using a projection matrix. I wrote a quite extensive answer about how to use projection matrices in Canvas to turn orthogonal tiles into isometric tiles for a different question.

When your map tiles are all stretched in different ways, you will have to change your projection matrix before drawing each tile.

The 3x3 projection matrices which are offered by the 2d context allow you to do all kinds of perspective transformations to map tiles except for perspective shortening (making close objects larger than small objects).

---
Tags: javascript, html-canvas
---


title: C++ Loading DLL Error

text:
# Question
Title: C++ Loading DLL Error
So I'm attempting to fix a OpenGL in Java problem by making a DLL in C++ and then call it from Java but I've ran into an issue. So I'm testing a basic DLL in C++ and I got this error: "error: 'hGetProcDLL' was not declared in this scope|" This is my code:

```
#include<windows.h>
#include<stdlib.h>
#include<cstdlib>
#include <iostream>

using namespace std;

typedef void (*f_print)(string);

    int main()
    {
    //The DLL Is Called OpenGL But I'm Making A Basic Print Function In It To Test It
    HINSTANCE DLLI = LoadLibrary("C:\\OpenGL.dll");
    if (DLLI == NULL)
    {
        cout << "Error loading DLL" << endl;
        return 1;
    }

    f_print print = (f_print)GetProcAddress(hGetProcIDDLL, "print");
    if (!print)
    {
        cout << "Invalid function!" << endl;
        return 1;
    }
    print("FUNCTION!!!!!!!!!");;
    return 0;
}

```

Any idea what's happening?

# Answer
> 2 votes
It’s just that you call your variable `DLLI` then try to use it as `hGetProcIDDLL`.

---
Tags: c++, opengl, java, dll
---


# Question
Title: Collision detection for 2D RTS game in C++
I'm currently working on a real time strategy game in C++, and I need to implement a collision detection algorithm. I need to have a very efficient algorithm because this game will be running on mobile devices, and has potential to have many objects on the screen at one time.

I was thinking that a QuadTree might work for this, but then I realized it could be slow since QuadTree's are designed for static objects, and having many objects moving around the Q-Tree might not be optimal.

So I'm wondering what a good algorithm is for detecting collisions? The objects in my game will just have simple axis aligned bounding boxes to check for collisions, so I need a nice spacial indexing system so an object only checks for collisions with objects around it.

# Answer
Simple spatial hashing will do. Divide your world into equally sized rectangles. Determine the rectangle that the unit is currently in by dividing its position by the rectangles dimensions. Do this for all units, and you will have a list of what units are in which buckets. Then check collisions between units in their buckets and their neighboring buckets.

The performance of this will depend mostly on what size you choose for the bucket, so test out different sizes until your FPS is the highest.

QuadTrees will work, too. In fact, they're closer to the canonical solution for this problem, since in RTS your units will usually not be distributed on the map equally. This is exactly what these dynamic trees are made for. The problem is a QuadTree is a lot more complex than a simple grid, and unless you actually encounter performance difficulties using a simple grid-based solution, you should choose the grid.
> 8 votes

# Answer
If you have AABBs of objects you can use a Recursive Dimensional Clustering algorithm, nicely described in Game Programming Gems, Volume II (by Steve Rabin).

Core idea of a algorithm is to group objects which bounding boxes overlap in one of dimensions and recursively split those groups in means of non-overlapping bounding boxes on other dimensions.

After the process finishes, grouped objects AABBs are colliding, and this may be sufficient considering what you described in question.

I found a nice explanation of this algorithm here
> 2 votes

---
Tags: c++, 2d, collision-detection
---


# Question
Title: Sound not playing on Windows XP - SoundEffect or Song: Monogame
**\*Solution:***** I have a RealTek ALC888. I solved this (OpenAL) by disabling hardware acceleration on my sound (Control Panel \> Sound \> Advanced, disable acceleration).

I'm trying to integrate sound into my Monogame game. I don't have the content pipeline hack -- just straight Monogame (Beta 3) at this point.

(I tried adding the content pipeline, but ran into some issues.)

I added a .wav file to my `/Content` directory, and I can create and instantiate both `SoundEffect` and `Song` classes. However, both show durations of `00:00:00` (on a ten-second long file), and neither plays.

I can call `LoadContent` without any issue. But when I call `Play`, nothing plays.

I've tried a couple of different sounds, and different formats (MP3 and WAV) to rule that out. Only WAV seems to even load without crashing out, but it doesn't play.

**This issue only occurs on Windows XP.** I tested it on a Windows 7 laptop, and the sound plays fine.

**Edit:** I opened a MonoGame issue to track this, and it includes several more details.

# Answer
It seems as though I am not the only one with problems getting MonoGame to run sounds on XP:

> A very simple alternative is using SoundEffect SoundEffectInstance classes. It is incredibly easy to modify your Windows XACT code to use SoundEffect SoundEffectInstance, HOWEVER, **I personally have had problems getting SoundEffect/SoundEffectInstance to work correctly under Windows XP** where as XACT works just fine. So I decided to leave XACT on my Windows game and just use SoundEffect/SoundEffectInstance on Mac.

(Emphasis mine.) Based on this, I can safely assume that MonoGame/XP is broken for audio. Unfortunately, Steam's hardware survey frequently cites around 10% of their user-base uses XP. So it's vital to support it.

To make this work, I has a sad. I already have my game/framework code both split by platform (Windows and Android). I added NAudio to the Windows side, along with this lovely OGG player for NAudio.

To get my framework code to be uniform, I:

* Created an interface on top of XNA's `SoundEffect` class
* Created my own `NAudioSoundEffect` and `XnaSoundEffect` classes (former wraps NAudio, the latter wraps the XNA `SoundEffect` class)
* Use Ninject to inject a factory by platform. It returns the correct sound effect class (`XnaSoundEffect` on all platforms except windows, which gets `NAudioSoundEffect`)

The solution allowed me to have a single `AudioComponent` class with an `ISoundEffect` instance, internally, which is platform-specific. And it works.
> 1 votes

---
Tags: xna, windows, monogame
---


title: Pygame 2D Scrolling Map

text:
# Question
Title: Pygame 2D Scrolling Map
I have currently a pygame program that stores tiles in a 2d list like

```
[[1,1,1]
 [1,1,1]
 [1,1,1]]

```

where the 1 is a tile object. I have the character centered in the middle of the screen, and I am trying to find the best way to make it so the 'camera' scrolls along with the character. I suppose I could have it so that it only draws the tiles that are in the current window range, but I feel like this will cause problems later. My goal is to have the an entire map, say 100x100 tiles that are drawn but only a small section is shown. So the enemies I generate would still be walking around the map, and things would be going normally except I can only see a small part of it. Is there a way I can take advantage of surfaces in pygame to do this more effectively?

Some relevant code.

```
def drawMap(self, screen):
    for y in range(self.height):
        for x in range(self.width):
            self._mapData[y][x].draw(screen, x*48,y*48)

```

This is in the TileMap class and each index is a Tile object, which has a draw method. My initial idea was to change both the range() calls to draw only the area of the map I want to but then I don't know how to account for enemies off the screen because they are defined by their x and y location relative to the TileMap I create.

I am thinking there is maybe something I can do with a larger pygame surface object that I do not realize so I figured I would ask this here.

# Answer
You accomplish the scrolling by moving the camera, and calculating the screen position for a tile based on the current camera position. You can skip drawing of any tiles that are not on screen.

```
def drawMap(self, screen, camera_x, camera_y):
    for y in range(self.height):
        for x in range(self.width):
            tile_position_x = (x * TILE_WIDTH) - camera_x
            tile_position_y = (y * TILE_HEIGHT) - camera_y
            if (onscreen(tile_position_x, tile_position_y)):
                self._mapData[y][x].draw(screen, x*TILE_WIDTH,y*TILE_HEIGHT)

def onscreen(x, y):
    return not (x < TILE_WIDTH or x > SCREEN_WIDTH or
                y < TILE_HEIGHT or y > SCREEN_HEIGHT)

```
> 3 votes

---
Tags: 2d, python, rpg, tilemap, pygame
---


title: Saving an arbitrary sized 2d array

text:
# Question
Title: Saving an arbitrary sized 2d array
I'm trying to create an arbitrary sized(but not infinite) 2d tilebased world. My question is, how do i save a world like this?

My idea was to split up the tiles into bigger chunks and then save those seperately. Let's say you have a world of 5000x5000 tiles, each chunk would be 50x50 and saved in a seperate file. This leaves me with 10000 seperate files, which does not seem optimal. Is there a better way?

# Answer
This is usually ideal - you can also further decide to split things into 'regions'. This is pretty similar to how Minecraft does things and you can probably learn a lot from just examining it. Splitting it into multiple file sis ideal because while it does incur a penalty for opening the file still, it makes things manageable and prevents large seeking times on a single large file on slower drives. You can read up on this post here for more information on the method. Essentially, what you had in mind is a good idea - just try and minimize chunks into optimal amounts. Good luck!
> 0 votes

---
Tags: java, tiles, savegame
---


title: How do I manage multiplayer login?

text:
# Question
Title: How do I manage multiplayer login?
How is the typical login, loading the level and spawning handled?
For example:

1. Client sends "iwanttologinwithcharacterx"
2. Server does some validity checks and instantiates characterx
3. Server sends back "loadlevelx"
4. Client sends "iaminloadingscreen", when finished sends "finishedloading"
5. Server sends "spawnyourcharacterx"

OR just after the "iwanttologinwithcharacterx" the server tells the client to handle steps 3, 4, and 5 without interaction?

I'm confused about what would be the ideal approach with the least room for errors.

Some info: The level in which players begin is always the same. Players can have multiple characters and during the game they often switch levels (this would be linked to my first question, how would I handle that cleanly? Don't destroy the `playerobject` between level load and just change their positions accordingly?)

# Answer
Your process is generally the right idea for a basic, generic multi player game without any specific design goals. However, there is a lot of stuff you should keep in mind that the client/server does not need to be doing. I'm going to list your steps again and annotate them.

**Client sends "iwanttologinwithcharacterx"**

Yes, this is an obviously needed step. Be sure to store a token and add them to the logged in list - at this point your server knows the login is valid.

**Server does some validity checks and instantiates characterx**

Nothing to say here.

**Server sends back "loadlevelx"**

The server can do this but alternatively if they always spawn in the same zone, then the client can load this from a local cache. I advise you send down a 'revision ID' of the map if your game patcher does not handle level patching - this can then be used to verify later whether or not the client would like a new copy of the map.

**Client sends "iaminloadingscreen", when finished sends "finishedloading"**

This is an unnecessary step in most cases, the client does not need to let the server know. Instead, the client can perhaps cross-compare the expected revision ID here and send a 'I need a new map cache' from the server. This gives the added benefit of map caching and live-editing.

**Server sends "spawnyourcharacterx"**

This can be be performed at any point in between, and you can probably spawn it while the map is loading.

Hope this helps!
> 3 votes

---
Tags: multiplayer, loading, levels, authentication
---


# Question
Title: differences in UDK map on different installs
My goal is to create a simple groundplane in UDK (11/2012 version, fresh install) that the user will be able to run around on. My requirements are therefore very basic and I tried to whip something up quickly in the editor. I created a circular (cylinder) plane and applied a material. I added a Blocking Volume, a Lightmass Importance Volume, and a Sky Light. I built everything and get no errors. The map played fine on my system.

I transferred the file to another system with the same version of UDK (also a recent install). When I try to play the map, I plunge to my death. Though I have verified that my player start position is above the ground, I seem to start below the ground looking up at it. What could cause a map that works great on one system have such a positioning issue on another system?

I believe this is a valid question. I'm obviously going to need to systematically test things and I already have tried moving the player start etc. However, I will need to have some idea of what can differ between installs. I'm extremely new to the UDK.

Thanks.

# Answer
I can't give you an absolute solution to your problem, but here are some things that you can do to help narrow it down:

* Verify that the ground plane you made has proper collision settings. Alternatively, if it suits your needs, try using a landscape instead. (http://udn.epicgames.com/Three/LandscapeCreating.html)
* Verify that both systems' maps are using the same game type, world info, and zone info information, by going to the following menus:
    + View -\> World Properties -\> World Info
    + View -\> World Properties -\> Zone Info
    + View -\> World Properties -\> Game Type
* If you are using a custom game type or other custom settings, verify that both computer's ini settings are similar in defaultgame.ini and defaultengine.ini
* If the above don't work, log both the playerstartloc and player's spawn location using the log functionality in unrealscript or in kismet. If these vectors are different, it will help you narrow it down. If you are basing your game on UTGame you may run into problems like this because UTGame performs very specific actions that may not suit your game.
> 1 votes

---
Tags: udk
---


title: AS3 Rect-Rect Collision

text:
# Question
Title: AS3 Rect-Rect Collision
Basically, my game has the player's attack hitbox change based on the attack being performed. I tried to make a simple collision test that takes an enemy's coordinates and have it check to see if it's within the range of the player. I don't want to resort to using Sprites and use `hitTest()` since efficiency is an issue. Anyway, the problem lies in the fact that the function below always returns true (even when the player is nowhere near the enemy).

```
private function quickHitTest(boxLeft:int, boxRight:int, boxTop:int, boxBottom:int, rangeWidth:int, rangeHeight:int):Boolean

return ((boxLeft > (300 - (rangeWidth/2)) && (boxBottom > (450 + (rangeHeight / 2)) || boxTop < (450 - (rangeHeight / 2)))) || (boxRight < (300 + (rangeWidth/2)) && (boxBottom > (450 + (rangeHeight / 2)) || boxTop < (450 - (rangeHeight / 2)))));

```

I having difficulties finding the source of the problem. All help is appreciated.

# Answer
Why make it so complicated? If you have the coordinates of both the player and the enemy you can just calculate the distance and see if it falls within the range. Or am i misunderstanding something?
> 1 votes

---
Tags: collision-detection, actionscript-3
---