# Question
Title: A question about C++ in video game industry
> **Possible Duplicate:**
> Why is C++ used for game engines? How about its future in game engines?

*C++ will remain the AAA video game industry standard, especially indispensible in video game engines till forseable future.*

What does this statement mean? Is it correct?

# Answer
> 3 votes
The truth is, most game developers do not make their own engines, or at least are not in charge of making their own engines. Often, a big developer will use the same engine for several studios. Examples of these are Bethesda, Blizzard, and Valve. They have used variations of the same engines for several games now. What really changes from game to game is usually more along the lines of art, mechanics, and story.

The game engines are really the core of any video game, though. And this is where the coding really begins. If you've ever even opened up any of Bethesda's construction sets, you might realize that their entire game was probably produced using a similar piece of software designed for their engine. But this is already building on a completed engine.

C++ is used for its versatility while remaining efficient, really. I know of very few programs I've written that couldn't have been in some way ported to C++. But at the same time it's old enough to retain the speed of being only two steps above Assembler (C being in the middle). It also retains portability that way. Windows, Mac, and Linux all easily support it. So this is why it is used in game engines.

But I also disagree with the statement you bring up with regards to game development as a whole. You do not need to know C++ to be able to work in video game development. What you do need to know is some form of coding (and C++ is a good one to know for a background). But if you are working on creating a new game engine, I'd agree that it is indispensable.

---
Tags: c++
---


# Question
Title: Why does this collision detection & resolution code only work for one side?
I am having a bit of trouble with my collision detection. It only works correctly for the right side, meaning, if I enter the tile from any other side, it brings me to the right side.

Here is my code:

```
const float spriteWidth = 5.0f;
const float spriteHeight = 14.0f;

float x = position.X;
float y = position.Y;

if (bounds.Intersects(tileBounds))
{
    if ((x + spriteWidth) > tileBounds.Left)
        position.X = tileBounds.Left - 5;
    if (x < tileBounds.Right)
        position.X = tileBounds.Right;
    if ((y + spriteHeight) < tileBounds.Bottom)
        position.Y = tileBounds.Bottom;
    if (y > tileBounds.Top)
        position.Y = tileBounds.Top - 14;
}

```

I just don't see why it would do that. I am calling this function from the Game1.cs Update function, FYI.

And it only works for one tile out of a possible many, but that's for a later question...

Does anyone have an idea why it would do this? Thank you very much.

# Answer
"position" probably refers to the upper left corner of your entity.

```
if (x < tileBounds.Right)
    position.X = tileBounds.Right;

```

The above will move the entity's left edge to the colliding tile's right edge. That's good.

```
if (x > tileBounds.Left)
    position.X = tileBounds.Left;

```

However, this will move the entity's left edge to the colliding tile's left edge. That's bad - it places your entity squarely inside the collidee.

Your top and left checks need to take into account the width and height of your entity.
> 1 votes

# Answer
If Your tile width is less than sprite width, then both conditions

```
if ((x + spriteWidth) > tileBounds.Left)

```

and

```
if (x < tileBounds.Right)

```

might be met at the same time.

Since You're not using "else if" in Your conditions this will lead to setting position.X twice, and since the second condition is setting it to the right edge, finally it will be just that.

I'm not saying that You should do "else if" as this won't actually solve the real problem. You need to consider this scenario what to do when Your tile rectangle is completely contained within sprite rectangle. The decision is up to You how to handle this.
> 1 votes

---
Tags: c#, collision-detection, collision-resolution, bounding-boxes
---


title: Viability of Java as a game language

text:
# Question
Title: Viability of Java as a game language
> **Possible Duplicate:**
> Is Java viable for serious game development?

I have been learning Java for a few months now, and there were a few things I was thinking about based on what I know about Java and games written in it. Is it viable to use it for making video games?

Some things that affected what I was thinking:

1. Java is a very secure language so it might be a good choice for multiplayer games where hacking is an issue
2. It is designed for web portability
3. The way it functions can make it very slow, which is bad for any realtime games
4. This is just something I have noticed, not necessarily linked to Java: if left running for too long it can start to become unstable(?)
5. On the other hand, I noticed that games such as Minecraft uses Java, and those do not seem as affected by those problems.
6. The immutability of several data types: I know it's a security feature, but not being able to re-size an array can get frustrating.
7. This may just a matter of style, but I got into a discussion with my CS teacher about whether or not you should use in-place computing. I mentioned that if you are doing something frame by frame, then it would be better. He agreed, but he also said that in most applications you'd want to retain the original value.

So based on these and other possible concerns/benefits, is Java viable?

# Answer
I have spent a lot of time toying with Java making hobby games. I have only recently converted to C/C++. My answer to your question would be ABSOLUTELY, to an extent.

Java provides some great libraries that can make developing games quite simple: LWJGL, Slick2D and, libGDX are 3 prime examples. Java's simplicity is a godsend when debugging(let's be blunt, C is a total pain sometimes).

However, where Java falls short, is performance. In the 2D field, there isn't much leeway - 2D games aren't usually render/GPU intensive. But when it comes to 3D: LWJGL simply cannot compare to C/OpenGL.

It all depends on how big of a project you are aiming for. If you want to make a 2D game, by all means go with Java. But I think it's safe to say that if you are aiming for 3D graphics with an emphasis on visuals, go with C/C++.
> 5 votes

---
Tags: java
---


# Question
Title: XNA 4.0 - strange blueish alpha with Spritebatch over Skybox
I created a 3D scene and now I wanted to draw a 2D overlay with the `SpriteBatch` class.

That is my rendering code:

```
public void Draw(GameTime gametime)
{
        SceneFactory.Graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

        // Earth
        Matrix[] transforms = new Matrix[earth.Model.Bones.Count];
        earth.Model.CopyAbsoluteBoneTransformsTo(transforms);

        sceneShader.CurrentTechnique = sceneShader.Techniques["Earth"];

        view = viewcam.GetViewMatrix();

        foreach (ModelMesh mesh in earth.Model.Meshes)
        {
            Matrix rotation = Matrix.CreateRotationY(earth.Rotation_Y) * Matrix.CreateRotationX(earth.Rotation_X);
            Matrix model = transforms[mesh.ParentBone.Index] * rotation * Matrix.CreateTranslation(earth.Position);
            Matrix modelview = model * view;

            lightposParam.SetValue(lightpos);

            ambientlightParam.SetValue(ambientLight.ToVector4());
            diffuselightParam.SetValue(diffuseLight.ToVector4());
            specularlightParam.SetValue(specularLight.ToVector4());
            shininessParam.SetValue(shininess);

            diffusetexParam.SetValue(earthDiffuse);
            spectexParam.SetValue(earthSpec);
            normaltexParam.SetValue(earthNormals);
            cloudtexParam.SetValue(earthClouds);
            nightmaptexParam.SetValue(earthNightmap);

            modelviewParam.SetValue(modelview);
            modelviewprojectionParam.SetValue(modelview * projection);
            normalParam.SetValue(Matrix.Invert(Matrix.Transpose(model)));

            mesh.Draw();
        }

        // Skybox
        sceneShader.CurrentTechnique = sceneShader.Techniques["Skybox"];

        transforms = new Matrix[skybox.Model.Bones.Count];

        skybox.Model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in skybox.Model.Meshes)
        {
            Matrix model = Matrix.CreateScale(10.0f) * transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(skybox.Rotation_Y) * Matrix.CreateTranslation(skybox.Position);
            Matrix modelview = model * view;

            modelviewParam.SetValue(modelview);
            modelviewprojectionParam.SetValue(modelview * projection);

            skyboxtexParam.SetValue(skyboxCubemap);

            mesh.Draw();
        }

        spritebatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicWrap, DepthStencilState.None, RasterizerState.CullCounterClockwise);

        spritebatch.DrawString(arial, currentInstance.GetType().Name, new Vector2(80, 150), Color.Green);
        spritebatch.DrawString(arial, currentInstance.getSceneDescription(), new Vector2(80, 200), Color.Green);

        spritebatch.Draw(previousScene, new Rectangle(80, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 110, 50, 50), previousSceneColor);
        spritebatch.DrawString(arial, "Previous Scene", new Vector2(135, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 95), Color.Green);
        spritebatch.Draw(nextScene, new Rectangle(280, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 110, 50, 50), nextSceneColor);
        spritebatch.DrawString(arial, "Next Scene", new Vector2(335, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 95), Color.Green);
        spritebatch.Draw(selectScene, new Rectangle(480, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 110, 50, 50), Color.LightGray);
        spritebatch.DrawString(arial, "Select Scene", new Vector2(535, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 95), Color.Green);
        spritebatch.Draw(terminateScene, new Rectangle(SceneFactory.Graphics.GraphicsDevice.Viewport.Width - 205, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 110, 50, 50), Color.LightGray);
        spritebatch.DrawString(arial, "Exit Application", new Vector2(SceneFactory.Graphics.GraphicsDevice.Viewport.Width - 150, SceneFactory.Graphics.GraphicsDevice.Viewport.Height - 95), Color.Green);

        spritebatch.End();

        SceneFactory.Graphics.GraphicsDevice.BlendState = BlendState.Opaque;
        SceneFactory.Graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        SceneFactory.Graphics.GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
}

```

The problem is, that I either get a blueish skybox and transparent 2D overlays (images and text) or a proper skybox but the 2D overlay isn't transparent anymore (depending on `BlendState.AlphaBlend / Opaque`). Here you can see some screenshots of the problem. I've found this post that references pretty much the same problem, but I already tried to switch the rendering order without any effect. And I'm pretty sure that I did the rendering in the right order (3D -\> 2D, right?).

# Answer
Just to confirm the comment as an answer then, and so it might help anyone else who has the problem.

Double check the `SceneFactory.Graphics.GraphicsDevice.Clear(Color.CornflowerBlue);` line of your code as this is what is responsible, when you alphablend, for your scene to have that blueish tint.

Changing it to `SceneFactory.Graphics.GraphicsDevice.Clear(Color.Black);` as you have done, will resolve this for you.
> 1 votes

---
Tags: xna, spritebatch
---


# Question
Title: Bullets and projectiles in component based entity systems
Currently one of my games engines written for a shooter seems to work correctly.

Currently projectiles are sparse, travel quite slowly and are synced over network they are generated as entities.

But in the future I'll have weapons generating very large amounts of much faster projectiles. So here I wonder if generating a system dedicated to projectiles would be a better idea. I currently want to generate projectile pools to manage the syncing of short lived projectiles without limiting the projectiles count.

Physics and collisions are managed by a physics engine where I can register any type of objects (server and client side).

Is there a better approach to the problem?

# Answer
> 3 votes
To address things like scatter guns and gatling guns, usually you do not create projectiles. Instead you handle rays. Projectiles are not visible so you just add some fx on top of this to give the illusion of firing. Then you check intersections with the ray to detect collisions and spawn a hit effects at collision locations.

It has the benefit of being less sensitive to update rate. Moreover, adding a heat time before firing, for example the gatling gun that rotates before firing, allows to hide latency between client and server in a networked game allowing them to synchronize.

---
Tags: component-based, entity-system, projectile-physics
---


# Question
Title: How should I store levels in a C++ game?
I am writing in C++. I am storing game levels as a 2-dimensional int array. This may be a hacky way of doing things, but I am not ready to change it unless I have to. I store values in the array and then draw them as I read the array. These are constant for me but I need to access them from multiple files.

How can I do this? If I put the level arrays in a header (`.h`) file and include it in many places I get a redefined variable compilation error. Is there a way to define a variable so it can't be used more than once?

How can I go about this in a better way?

# Answer
If you want a variable visible across multiple files, use `extern`:

```
// Globals.h
extern int Data[10][10];

//Globals.cpp
int Data[10][10];

```

However, it makes a lot more sense to load them from file. Even if you don't want to use standard library containers, loading and saving is trivial, and will help you to modify and add additional levels in the future. Also note that you will be able to supply an editor for maps.

Here's sample 2-dimensional C-style array serialization:

```
#include <fstream>

int Data[SizeX][SizeY];

// save
{
    // You can use binary mode too!
    ofstream File ("data.txt");
    for (unsigned y = 0; y < SizeY; ++y)
        for (unsigned x = 0; x < SizeX ++x)
            // you'd need to change it to File.write(...) when using binary mode.
            File << Data[x][y] << " ";
}
// load
{
    ifstream File ("data.txt");
    for (unsigned y = 0; y < SizeY; ++y)
        for (unsigned x = 0; x < SizeX ++x)
            File >> Data[x][y];
}

```

You might also want to add some sort of header to your file - containing map size, game version, author of the level etc. However, loading of this data is trivial and I leave it as an exercise :)

I'd also take a look at std::vector. Contrary to your belief, it's *a lot easier* to use than C-style arrays. It was designed to be!
> 6 votes

# Answer
I made a tile based breakout game, and stored the levels in 1 txt file. 0 was no block, and a 1-9 was a block that would take that many hits. I suppose it could be expanded to use letters as powerups or special block. But they were formatted to be a certain width, and a certain length, with 1 line between each level.

ex

```
11111
00000
00010
11101

11001
02223
12321
11111

```
> 2 votes

# Answer
Unfortunately no, you can't define multiple variables with the same name. Suppose the compiler lets you do so, but when you're going to use it, how do you know which one are you talking about?

So in general you have three choices:

1. Make each level into a different variable. Instead of `int[] level`, do `int[] level1`, `int[] level2` and so on. It's the easiest to understand, but scales the worst, as you have to hardcode everything, and will get bored writing everything as you reach more levels.
2. Make them into an array. Instead of `int[] level`, do `int[][] levels`, and store the first level in `levels[0]`, the second one in `levels[1]` and so on. You can either initialize them statically in a single huge file, or dynamically with a bunch of files.
3. Make your levels load dynamically from data files. This is what professional games do, and is a very positive thing because you're separating code from data. So you keep your `int[] level`, but initialize it by reading a bunch of `int`s from a file. Google "reading ints from a file c++" for more information on how to do this.
> 0 votes

---
Tags: c++, sdl, storage
---


# Question
Title: What's a good Flash game development tutorial, in FlashDevelop, for an absolute beginner?
Ok, here's my situation: I'm tutoring a 14yo homeschooled student with very little previous programming experience, and I'd like to teach her how to program. I think that Flash Actionscript 3 is a good resource for her to start out with, mostly because she seems to have an interest in game development.

I've decided that FlashDevelop, used alone, is the best interface for her to use, especially as she becomes more proficient in Flash. The trouble is, while I am an extremely competent Web programmer in other languages, I have no experience with Actionscript at all, and I can't find a good tutorial for her to use.

The tutorial doesn't need to have the algorithmical basics of programming, like the concept of loops, if statements, OOP, etc; I can teach her those. What I need is a tutorial that teaches Actionscript SYNTAX and walks you through the steps of game development in FlashDevelop. Once I have that, I can do everything else.

Can anyone help me?

# Answer
try with a game, i think it is the best solution to learn : you will find some examples here :

35-flash-game-development

and this one especially is good to learn :

avoider game tutorial
> 1 votes

# Answer
To get familiar with the Flash Develop IDE: http://active.tutsplus.com/tutorials/beginners-guide-to-flashdevelop-intro-basix/

As Paul suggested, the avoider game tutorial is great.
> 1 votes

# Answer
The most comprehensive guide I've seen so far is this one from GamedevTuts+. It gives you a complete overview of Flash gamedev, pointing out very interesting tutorials and resources.
> 0 votes

---
Tags: actionscript-3, flashdevelop
---


title: 2d shapes in XNA 4.0?

text:
# Question
Title: 2d shapes in XNA 4.0?
Having some experience of XNA but none of 3D programming. I have an idea i want to realize but i have not decided to do it in 3d or 2d. Im not sure which one will be best in XNA.

I want to have a shape like a blob that can reshape depending on input. The morphing does not need to be very advanced. It could be a circle (2d) or globe (3d) that just has one point that moves slightly in a random direction.

In ASP.NET i have made this through the 2d Draw classes where i can make lines, circles, squares etc and then modify the points that makes them up. But it seems to me that XNA does not have classes for making 2d shapes (can i get this confirmed?). If it had, then this would be the quickest solution for me.

# Answer
> 1 votes
You'll need to use a library or make your own.

Here's one you can use: http://www.drippingflames.com/xna/

# Answer
> 0 votes
You are right. XNA does not have a build in method for creating primitives (eg. 2D circles) and the way that I've had to implement it previously is by building my own primitive shape builder that pieces lines together.

The good thing about this is that there's loads of examples out there on the net how to do this, and you might bump into some source code that you could reuse (with the writers permission of course).

A quick search has revealed this project on Bitbucket : https://bitbucket.org/C3/2d-xna-primitives/wiki/Home

And a good looking tutorial if you want to read up on the science : http://www.bit-101.com/blog/?p=2832 (he talks about drawing a circle too)

# Answer
> 0 votes
I'd suggest sticking with a 2D game. At least then you won't need to muck about with matrices (as far as I can remember). On the other hand, if you want primitives then you'll need to deal with matricies anyway, as XNA only has 3D primitives. So, if you really have your heart set on 2D primitives, just use these with the Z component set to 0.

I'd suggest looking at http://rbwhitaker.wikidot.com/primitives-tutorials to get a handle on how to draw 3D primitives. Actually, http://rbwhitaker.wikidot.com/xna-tutorials has great tutorials covering a ton of stuff from 2D to 3D to HLSL and more. It was my starting point with XNA.

But for 2D Primitives, go and at least check out Luis Estrada's suggested library.

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


title: Tools for creating 2d tile based maps

text:
# Question
Title: Tools for creating 2d tile based maps
What are some tools I can use to create 2d tile based maps?

Please provide the information below, and try to limit to one tool per answer.

* Name
* Link to website
* General features
* Export format
* Anything else you deem noteworthy

# Answer
Tiled Map Editor

From the website:

> * General purpose tile map editor with XML-based map format
> * Supports orthogonal and isometric maps
> * Custom objects can be placed with pixel precision
> * Full undo/redo and copy/paste support
> * Add custom properties to tiles, layers, objects or the map
> * Automatically reloads tilesets when changed externally
> * Resize or offset your tile map later as needed
> * Efficient tile editing tools like stamp and fill brushes
> * Supports input/output plugins to open and save files in custom formats
> 28 votes

# Answer
**The Best of the Pack**

Tiled Map Editor http://www.mapeditor.org/

Mappy http://tilemap.co.uk/mappy.php

TME - Tile Map Editor http://tilemapeditor.com/

TileStudio http://tilestudio.sourceforge.net/

tIDE (Tilemap Integrated Development Environment) https://colinvella.github.io/tIDE/

Gleed2D https://github.com/SteveDunn/Gleed2D/wiki

Tile2map http://www.tile2map.com

**Worth a Try / Alpha Versions**

TaT Tile Map Editor http://kotisivu.dnainternet.net/ttilli/tilemapeditor/main.htm

Simple Tile Map Editor http://devlinslab.blogspot.com/2007/11/simple-tile-map-editor.html

Flan Map Editor http://flixel.org/forums/index.php?topic=225.0

Tile Map Editor VB.Net http://sourceforge.net/projects/tilemapeditor2d/

**Abandoned / Unfinished**

JEngine Tile Map Editor (no description, no screenshots) http://jenginetilemapeditor.codeplex.com/
> 15 votes

# Answer
Ogmo Editor

From the website:

> **Here's How It Works**
>
> After deciding to use Ogmo Editor for a game, the first step is to write up a "project file" for that game. A project file is just an XML file defining all the tilesets, objects, layers and settings for a project. Once you've got that done, you open it in the editor and you're good to go - you can start creating, editing, saving and re-opening levels. If you need to, you can add new tilesets and objects to your project along the way and all your old levels remain compatible, so you aren't required to define every asset you'll eventually use right away.
>
> **Getting Your Levels Into Your Game**
>
> Exported levels are just XML files, and the format is largely defined by you in the project file. Ogmo Editor was designed with Flash in mind, but most modern programming languages have robust XML support. If you're lost, check out the tutorials section - there might be an article on using Ogmo Editor with your language or library of choice.
> 3 votes

# Answer
My old favorite was Deluxe Paint (that dates me). I currently use Paint Shop Pro which has a handy 'convert to seamless texture' feature. Not as good as a true tile-symmetry editor, but good in a pinch.
> 3 votes

# Answer
It might be worth creating your own level editor and integrating into your game - then you can also allow players to create their own levels.
> 2 votes

# Answer
Cosmigo's Pro Motion is one of the old-school favorites, even though it's more of a paint tool than a level editor proper. Great for sprites as well as tiles; lots of "grid" functionality. Their features page details a lot of this, and talks about new tile map functionality:

```
* RGB channel depth can be selected from 222 to 888
* 16 color PNG support
* Optimize tile based graphics for hand held systems that have a limited number of colors per tile like Gameboy Advance etc.
* Support for tile painting to create endless textures
* Tile map editor with auto optimization, mirroring, felxible export
* AnimStrip files can be created containing frames side by side in a bitmap, PNG/BMP

```
> 1 votes

# Answer
Tume. http://en.wikipedia.org/wiki/TUME Worth it if just for watching their tutorials on how they approached certain problems (they use layers in many more ways than for tiles, which is very smart as it allows you to be game agnostic without forcing a paradigm on the user). Interesting features, used for numerous commercial games back in the day. No parallax editing (would be hard anyhow, as the parallax layers are generally driven by logic - you'd need your game as a plugin - which brings me to the following point - your game makes a great map editor. I have always done in game editing, it allows you to "live preview" and sets you up for user generated content to boot.
> 1 votes

# Answer
Minimal Javascript Tile-based Map Editor

http://samlancashire.com/mapeditor

I made this for my own game, but decided to polish it up a bit for general use. It's very simplistic, but will get the job done.

Exports map as two-dimensional javascript array. The array items contain the coordinates of the tile relative to the tileset. For example

```
map1[x][y] = '0,0'; //would be top left tile in tileset

```
> 1 votes

---
Tags: tools
---


title: XNA 4.0 Model into parts

text:
# Question
Title: XNA 4.0 Model into parts
is there a way to split a .fbx model into parts, and move those parts individualy in XNA 4.0 ?

Thanks

# Answer
Perhaps when you draw each part you could give each one it's own world matrix, remembering that each part is still offset from the origin of the model as a whole.

```
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (ModelMeshPart part in mesh.MeshParts)
    {
         ((BasicEffect)part.Effect).World = ((Matrix)part.Tag).worldMatrix;
         ((BasicEffect)part.Effect).View = viewMatrix;
         ((BasicEffect)part.Effect).Projection = projectionMatrix;
    }
    mesh.Draw();
}

```

Of course, this means that you'll need to find a way to identify each part and assign each of them their own special `worldMatrix`, because the `Tag` is always `null` by default.

Besides that, the only other solution that's immediately appent to me is to export the objects individually and treat them as their own entities.
> 1 votes

---
Tags: xna, models
---


# Question
Title: Rotate an object around a point in Ogre3D
> **Possible Duplicate:**
> How can I rotate about an arbitrary point in 3D (instead of the origin)?

I am new to 3D programming and I have been using Ogre3D lately to get a grasp of it.

What I am trying to do is the following:

I want to make an entity rotate around a point (probably the parent SceneNode) in a circular way only in the X and Z axis.

I have tried using yaw/pitch/roll and rotate but no luck, and I can't find any good tutorials/how-tos online.

# Answer
I finally did it using the following pseudo-code:

```
parent = sceneMgr->getRootSceneNode()->createChildSceneNode();
child = parent->createChildSceneNode();
child->attachObject(entity);
child->translate(10,0,0);
parent ->rotate(Ogre::Quaternion(Ogre::Degree(10), Ogre::Vector3(1,0,0)) , Ogre::Node::TransformSpace::TS_WORLD);

```

For anyone who has the same problem as me.
> 3 votes

---
Tags: rotation, ogre
---


# Question
Title: Change the tilemap shown on stage in Flixel
I am building a simple platformer using Flixel, beginning with the source code from Flixel creator's EZPlatformer . I would like to adjust the level's tilemap when the player sprite enters/overlaps with a sprite representing a door. I use Flixel's built in function to track if the player overlaps the door sprite.

`exits` is a class level variable: `public var exits:FlxGroup;`

I call this function in the Update event to check for overlap: `FlxG.overlap(exits,player,UpdateScreen);`

I successfully catch when they overlap, however when I try and load the new tilemap, the old one continues to show. I use this function to attempt to update the tilemap on the screen:

```
public function ChangeScreen():void
        {
            //load the screen and locations of sprites(e.g. player, exits) based on current screen
            switch(currentScreen)
            {
                case 1:
                    //load tilemap
                    level = new FlxTilemap();
                    level.loadMap(FlxTilemap.arrayToCSV(data1,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO);
                    add(level);
                    break;
                case 2:
                    //load new tilemap
                    level = new FlxTilemap();
                    level.loadMap(FlxTilemap.arrayToCSV(data2,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO);
                    add(level);
                    break;
            }
        }

```

I thought that I would need to first call `remove` on `level` to take it off the stage, and then call `add` on it, however, when I do that, the tilemap does not show up at all. What is the correct way to do this?

# Answer
When you set level to a new value, you lose the reference to it in your code. Its parent FlxGroup still maintains a reference to it in its members array, however, so it continues to display. Using `remove` is a good idea, but I suspect you're doing it like this:

```
level = new FlxTilemap();
level.loadMap(FlxTilemap.arrayToCSV(data2,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO);
remove(level); //WRONG
add(level);

```

You need to remove the level while your reference still points to the old level, like so:

```
remove(level);
level = new FlxTilemap();
level.loadMap(FlxTilemap.arrayToCSV(data2,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO);
add(level);

```

Also, make sure that you're removing the old level from the same FlxGroup that you added it to.
> 3 votes

---
Tags: flash, actionscript-3, tilemap, state, flixel
---


# Question
Title: Is there an AIR native extension to use GameCenter APIs for turn-based games?
I'm planning a turn based game using the iOS 5 GameCenter (GameKit) turn-based functions. Ideally I would program the game with AIR (I'm a Flash dev), but so far I can't seem to find any already available native extension that offers that (only basic GameCenter functions), so my questions are: Does anyone know if that already exists? And secondly how complex a task would it be to create an extension that does that? Are there any pitfalls I should be aware of etc.?

\** UPDATE \**

There does not seem a solution to the above from Adobe. For anyone who is interested check out the Adobe Gaming SDK. It contains a Game Center ANE which I've read contains options for multiplayer but not turn-based multiplayer, at least it's a start. Comes a bit late for me as I've already learned Obj-c!

# Answer
Thanks to jimmyo for mentioning our GameKit ANE. Our updated version includes support for both turn-based and real-time Game Center matches.

Phil, the task is not complex with our high-level API. You listen to three important events, and make one call each to advance turn, assign match outcome, and end game.

This ANE also provides a low-level API to the FULL native GameKit framework if you need more advanced functionalities. That's right, the COMPLETE native GameKit framework with all the GK classes, properties, methods, delegates, and callback functions!

You can get it at https://airextensions.net/shop/extensions/game-kit-by-vitapoly/.
> 2 votes

---
Tags: iphone, ios
---


title: Twin stick shooting with keyboard

text:
# Question
Title: Twin stick shooting with keyboard
In a top down shooting game, what alternatives are there for input if I want the direction of movement to be independent from the direction I'm shooting at? I'd like to avoid shooting with the mouse as it's much too precise, but alternatives that make it harder to aim could also work.

Alternatives I've already considered are:

* Arrows for movement and WASD for shooting. The Binding of Isaac does this and it has two problems. It only allows for shooting in four directions, where I'd prefer at least eight; and most keyboards start ignoring some key presses if you press more than 2 keys at one, making it impossible to move in a diagonal while shooting.
* Arrows or WASD for movement, shooting direction becomes fixed in the direction you are facing when you start shooting. I don't remember where I saw this. This allows for shooting on any direction, but you have to stay still for a moment to change shooting direction, and it just doesn't feel very dynamic.

# Answer
> 5 votes
If, in your question, "twin-stick" is a misnomer and you just mean top-down shooter, that's different... My answer is going to assume you do mean "twin-stick."

\<sidenote\>In the Binding of Isaac, only shooting in 4 directions was a specific design decision. (I can't find a source for that, but I recall Edmund saying it was intentional.) It's worth noting the game does let you curve shots by shooting while you're moving.\</sidenote\>

If you're targeting a controller as the preferred method and supporting keyboard input, you're going to need to emulate that behavior as much as possible (or write two completely different control schemes into your game and design for both ways of playing).

Two controller sticks is rather precise already. I'm not sure what you don't like about mouse to shoot but I'd reconsider avoiding it. I'd argue that it's less precise than two joysticks since you have to move the mouse to different sides of your character, as opposed to just switching the direction of the mouse. Are you limiting the angles you can shoot in if you're using a controller? If you're not, that's potentially going to suck for keyboard players.

If you must depart from it, consider:

* Allow movement with WASD and shooting in 8 directions with IJKL. Worst (realistic) case is 4 simultaneous letter keys. I don't think that should be a problem for most keyboards.
    + It gives you 8 discrete directions to move and shoot separately. It doesn't give you the finer control but is very usable if the game design accounts for it.
    + Back in the day, I played the crap out of Robotron on the Apple\]\[ which used a similar scheme (ESDX and IJKM). It was quite playable.
* Allow movement with WASD and lock shooting in the direction that the player was facing when he started shooting. Like Hyper Princess Pitch and Voxatron do.
    + If you're moving down and hold shoot, you start shooting down and stay facing/shooting that way regardless of where you move until you let go of shoot.
    + Like you mentioned, it does have the disadvantage of having to move toward what you want to shoot for long enough to face that direction and start shooting. It makes running away from a large mob tricker.
    + I don't like this scheme myself but in the games I linked above, it does work.
* Allow movement with the mouse and use WASD (or similar) to shoot, like one of the control schemes in Echoes.
    + It's a little weird, but it's a possibility. Making the player follow the mouse gives you fine control over your movement while keyboard input still limits your shots to less precise angles.
    + Viable if your game is reliant on fine grained movement and less so on shooting.
* Mouse only. (Yeah, we're departing from twin-stick shooter-dom here.) Something like Click-to-move, Shift-click-to-shoot
    + It works in Diablo and Torchlight.
* The already suggested forward/backward, strafe, rotate, shoot scheme. But, I'd suggest revising it to not have an extra button to toggle strafe v rotate; add two extra buttons so you can strafe and rotate at the same time. The top-down levels of Contra 3 on SNES did it that way and it was pretty effective.
    + Suggested scheme
        - WS to move forward/backward, AD to strafe, QE to rotate
    + This would also let you translate your controller input the same way (LT and RT to rotate), avoiding significant disparity between your input methods.

Really, it all boils down to how responsive and orthogonal you want your two actions (moving and shooting) to be.

# Answer
> 3 votes
Essentially you have yourself the challenge of overcoming deep rooted control schemes. Attempting to apply the style of device A to device B doesn't work well. If it did, there wouldn't be much of a reason for device A.

I think any choice of keys will be kind of strange. There's a reason twin stick shooting isn't very natural on the keyboard. It doesn't have twin sticks.

Anyway you slice it, it's going to be difficult to limit to two keys maximum and keep a natural feel. Since running diagonally is taking two, you'd be unable to shoot. The two key limit does depend on the hardware, and that's something you'll need to warn your users about.

I'd have the option available for using just the keyboard, but support mouse aiming and gaming controllers. The mouse aiming would be discrete as well, only allowing the eight directions the keyboard or gaming controller does.

If you're worried about it feeling natural, require a gaming controller. Otherwise just pick your own controls and hope the user is able to adapt. Other options could be:

* WASD for movement. Numpad for shooting.
* WASD for movement. UIOJLM\> for shooting.

# Answer
> 3 votes
I would do WASD for movement and mouse for shooting, with the aim restricted to 8 directions. So in other words instead of pointing directly at the mouse cursor you point in whichever of the 8 directions is closest to the mouse cursor. I don't know off the top of my head the code to do this but I'm pretty sure it'll be something simple involving atan2()

# Answer
> 0 votes
I remember a game, back in the old days, where left and right would rotate you, until you held down shift, then left and right would strafe instead. Forward and back would move you in the direction your character was facing.

Using this approach you could get shooting in a full 360 degree circle, yet still have a 'fine adjustment' mode, strafing to get the perfect shot off.

It also allows for greater control of a character, able to shoot in any direction you want and still able move at the same time.

The game as I remember was very fast paced and sometimes it would be better to strafe out the way of a bullet than turn 90 degrees and walk forward. It would also very easy to get two players on the keyboard for this control mechanism.

Otherwise you could always add some random deviation to the angle of the shots if you were using a mouse. Simulating a bullet spray, rather than an accurate 'click to kill'.

---
Tags: game-design, input, keyboard, shoot-em-up
---


title: Keeping Track of Position OpenGL

text:
# Question
Title: Keeping Track of Position OpenGL
I have a sphere in my 3D world located at the origin. I have models orbiting it and I need to keep track of each models' position (x, y, x coordinates) as well as update their bounding boxes for collision detection. I have calls to `glRotate()` and `glTranslate()` but I'm not sure how to keep track of this. Should I create a `position` matrix and apply rotations and translations to it? Any help on that would be great!

Also if there is a better way to do this I am open to anything.

# Answer
> 1 votes
Sounds like you're using very out dated OpenGL code. You should look into modern techniques (a quick Google search for some modern OpenGL tutorials should do it), I wouldn't waste much more time learning/using the dated code you're using now.

Beyond that, there are lots of ways to organize your world and the objects you store in it. The **very basic** example is to just have a class that represents an object in your world:

```
public class DrawableObject {
   Vector3f position;
   Vector3f rotation;
   Model model;
   BoundingBox bounds;
}

```

Then create your objects using these classes. When you're updating the position of the orbiting objects, update the `DrawableObject` instance that represents them. Then when you're drawing the objects, use the `position` and `rotation` stored in the `DrawableObject` instance.

Basically, you don't want to send the updates to the graphics card and not have them stored anywhere on the CPU side. You want to update something locally and then use that data to update the data on the graphics card.

Eventually you could move on to something more complex like an entity component system. But for now, I'd stick with learning modern OpenGL and keeping track of the objects in your world in a more organized way.

---
Tags: java, android, 3d, opengl-es, libgdx
---


# Question
Title: How to write my own 3-D graphics library for Windows?
I want to forget about DX, OpenGL, SDL, etc. Basically any low-level libraries I'm against.

I would like to write my own OS-compatible library that is closer to the OS-API for window-systems, and make my own low-level graphics library that makes adequate calls to the OS drivers and such.

How should I get started?

# Answer
I assume you want your library to work for more than one specific videocard. So you will need to make assumptions about the minimal set of features current videocards support. You can assume that this minimal set is basically the instructions that DirectX and OpenGL require *(so that's strike one for writing your own library)*.

Of course you could use these instructions and use them as you want in your library. However you still need a way to talk to the GPU, now I don't think there is a way to do this (without severe reverse engineering and guaranteed differences between different models) without using the driver provided by the GPU vendor (AMD, nVidia or Intel usually) *(strike two)*. Now of course you will have to talk to the driver in a way it understands... and well unfortunately for you the driver understands only DirectX and OpenGL *(strike three, you're out!)*

So theoretically there is a way to do what you want, but it would involve writing your own driver for a GPU which, without the help of nVidia or another GPU vendor is neigh impossible, and the end gain would be neligible since you would still have only the instructions nVidia and other GPU vendors found useful for implementing OpenGL and DirectX.

Since your question has a lot of overlap with this one on stackoverflow you might want to read the answers there as well.

Edit:

If you tell us *why* you are not content with DirectX and OpenGL we might be able to help you with that underlying problem.
> 3 votes

---
Tags: 3d, graphics-programming
---


# Question
Title: How do you maintain content size vs. content quality in a mobile application?
I am developing my first Cocos2d iPhone/iPad game that includes quite a few sprites, I would need approximately 80 different. As this is for both normal and HD displays I have 2x of each sprite. I am using TexturePacker to optimize the thing.

I would like to ask if there are any rules-of-thumb, tricks, ideas etc. to adjust to in regards to size of content, quality and how you maintain high-quality HD-based graphics due to its size vs. the device memory sizes?

Also, is it a good idea to only have one copy of the sprites and scale it using code?

# Answer
> 0 votes
There are multiple ways to save space on textures These are ones I have seen and used (with internal dev tools):

You can reduce the colorspace of some of your textures, you don't need 32bit for everything.

You can use very modest palettes for most (very) small textures. You can even share those palettes across textures.

You can use color-keys for some textures which are reused for different teams but with different colors. This way you don't end-up with 4 versions of the same texture.

You can remove alpha from textures which don't need it and use a given color as background.

Monochromatic textures can be given a color at runtime and they only use 1 bit per pixel without alpha. Otherwise you only need to store the alpha value. (fonts for example).

You can also take all your textures and compress them into one file (this can be advantageous over compressing each file separately).

You can reuse some textures across resolutions/screen sizes.

As to using only the highest resolution files and scaling them on the client this can work but you should make sure it all scales down well. If some scaled textures don't look good you can add the lower resolution version only for those in your app.

To speedup the loading time during scaling/uncompressing you could create a cache on first launch with the desired scales/colors/alphas on the device and load those subsequently to avoid expensive loading/processing between scenes/levels... This can save you if use many optimization techniques and you have a lot of loading/unloading to do. But don't rely on having the necessary disk space every time.

# Answer
> 0 votes
If you have a lot of sprites it could certainly be an option to scale down high-res assets on devices with lower resolutions. These devices also usually have a lower maximum texture size, so you can't just use the high-res assets as textures.

To go about this you could use the Quartz 2D API (basically create a bitmap-context and draw your image with the desired size using `CGContextDrawImage`). Then you can use the `CGImageRef` you get and add it to the `CCTextureCache` as there's already a built-in function for this. Once you done this, you have the `CCTexture2D` ready and you can use it for sprites etc.

Loading the data from pre-rendered files is going to be faster though. If you have lots of sprites, it might have a significant impact on the loading time of your game, so you'll have to try if it's worth trading loading-time for application-size.

I'd say if you can fit the application into the new 50 MB limit (download limit for cellular networks) with the above trick, then do it. If your application will get larger anyway, I think it isn't worth the effort.

Another thing you might want to check out first is a PNG optimizer like ImageOptim. There's even a small guide for iOS optimization and what you'll have to change in XCode too. I updated an app for iPad 3 and managed to have both low- and highres assets in there without increasing the app-size compared to the previous low-res version (although I only had very few assets and also ones that can be compressed very well without losing quality).

# Answer
> 0 votes
I'm not familiar with iOS specifically. For my Android game, I tried the "make big images and sample it down" thing people usually say. It looked quite odd.

For my current iOS/Android game, I'm using vector images instead; I create them in Flash (CS3), then rasterize them in-game depending on the size of the size of the device's display surface. It works quite well, but you need to rethink how you lay things out.

An alternative method I tried in the past is keeping multiple sets of assets, and dynamically picking the right set at compile time -- so making an HD build and a non-HD build.

You can try all three methods and see what works best for you. It's not just about graphics, it's about sustainably maintaining your workflow with your tool chain.

---
Tags: sprites, cocos2d-iphone, objective-c, spritesheet, ipad
---


# Question
Title: Efficient path-finding on 2D tile-based multilevel map
It's a question I've been thinking about for some time... How do you effiently find a path on a 2D tile-based multilevel map? The map I use, for example, is 2048 on 2048 tiles wide. It has 14 levels and levels are connected by stairs, ladders, rope holes, ...

How would you introduce level-changing tiles into A\* in an efficient way? I know it is possible to add multilevel path-finding by just adding edges from an up-node to the corresponding down-node. But then path-finding isn't very efficient.

For example. What if the current node (e.g. \[100, 100, 7\]) is directly under the goal (i.e. \[100, 100, 8\]), and we can't go up anywhere near the current node. Instead we first have to go down some levels, and then up again, only then to reach the goal. A lot non-existing paths will be considered (= a lot of time and computation) before we finally find an existing path.

Feedback appreciated, Gillis

# Answer
That would depend on what you're using for your heuristic. However, even if you're using shortest distance, the search algorithm will still work. It will spread out evenly until it finds somewhere to go down.

If you're already doing that and just want to find a way to improve the speed, there's a few options you can use.

* **Add precursors to your search**. If the result is on the next level down, add a requirement that the algorithm must first find a way down. The heuristic for this can be an average of the distance from all the ways down on the current level. Though you may find a way down that's not connected to part of the lower level you want to go to.
* **Add "reachability" information to your grid**. Do a breadth first search on each level after it's created. Mark each tile that's reachable with a "reachability" zone ID. Continue this until every tile is marked. For example, each tile with the ID "1" is reachable from every other tile with the ID "1" *on the same level*. Now when you're searching for a way down, you can rank the ladders based on which zone they connect to. If the tile you're trying to reach on the next level down is in zone "4" and you have a ladder on your current level that leads to zone "4" you can head for that one directly.

You can even extend the "reachability" idea to extend multiple levels. I would use a separate ID for that. This second ID would basically tell you if one tile was completely disconnected from another, so you could forgo the search entirely pretty quickly.

Basically the best way to speed up the searches is to add more data to your world. With better data your algorithm will be able to make better decisions about which paths to try and which to avoid. All in all, speeding up your search.
> 3 votes

# Answer
There's nothing intrinsic to the multi-level aspect that makes this harder or less efficient. A regular heuristic should work fine on a 3D map just as it does on a 2D map. What seems to be the issue for you is that certain edges make the graph maze-like, which makes the heuristic less effective. It's just a side-effect of your chosen design that these edges tend to be the vertical ones.

I would therefore suggest an approach that prioritises the vertical route before the overall route. Preprocess the map to have a graph of vertical connections between the levels, with the relevant distances between each connection precalculated. This lets you create a top-level path from one of the 14 levels to another, and you then need to construct the start, middle, and end of this path. The start is the route to the first vertical connection, the middle is the route from each vertical connection to the next, and the end is the route from the last vertical connection to the destination. Depending on memory availability it may even be practical to precalculate all the segments of the middle parts so that you only need to run A\* on the first and last levels, since everything in between can be looked up from a table.

This won't necessarily produce the shortest path, as the distance travelled on the first and last levels might not lead to the optimal vertical connections. But the path is likely to be among the shorter options. You might consider running some tests and comparing the length of these paths with the slow-but-optimal naïve A\* search to see how often the length is suboptimal, and how often that happens.
> 2 votes

# Answer
I honestly don't know the A\* algorithm, but I know it's an extension of Dijkstra, and Dijkstra's doesn't have a limit to the number of nodes connected with each node. Here, the nodes are the tiles, so I guess you could check for every tile the algorithm visits, if it's a tile connected to a ladder, rope, etc, and add that tile to the path? Just guessing. Also, if each level forms a connected graph, avoid going through all levels but chekcing if starting and end points are in the same levels.

Hope I helped something, I've programmed a couple of algorithms to find paths that had things like yours, levels and all that (from another perspective), and I didn't have any particular trouble, I just did what I told you.
> 0 votes

# Answer
Some reading for those unfamiliar with HPA.

Some points in pseudo random order:

* HPA is perfectly applicable in 3D.
* It may be wise to shape the clusters according to where paths are expected to be, in this case keeping them 1 tile high is probably appropriate.
* A cluster may internally be split so that two entry points do not have a connecting path within the cluster, this is why your grand scale algorithm search a graph of exit nodes rather than clusters, since this graph will reflect the unconnectedness.
* A\* lose effectiveness as the terrain grow more mazelike, this is true for HPA as well, but it remains a clear performance improvement.
* It is possible to add more levels to the optimization, for instance you could group your 16x16 clusters into 64x64 superclusters, further reducing the number of nodes in the initial graph.
> 0 votes

---
Tags: 2d, algorithm, path-finding
---


title: DirectX Objects in a struct

text:
# Question
Title: DirectX Objects in a struct
I am playing around directx lately and I am learning from rasterek.com tutorials. He passes pointers to directx objects (like ID3D11Device, ID3D11DeviceContext etc.) for almost every class he creates. Wouldn't be a better approach to create some kind of singleton or event a simple struct that keeps all of the objects? I don't know too much about game engine designs and I don't understand his purpose, for me it's just more work to do.

Example: His code:

```
bool Class::initialize( ID3D11Device* device ) {
    device->doSmth();
}

```

My idea:

```
struct DXObj {
    static ID3D11Device* device;
}
bool Class::initialize() {
    DXObj::device->doSmth();
}

```

# Answer
This is more just a general programming question, and in general all of these kinds of questions boil down to subjective decisions on your part given that there are pros and cons of any given approach.

But *in general*, your idea isn't necessarily a good one given that all you're really doing is making those objects globals. Global accessibility might mean you don't have to pass them around as much (possibly making your life easier), but it also means you might be inclined to make "sloppy" architecture decisions (which will make your life harder when/if you get around to refactoring). You should be striving to encapsulate as much as possible in one section of the code base to reduce dependencies and so on.

Just look up any of hundreds of articles on whether or not you should make things global and you'll find a lot more on the subject matter.
> 1 votes

# Answer
Problems like these are usually solved with something called a "context" variable - an "umbrella" structure that keeps all session-local state (variables that could also be global) inside it. Whenever you need something from it, you pass the context or "make it current" (set a global variable that is a pointer to a context). That way, you have at most one global variable instead of many.

However, since this method is widely accepted and used despite globals being hated all around the world, this is somewhat close to hypocrisy. So until there's a real need for such workarounds (platform limits or the requirement to have multiple sessions/states), using globals is just fine. Using too many of them can make code hard to understand, that's about the only problem you could bump into so far.
> 1 votes

# Answer
So I can confirm your suspicion. The code sample you posted *definitely bad*. The loose `ID3D11DeviceContext` should be a member of a class somewhere.

You don't need a **singleton**. We already agreed singletons are bad.

But **yes**, you should write a single class to represent your main game object (or main window object, whatever you like to call it), and inside that class have a single `ID3D11DeviceContext`.

You don't need to declare your `ID3D11DeviceContext` static. No idiot will try to create 2 instances of your `DxObj`.
> 1 votes

---
Tags: architecture
---


# Question
Title: Iterating 1D array and getting 2D tile position
I know I'm missing something very obvious here, but I have a 1D array that contains integers.I have a map that is 30 x 30 and the center coordinate is 0,0 (This is actually 3D, but I'm essentially removing the Y-axis). Because of this offset, my loop is from -15 to 14, rather than 0 to 29. Is this incorrect?

I'd like to iterate through the array and if the integer is "1", then I'd like to call `AddSphere(x,y,z)` with the correct `x` and `z` values. How would I get the correct values for x and z? The file is designed to be read left to right rather than left to right, right to left, left to right etc... (although if that's a better approach, I can just change the data to match that style).

# Answer
One possible way is to split the integer into two values between `0` and `29` (this is done using integer division and modulus) then offset them by `-15`:

```
for (int n = 0; n < 30 * 30; ++n)
{
    if (Array[n] == 1)
    {
        int x = n % 30 - 15;
        int y = 0;
        int z = n / 30 - 15;

        AddSphere(x, y, z);
    }
}

```

Note that `-15..14` is asymmetrical. If you want `(0,0)` to be at the exact centre of your map, you need an odd value instead of `30`.
> 1 votes

---
Tags: c#, 2d, algorithm, tiles
---


# Question
Title: How to calculate the position of an attached model after rotation?
I'm programming a basic game on XNA. I started to place an object (eg weapon) attached to the right arm of my player. When I move my character forward behind left or right all right. But when I rotates my equipment is not positioned correctly. I am fully understands it is necessary to recalculate the new position based on the rotation done but I do not see how. Here is my code and pictures

```
        //Function that will draw the current item selection in the player's hand
private void draw_itemActionInUse(Model modelInUse)
            {

                int handIndex = skinningData.BoneIndices["Hand_Right"];

                Matrix[] worldTransforms = animationPlayer.GetWorldTransforms();

                Matrix rotationMatrixCalcul = Matrix.CreateRotationY(player.Rotation.Y);
//Here I calculate the new position of the item, but it does not work
                Vector3 newPosition= Vector3.Transform(new Vector3(player.Position.X, player.Position.Y + 4, player.Position.Z ), rotationMatrixCalcul);
                foreach (ModelMesh mesh in modelInUse.Meshes)
                {
                    foreach (BasicEffect effect in mesh.Effects)
                    {

                        effect.World =
    worldTransforms[handIndex]
    *
    Matrix.CreateScale(2)
    *
    Matrix.CreateRotationY(player.Rotation.Y)
    *
    Matrix.CreateTranslation(newPosition);

                        effect.View = View_;
                        effect.Projection = Projection_;

                        effect.EnableDefaultLighting();
                    }

                    mesh.Draw();
                }

            }

```

**Figure A**: position: x:0;y:0;z:0 angle : 90 **Figure B**: position: x:2;y:4;z:0 angle : 90 **Figure A**: position: x:1;y:0;z:1 angle : 35 **Figure B**: position: *How calcul this position ?* angle : 35

# Answer
You'll need to position the weapon in the player's local space, and apply the same transformation to it that you apply to the player model.

More specifically, figure out the vector from the player's origin to the weapon's origin, before applying any rotation. In your case it seems this may be (2, 0, -2) or some such. Then rotate that vector by the player's rotation, and then add to it the player's translation.
> 4 votes

---
Tags: xna, models, blender-game-engine
---


# Question
Title: Does Monogame on Windows Desktop use OpenGL or DirectX by default?
if i use monogame 3.0 beta on windows desktop, does it use the directx renderer (sharpdx) or the opengl renderer by default?

if it uses directx is there away to make sharpdx call directly? thanks!

# Answer
in the meantime i found out that it does use OpenGL for windows desktop and DirectX for windows 8 metro.
> 3 votes

# Answer
MonoGame currently only supports OpenGL. It has basic support for OpenGL ES for Android/iOS, and its DirectX support is still in development and incomplete. Hence, to answer both your questions (please don't post more than one question at a time):

It uses OpenGL by default.

There is no way to make it use DirectX at runtime, other than to recompile MonoGame in DirectX mode (which is not likely going to be usable for real projects yet).

Relevant code for MonoGame's graphics layers is at https://github.com/mono/MonoGame/tree/develop3d/MonoGame.Framework/Graphics

You will notice that DirectX support is wrapped behind conditional compilation in the code, that OpenGL assemblies are always pulled in even when compiled in DirectX mode, and that there is not even a project configuration in the .csproj that sets the necessary directives.
> 2 votes

---
Tags: opengl, directx, monogame, sharpdx
---


# Question
Title: Performance tracking/monitoring in games
Let's say I have an online game with a downloadable client / browser plugin. I want to track performance of my software and automatically send summary to the server. Let it be fps, latency, load time, physics step calc. time, whatever... I also want tools to perform data analysis: per session stats, per hardware stats, avgs, totals, diagrams, etc. So that I could see what are the real world hotspots / bottlenecks.

Is there any common out-of-the-box / SaS solution?

# Answer
A common approach to this is to simply use any of the numerous Web statistic tracking services available, or to roll your own.

The idea is simple enough. Web tracking software simply records every "hit" to a particular URL, along with some supporting information. You can make up URLs for specific game resources or events to use for tracking things in your game. You can either use paths in the URL or query parameters to encode extra information, plus the built-in stats these services offer (like "time on site" to see how long a user is on a particular level by pinging the level URL every so often, or time of day to see when people are on your game, or what regions your game is popular in, etc.).

For example, you might player metrics by using URLs like:

```
http://stats.example.com/games/mygame/levels/level3/start?user=playerid
http://stats.example.com/games/mygame/levels/level3/died?user=playerid
http://stats.example.com/games/mygame/levels/level3/finished?user=playerid

```

You can track performance characters by posting to URLs like:

```
http://stats.example.com/games/mygame/levels/level3/zones/zone13/performance?avgfps=47.5&mem=145MB&tex=247MB&minfps=17.2

```

Building your own service for this is fairly straight forward. You need at minimum just a simple HTTP server somewhere that logs requests, and then one of the myriad of log processing scripts out there that are so popular with Web administrators.

Generating these calls is likewise quite simple using any HTTP library. If you are building in a browser, you can just use the built-in XmlHttpRequest support to generate the hits.

You can alternatively use an off-the-shelf solution, such as Google Analytics, Clicky, and so on. They are not going to make it easy to do custom processing of performance characteristics. For that, you're best off with a custom solution that collects those stats with a script and compiles them into useful reports. Also note that some solutions, like Google Analytics, are heavily geared towards Web users only; notable, they only deliver a .js file (which is hosted on their servers and you are not supposed to copy), rather than an actual REST API, because their protocol can and does change without warning. I've seen a team go through some non-trivial effort to embed a JS interpreter just to run the Google Analytics .js files in their standalone game... don't do that, it's wasted effort for a service that isn't even ideal for the target use cases.

I've been told there is an existing off-the-shelf solution for games, but I cannot for the life of me remember its name, and Google has been no help. I may have been told wrong.

Building your own really isn't hard, though. Any half-competent contracted Web programmer (which excludes 97.4% of Web programmers, as a warning) should be able to whip up a complete working solution within a week. You'll obviously want to have a clearer definition of the exact kinds of statistics and events you're looking for.
> 1 votes

---
Tags: performance, optimization
---


title: Find connected hex of same color

text:
# Question
Title: Find connected hex of same color
I'm using Lua. I have a hex map. It is randomly generated into an table.

hexmap\[y\]\[x\].color = "red"

I wish to find each "group" of hex's. i.e. all hex's of the same color that connect to each other will belong to one group.

As an example, in the following image:

The result should be:

1 blue group (all hex's connect) 3 green groups 1 black group

Any suggestions?

Thank you.

# Answer
Start from the top left and use a BFS flood fill to get all of the same color cells of the starting cell (while marking the cells as visited). Once the BFS finishes keep traversing your hexmap looking for unvisited cells. If you find an unvisited cell start another BFS flood fill (same idea as before). To determine if you have finished either keep a count of the visited cells and see if it matches your N\*M hexmap array, or just keep traversing your hexmap looking for unvisited cells.

Example (using your picture above):

1. i = 0, j = 0 (top left of hexmap) \[0,0\], color is blue.
2. BFS flood fill the starting point only looking for blue cells, this will mark all blue cells as visited.
3. look for the next unvisited cell, which will be the green cell at \[0,3\].
4. repeat step 2, but instead of blue cells, you are looking for green cells.
5. repeat step 3 and 4 until you are done.
> 4 votes

---
Tags: tilemap, lua, hexagonal-grid
---


title: char* to code block

text:
# Question
Title: char* to code block
I am 99% certain this will require code compiling at runtime, but it is necessary.

I am thinking of making a very simple app that allows advanced users to write in a script-like language in order to customize certain things (basically a build-your-own-app app). This includes OpenGL shaders, custom launch animations, and so on. The thing is that I am purposefully making the language very robust, and, while it is working perfectly, it is very slow. I was thinking about simply translating the script into C code (prototype is already working smoothly) and turning that C code into a code block that can be saved and loaded whenever I need it.

I can do this with the Cocoa/Cocoa-Touch 'NSDictionary' but the overhead in Objective-C really bothers me. I am afraid that the complex code created with Objective-C will be too costly to run like a norma app. You may say this is not going to cause problems, but the constant re-interpreting and numerous function calls that I am already doing will force me to save every byte I have at my disposal. That left me with one option, as far as I can see. I need to compile the code and integrate it into the executable. My question is this: can I compile code stored in a char array and store that in a code block immediately without a relaunch? If so, how?

Note: This app is being made to run on Mac OS 10.6 and higher. It is currently compatible with all versions of Linux and Windows 7 as well, and I would like to keep it that way for as long as possible so it can be released on those operating systems. I do not want to force potential users to get a different operating system if they want to use this app. I can and will sort out all of the other complications, but this issue is confusing me too much.

# Answer
You are looking for a scripting language that can be embedded into your application. That is, a language which is designed to be interpreted at runtime (in many cases quite efficiently) and can be used to allow user extension of your native code written in C/C++/ObjC.

There are *many* to choose from. Lua and Python are two quite popular ones, particularly in games. There are also embeddable libraries for JavaScript, not to mention Ruby, TCL, LISP, C#, and countless others.

If for some reason you are dead set on using a language like C, C++, or Objective-C, your options are much more limited. First, just realize that it's a bad idea anyhow. Only "real programmers" are comfortable with languages like C/C++/ObjC. Really, only "real programmers" are generally comfortable with *any* language, even "made for beginner" scripting languages (programming is programming, and programming requires a level of knowledge, expertise, and so on to do even slightly competently), but it's more so for systems level languages. If you want to interpret a subset of C or C++ at runtime, there is CINT/Clint, which are interpreters built off of Clang.

If you want an offline compilation process, you can of course just save your code snippet out to a file and invoke an actual compiler. On OS X, you can invoke GCC or Clang as a sub-process to compile code into a shared library, which you can then dynamically load using dlopen()/dlsym()/dlclose(). Again, though, I do *not* recommend this approach at all, unless you have very particular needs.

Embedding Lua, Python, or so on will let you keep compatibility with OS X and Windows, not to mention Linux, iOS, Android, and consoles. Lua is used by a number of commercial games as their scripting/logic engine, and Python has seen use in commercial games too. C# is popularized thanks to XNA, and is used as the extension/scripting language of Unity 3D.

You can also build your own from scratch, but clearly the dictionary approach you mentioned is going to be non-optimal for all but the simplest approaches. How to write your own scripting language is a very, very involved topic; I could answer dozens of specific questions on that topic and still barely scratch the surface.

My recommendation there, if you are so inclined as to learn how to design a language interpret, is to start researching the existing Open Source scripting languages (which is practically all of them). There is a lot design documentation and developer discussion history (via mailing list archives and the like) for almost every major scripting language in use today, not to mention all of the code is available online. Lua is by far the smallest and simplest of the popular extension libraries, although I would not consider its code to be the best for learning from.

I do not, sadly, know of any resources on getting started with writing a custom script language. There are some classic texts on general compiler design around, which you can easily find via Google.
> 8 votes

---
Tags: c, cross-platform
---


# Question
Title: Unity - Code is fine in the editor, has error on android
Right. Im running into some weird issue with android unity. I have this bit of code

```
function OnTriggerStay (other : Collider)
{

        if(die.GetComponent(DieScript).sideUp ==6 ||die.GetComponent(DieScript).sideUp ==2 || die.GetComponent(DieScript).sideUp ==4)
    {

       parSys.startSpeed = -5;
        if (other.attachedRigidbody)
        {
        var direction = -(other.attachedRigidbody.transform.position - transform.position*1.5);
            other.attachedRigidbody.AddForce(direction);
        }

        }

```

Now, this runs fine in the unity editor. More then fine, It runs perfectly. However on android the whole OnTriggerStay method fails, and I get this error from logcat

```
I/Unity   (29199): NullReferenceException: Object reference not set to an instance of an object

I/Unity   (29199):   at ZoneScriptDie.OnTriggerStay (UnityEngine.Collider other) [0x00000] in <filename unknown>:0

I/Unity   (29199):

I/Unity   (29199): (Filename:  Line: -1)

I/Unity   (29199):

I/Unity   (29199): NullReferenceException: Object reference not set to an instance of an object

I/Unity   (29199):   at ZoneScriptDie.OnTriggerStay (UnityEngine.Collider other) [0x00000] in <filename unknown>:0

I/Unity   (29199):

```

Why is it failing in android? The whole object freezes up, the particles just hang in place like a frozen snowglobe.

# Answer
I think I fixed it, I changed the code from

`die = GameObject.find("die"); //Worked fine in the editor` to `die = gameObject.transform.parent.gameObject;`

It now runs fine on the phone. So Yes chaosTechnician was right, It wasnt being set. That being said does anyone know why it is that That particular gameObject.find didnt work?
> 0 votes

---
Tags: android, unity, javascript
---


# Question
Title: Real-Time-Strategy control structures/achitecture
I am looking at building a real time strategy game (of at least the framework for one) in Unity, and was wondering what control structures and/or architecture I should focus on using.

current expectations: I think that I will need a global controller/registry architecture, with sub controllers for the different players while considering the AI controller(s) to be player(s), and then registries for the different groups.

how does my current design logic hold.

additionally are there any specific resources that I should look through to achieve this goal?

# Answer
Despitethe fact that your Question is verry unprecice i will give it a shot.

First, you should get familiar with the concept of Entity Component Systems: Using component based entity system practically

Then you should learn what exactly the command pattern is, because it is by far the most usefull in rts games and multiplayer games: http://en.wikipedia.org/wiki/Command\_pattern

This should give you a better view on what the next questions are you need to ask.
> 1 votes

---
Tags: architecture, rts
---


# Question
Title: OpenGL first person camera orientation issues
I have a "camera" in my opengl program that I recently finished. However, I've noticed that whenever I rotate and then move again, the x, y, and z angles change. For example, when I press the "w" key, I move forward along the "z" axis. If I then rotate the camera 90 degrees, when I push the "W" key, I will actually be moving right, seemingly along the "x" axis. It makes sense why this happens, I'm just wondering why its happening. Here's the rotation function:

```
private void camera() {
    glRotatef(xrot, 1.0f, 0.0f, 0.0f);
    glRotatef(yrot, 0.0f, 1.0f, 0.0f);
}

```

The keyboard function:

```
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        xpos -= 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        xpos += 0.035 * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
        zpos += 0.03f * delta;
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
        zpos -= 0.035 * delta;
    }
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {
        xrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
        xrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        yrot += 0.035;
        if (xrot > 360) {
            xrot -= 360;
        }
    }

    if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
        yrot -= 0.035;
        if (xrot > 360) {
            xrot += 360;
        }

    }

```

And my translate function:

```
        glTranslated(xpos, ypos, zpos - 30);

```

any ideas on how to solve this? I would be very grateful

# Answer
> 0 votes
What you're not doing is rotating your x- and y-positions based on which direction your player is pointed. (note that this depends solely on your z-angle, and not on the x and y axes)

You will need to perform your manipulations on a pair of variables that get rotated *after* all the keys are checked, which also means you'll need to calculate the rotation with good-old sines and cosines.
(note that you'll also need to handle things carefully if you have *any* slopes whatsoever. Having the player move smoothly up and down them is extremely important for a good user-experience)

The code is relatively simple:

```
// Process the motion commands as normal

// Now rotate the raw values:
final_dx = raw_dx*cos(rot_z) + raw_dy*sin(rot_z);
final_dy = raw_dx*sin(rot_z) + raw_dy*cos(rot_z);

```

Note that you may have to change a few signs around (ie, multiply by -1) to make sure that the rotations line things up properly.

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


title: How to draw a trapezoid in OpenGL?

text:
# Question
Title: How to draw a trapezoid in OpenGL?
The question seems easy, but you simply change vertex positions to match the corners of a trapezoid but it simply fails. I've tried scaling top and bottom edges like this :

but when I apply my texture it doesn't behave as I expected rendering this texture

into this image

**Edit:**

so far I've managed to produce a good looking image by changing w component of vertex coordinates instead of the x component, but I'm wondering if there is any better way to solve it?

**Edit2:**

here are my vertex and texture coordinates when I initialize the class.

```
float w = mTexture->getPixelsWide();
float h = mTexture->getPixelsHigh();
mVertices[ 0+0] =-w; mVertices[ 0+1] = 0; mVertices[ 0+2] = 0; mVertices[ 0+3] = 1;
mVertices[ 4+0] = w; mVertices[ 4+1] = 0; mVertices[ 4+2] = 0; mVertices[ 4+3] = 1;
mVertices[ 8+0] =-w; mVertices[ 8+1] = h; mVertices[ 8+2] = 0; mVertices[ 8+3] = 1;
mVertices[12+0] = w; mVertices[12+1] = h; mVertices[12+2] = 0; mVertices[12+3] = 1;
mCoordinates[0] = 0; mCoordinates[1] = 0;
mCoordinates[2] = 1; mCoordinates[3] = 0;
mCoordinates[4] = 0; mCoordinates[5] = 1;
mCoordinates[6] = 1; mCoordinates[7] = 1;

```

and later to scale it I'm currently using:

```
float ts = (mSpreadTime - mDropTime) / ((mSpreadTime - mTime) + mTopSpreadRatio * (mTime - mDropTime));
float bs = (mSpreadTime - mDropTime) / ((mSpreadTime - mTime) + mBottomSpreadRatio * (mTime - mDropTime));
mVertices[3] = ts;
mVertices[7] = ts;
mVertices[11] = bs;
mVertices[15] = bs;
mVertices[1] = 0 * ts;
mVertices[5] = 0 * ts;
mVertices[9] = h * bs;
mVertices[13] = h * bs;

```

note: that method above solved my issue, I'm looking for a way to fix it without messing with w component.

# Answer
> 4 votes
I think this is a common issue on trapezoids. **Here** there is a good explanation of it, and the solution. Basically, OpenGL will divide your trapezoid in triangles, as you showed in your first figure, and these two triangles are not equal, thats why the texture mapping looks *distorted*. Luckily OpenGL is not only 2D but also 3D, hence you can workout a solution using the `w` coordinate.

```
           Using only 2D                                  Using 3D coordinates

```

---
Tags: 2d, textures
---


title: Double buffering on HTML5 Canvas game?

text:
# Question
Title: Double buffering on HTML5 Canvas game?
My simple canvas game seems to work fine on Chrome and FF on Mac/Linux. I haven't had chance to test it on smart phones or Windows environments yet. It doesn't use double buffering but I have seen some JS Canvas examples using it.

When is the use of the double buffering recommended? Does it make difference only for specific browsers? Is there a significant performance hit?

Thanks!

# Answer
> 14 votes
Double buffering a canvas based game will certainly be a performance hit. You'd be drawing an extra amount of pixels equal to your canvas size every frame. In canvas based games drawing to a canvas is the biggest bottleneck in most cases and you want to limit that as much as possible, especially on mobile devices.

Chrome has GPU acceleration (as of the latest versions) as well as a wicked fast JavaScript engine (V8) that you won't see matched in a mobile environment. Even in Chrome you'll see a slowdown by implementing double buffering.

Long story short, the benefit of double buffering (dealing with "tearing") isn't worth the performance hit you'll take most likely.

# Answer
> 5 votes
There is no need to double buffer html5 games. The browser already handles this for you by only updating the canvas object after your script has run. http://www.mail-archive.com/whatwg@lists.whatwg.org/msg19969.html

# Answer
> 1 votes
I noticed that using doing double buffering like this :

1. draw everything a invisible canvas
2. copy invisible canvas to the real canvas

actually slows down the rendering (lower fps), instead of speeding it

---
Tags: javascript, html5, html-canvas, double-buffering
---


# Question
Title: Collision detection between player and tiles
I am trying to implement basic (for now) collision detection into my platformer. I have tiles that are each 16 x 16 in size. The character is 32 x 32 pixels in size and has its own bounding box. Now, in my Tile class, I have a bool, isSolid. Each of these tiles in my array also have a rect for their respective bounding boxes.

I am checking to see if there's an intersection between the player and tiles by doing:

```
if (player.GetBoundingBox().Intersects(map.tiles[(int)player.position.Y / 16,
(int)player.position.X / 16].bounds) && map.tiles[(int)player.position.Y / 16,
(int)player.position.X / 16].isSolid)
{
...
}

```

Now, my problem is that this is extremely inaccurate as I'm rounding off the position. I'm tired as heck right now and for the life of me I can't figure out how to properly do this. What is the best way to approach this issue?

# Answer
> 2 votes
Your problem begins with your massively long line of code. You lose nothing by breaking out each individual segment and putting it into its own variable... the compiler will optimise these out in the end, anyway. And you will understand the code you are writing, much more clearly. There are plenty of problems challenging enough that you need not give yourself a handicap!

Second, you need to decide how you are going to approach this. Will you do bounding box checks, or will you do individual tile checks (possibly alone, or possibly *as well*)? At the moment I get the feeling you're confounding the two. Tile-by-tile checks are more expensive if used alone. So better to do bounding rectangle checks first and foremost. Your platforms should have their own bounding rectangles.

So let's look at your code, modified.

```
foreach (BoundingBox platform : platforms) //platforms is a List you've built beforehand.
{
            if (player.GetBoundingBox().Intersects(platform)
            {
                if (tile.isSolid)
                {
                    pushPlayerBack();
                }
            }
 }

```

The platforms list is a set of `BoundingBox`es which you construct *before* building your tilemap. Once you have the platform `BoundingBox`es, you can derive each tile's `isSolid` value by running through the list of platform `BoundingBox`es and updating tile values accordingly. This way, the tilemap matches the list of platform `BoundingBox`es, and you can do a nice cheap and easy `Intersects` check to see if your player overlaps any solid tiles.

Now that you know whether the `BoundingBox`es overlap, you can either accept that result as the final answer or do an additional finer scale, tile-by-tile check within the overlapping area.

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


# Question
Title: Boundaries in game development: How do “professionals” do it?
How do professionals do boundaries in a 2D game? The way I do is say I don't want the sprite to move into a certain area:

```
//Example
if ((playerPosX >= 825) && (playerPosX  <= 910)&& (playerPosY >= 170) && (playerPosY <= 255)) {
    //do nothing
}else{
    //move
}

```

But some games out there have a lot of boundaries so I'm wondering, is there an easier way. I don't think there is any way someone would use the above method throughout a whole game, just to block of movement.

**EDIT:** My question is mainly regarding a game where you can walk around, similar to Pokemon or final fantasy

# Answer
> 12 votes
Nothing wrong with that, at all. We do whatever is the simplest, that works.

Having said that, what you describe in your code is a means to bound objects into a rectangular playing field, eg. Robotron or Gremlins, or to keep a bouncing ball inside the screen. On the other hand, if you want to collide with many separate boundaries, or for objects to collide with other objects, you need to look into collision detection.

There are two broad approaches to detecting collisions:

1. Cell/tile-based collision detection
2. Geometric collision detection

Some games, like PacMan, use cell-based collision detection. The entire map is represented as cells which are either filled or open(boolean value). The characters (ghosts & PacMan) can only move between cells that are open.

However, nearly all collision detection you see in modern games is geometric. The geometric collision detection category breaks down into:

* Axis-aligned rectangular collision detection, one application of which you've described above; however your whole world may be made out of axis-aligned rectangles which either keep things in, or keep things out, or both.
* Circular collision detection, where a collision occurs when the distance between Circle1 & Circle2 is less than their combined radii (extends to spherical collision detection in 3D).
* Polygonal (line-based) collision detection (e.g. Box2D); this also works for non-axis-aligned rectangles / boxes. Extends (with a considerable amount of extra mathematical effort) to polyhedral (line- & plane-based) collision detection in 3D (eg. ODE). It is costly because it takes processing time proportional to the number of lines in each of the two colliding polygons.
* 3D parametric surface collision detection, which is a whole other ball game and isn't really used in games but rather in eg. CAD software and raytracers. There is probably a parallel for this in 2D (using splines and the like) but I've never seen it's like in use.

It is also worth noting that there is a clear hierarchy of cost in the list above. Axis-aligned rectangular is cheaper than circular collsion detection is cheaper than polygonal collision detection is cheaper than more accurate parametric line or surface methods. For this reason, collision detection algorithms often consist of a "broadphase" and a "narrow phase", the broadphase being where a cheaper algorithm is used to check for "early fail". For instance, in 3D it is far easier to first determine what the maximum spherical bounds of two objects are, and see if these overlap, and then only if they do overlap, to check the individual planes, edges and vertices to see if a *real* overlap occurs.

# Answer
> 1 votes
What I have done before is generate a specific tile around the edge of the map and check constantly if the player is on one of those tiles. I then tell it to pretty much not let it to go past those tiles. I usually assign an ID to each type of tile to help checking if the player is on the tile. I also generate black or "void" tiles around the map and I don't let the player move on them.

# Answer
> 0 votes
Yeah for a game like pokemon I'm sure a tile based approach would be best. Every peice of the game is represented as a square sprite with large items like buildings usualy a few seperate tiles. I've made a few with a separate layer for movement tiles that don't get drawn at run time, but show up in the editor. Then when moving it checks to see if that is a tile you can move to, otherwise you just bump into a wall. Simmalerly you could have tiles where you could swim, or use other special abilitys. There are many great books on tile based games, and probably a lot of good resources online too

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


title: Collision Problems in Pacman Clone

text:
# Question
Title: Collision Problems in Pacman Clone
I am working on a Pacman clone. I am using Java for the project. I have been having problems with collisions, and allowing the player to pass through objects. Note that the tile size (and player) is 16x16px.

Here is the collision code in the player class.

```
private void processInput(Input input, int delta)  {
    if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_RIGHT) ||
        input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_DOWN))  {

        if (input.isKeyDown(Input.KEY_LEFT))  {
            velocity =  new Vector2(-1 * speed * delta, 0);

            rotation = 180f;
        }
        else if (input.isKeyDown(Input.KEY_RIGHT))  {
            velocity = new Vector2(1 * speed * delta, 0);

            rotation = 0f;
        }
        else if (input.isKeyDown(Input.KEY_UP))  {
            velocity = new Vector2(0, -1 * speed * delta);

            rotation = 270f;
        }
        else if (input.isKeyDown(Input.KEY_DOWN))  {
            velocity = new Vector2(0, 1 * speed * delta);

            rotation = 90f;
        }
    }

    processCollision();

    this.position.x += velocity.x;
    this.position.y += velocity.y;
}

private void processCollision()  {
    this.positionTile = new Vector2(position.x, position.y);

    this.positionTile.x -= board.getX();
    this.positionTile.y -= board.getY();

    this.positionTile.x /= 16;
    this.positionTile.y /= 16;

    Vector2 normalisedVelocity = new Vector2(velocity.x, velocity.y);
    normalisedVelocity = velocity.getNormal();

    if (collision(normalisedVelocity))  {
        velocity = Vector2.ZERO;
    }
}

private boolean collision(Vector2 direction)  {
    Vector2 index = new Vector2(positionTile.x + direction.x, positionTile.y + direction.y);

    if (!board.getTiles()[(int)index.y][(int)index.x].collidable)  {
        return true;
    }

    return false;
}

```

And here is the board class.

```
public class Board {
    TileSheet sheet;
    TileRenderer renderer;

    Tile[][] tiles;

    Vector2 initPlayerPosition;

    float x = 0;
    float y = 0;

    public float getX()  {
        return x;
    }

    public float getY()  {
        return y;
    }

    public TileSheet getSheet()  {
        return sheet;
    }

    public Tile[][] getTiles()  {
        return tiles;
    }

    public int getWidth()  {
        return tiles[0].length;
    }

    public int getHeight()  {
        return tiles.length;
    }

    public Vector2 getInitPosition()  {
        return initPlayerPosition;
    }

    public Board()  {
    }

    public void loadLevel(String name)  {

        // Temp, the following five lines (including the whitespace) look ugly
        // TODO: Make the map placing dynamic
        this.x = 800 / 2 - (tiles.length * sheet.getTileWidth()) / 2;
        this.y = 20;

        initPlayerPosition.x += this.x;
        initPlayerPosition.y += this.y;
    }

    public void init(GameContainer gameContainer, StateBasedGame game) throws SlickException  {
        Image sheetImg = new Image("data/textures/tileset.png");
        sheet = new TileSheet(sheetImg, 16, 16, 1.0f);

        renderer = new TileRenderer(this);
    }

    public void render(GameContainer gameContainer, StateBasedGame game, Graphics graphics)  {
        renderer.render(tiles, gameContainer, game, graphics);
    }

```

...

```
public class Tile  {
    int sheetX;
    int sheetY;

    bool collidable;

    public Tile(int sheetX, int sheetY)  {
        this.sheetX = sheetX;
        this.sheetY = sheetY;

        // If there is nothing (0,0) allow the player to collide
        if (sheetX == 0 &&
            sheetY == 0)  {
           collidable = true;
        }  else  {
           collidable = false;
        }
    }
}

```

Any ideas?

# Answer
Ok so i'm currently making a 2D top down view game and the way you created your board i think is similar to mine or maybe not lol.. however! this is how i implement mine.

This is my getTile method.

```
public Tile[][] getTile(int x, int y) {
    if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight()) {
    return new VoidTile();
} else {
    return tiles[x][y];
}
}

```

In my Tile.java class i have a isSolid() method which returns whether the tile is solid or not. However, my tiles extend my Tile.java so they inherit this method and I override it in their constructor. I am not sure if you have other tiles? It is good practice to do it this way though :)

In your case for a pacman clone you could have VoidTile.java, WallTile.java and you could also use the Tile.java class for the fruit that pacman picks up (i.e GrapeTile.java).

In my player.java class i have a checkBlockedDirection(int x, int y) method and it looks like this.

```
    public void checkBlockedDirection(int x, int y) {
    boolean u = map.getTile(x, y - 1).isSolid();
    boolean d = map.getTile(x, y + 1).isSolid();
    boolean l = map.getTile(x - 1, y).isSolid();
    boolean r = map.getTile(x + 1, y).isSolid();

    if (u) {
        uBlocked = true;
        System.out.println("up tile blocked");
    } else {
        uBlocked = false;
    }
    if (d) {
        dBlocked = true;
        System.out.println("down tile blocked");
    } else {
        dBlocked = false;
    }
    if (l) {
        lBlocked = true;
        System.out.println("left tile blocked");
    } else {
        lBlocked = false;
    }
    if (r) {
        rBlocked = true;
        System.out.println("right tile blocked");
    } else {
        rBlocked = false;
    }
}

```

Then in my player update method i have this

```
public void tick() {
    float dx = 0;
    float dy = 0;

    if (input.up.isPressed()) {
        direction = 0;
    } else if (input.down.isPressed()) {
        direction = 2;
    } else if (input.left.isPressed()) {
        direction = 3;
    } else if (input.right.isPressed()) {
        direction = 1;
    } else {
        direction = 4; // standing
    }

    checkBlockedDirection((int)x, (int)y);

    if (input.up.isPressed() && y > 0 && !uBlocked) {
            dy += -speed;
    } else if (input.down.isPressed() && y < map.getHeight() - 1 && !dBlocked) {
            dy += speed;
    } else if (input.left.isPressed() && x > 0 && !lBlocked) {
            dx += -speed;
    } else if (input.right.isPressed() && x < map.getWidth() - 1 && !rBlocked) {
            dx += speed;
    }
    x += dx;
    y += dy;

}

```

Basically it just checks which direction the player is facing, Then checks if the blocked up, left, right and down are either blocked or not.

If they aren't blocked then it moves the player across one block.

Not sure if this helps or not but it's just my take on this kind of grid collision detection :)

Enjoy
> 1 votes

# Answer
If you're unsure about whether or not you lookup the array correctly, you can add some print statements (System.out.println("...");) that spits out the index and result of the array lookup.

I suggest you refactor your code to deal with game logic separate from drawing details.

You could represent your board as a 2d integer array with integer value referencing tile type. Then store logical position as integers x and y.

(Look up "Normal form" as it relates to databases to get a sense of how to structure your data efficiently)

Generally you want to use as small amount of data as possible to represent a given concept. Not only for performance reasons, but also to keep code simple and elegant.

For instance, you store sheetX and sheetY for every single tile in the map. Sheet x and y will never be different for two tiles of the same type, so it makes no sense to store it for each tile. Rather have a 1 dimensional array of tile types, then build your game board using references to tile types.

Sheet x and y don't really have to be stored at all if your tilesheet have consistently sized tiles. You can just index the tile and calculate the x and y.

```
Rectangle getTileGraphicBounds(int index,
        int tileSheetWidth,
        int tileSheetHeight,
        int tileWidth,
        int tileHeight) {

    // TODO: insert tests here to make sure sheet width and hight are multiples of tile width and height

    int horizontalTileCount = tileSheetWidth / tileWidth;

    // Calculate x and y

    // modulus yields the remainder of index divided by horizontalTileCount, which is the x value
    int tileX = index % horizontalTileCount;

    // index divided by horizontalTileCount will yield the integer y value as the remainder gets discarded
    int tileY = index / horizontalTileCount;

    int sheetX = tileX * tileWidth;
    int sheetY = tileY * tileHeight;

    return new Rectangle(sheetX, sheetY, tileWidth, tileHeight);
}

```

To get nice smooth animations in your graphical presentation of the game you'll need to store position in terms of pixels, not board position. For scalable graphics you need to store subpixel position using floats or doubles.

In the drawing part of your program you could have the position of the character graphic represented as float x and y.

For every iteration of the main loop check if drawPosition is close to logicalPosition (with a suitable threshold, 0.001f for instance). If it is you check for input and perform movement, if it's not, you animate the drawPosition towards the logicalPosition. While animating it makes sense not to check input (no movement can be made until the animation stops).

This will keep the game logic simpler and makes it easier to avoid problems with collition and such.

Example game logic (partial, untested):

```
// in main class:
Vector2i logicPosition;
Board board;

...

class Vector2i() {
    int x;
    int y;

    Vector2i(int x, int y) {
        this.x = x;
        this.y = y;
    }

    Vector2i() { this(0, 0); }

    Vector2i add(Vector2i other) {
        return new Vector2i(this.x + other.x, this.y + other.y);
    }
}

...

class Board() {
    // 2d array representing level, values referencing tile type.
    int[][] data;

    // A list of all walkable tile types.
    ArrayList<Integer> walkable = new ArrayList<Integer>();

    bool isWalkable(Vector2i position) {
        // data[][] is indexed y, x to make level prototyping easier.
        return walkable.contains(data[position.y][position.x]);
    }
}

...

// Calls move() to perform collition/motion.
void processInput(Input input) {
    Vector2i motion = new Vector2i();

    if (input.isKeyDown(Input.KEY_UP)) motion.y = -1;
    else if (input.isKeyDown(Input.KEY_DOWN)) motion.y = 1;
    else if (input.isKeyDown(Input.KEY_LEFT)) motion.x = -1;
    else if (input.isKeyDown(Input.KEY_RIGHT)) motion.x = 1;

    move(motion);
}

...

// Collition test happens here.
void move(Vector2i motion) {
    Vector2i futurePosition = this.logicPosition.add(motion);

    if (board.isWalkable(futurePosition)) {
        this.logicPosition = futurePosition;
    }
}

```
> 1 votes

---
Tags: java, collision-detection, lwjgl, slick
---