# Question
Title: Flash Actionscript 3.0 Game Projectile Creation
I have been creating a side-scrolling Actionscript 3.0 game. In this game I want the Player to be able to shoot blow darts as weapons. I had some trouble getting the darts to be created in the right place (in front of the player), but eventually got it working with some help from this page (please look at it for background information on this problem):

https://stackoverflow.com/questions/8031553/flash-actionscript-3-0-game-projectile-creation

I got the darts to be created in the right place (near the player) and a 'movePlayerDarts()' function moves them. But I actually have a new problem. When the player moves after firing a dart, the dart tries to follow him! If the player jumps, the dart rises up. If the player moves to the left, the dart moves slightly to the left.

Obviously, there is some code somewhere which is telling the darts to follow the player. I do not see how, unless the 'playerDartContainer' has something to do with that. But the container is always at position (0,0) and it does not move.

Also, as a test I traced a dart's 'y' coordinate within the constantly-running 'movePlayerDarts()' function. As you can see, that function constantly moves the dart down the y axis by increasing its y-coordinate value. But when I jump, the 'y' coordinate being traced is never reduced, even though the dart clearly looks like it's rising!

If anybody has any suggestions, I'd appreciate them!

Here is the code I use to create the darts:

```
    // This function creates a dart
public function createDart():void {

    if (playerDartContainer.numChildren <= 4) {
        // Play dart shooting sound
        sndDartShootIns.play();

        // Create a new 'PlayerDart' object
        playerDart = new PlayerDart();

        // Set the new dart's initial position and direction depending on the player's direction
        // Player's facing right
        if (player.scaleX == 1) {
            // Create dart in front of player's dart gun
            playerDart.x = player.x + 12;
            playerDart.y = player.y - 85;
            // Dart faces right, too
            playerDart.scaleX = 1;
        }
        // Player's facing left
        else if (player.scaleX == -1) {
            // Create dart in front of player's dart gun
            playerDart.x = player.x - 12;
            playerDart.y = player.y - 85;
            // Dart faces left, too
            playerDart.scaleX = -1;
        }
        playerDartContainer.addChild(playerDart);
    }
} // End of 'createDart()' function

```

This code is the EnterFrameHandler for the player darts:

```
    // In every frame, call 'movePlayerDarts()' to move the darts within the 'playerDartContainer'
public function playerDartEnterFrameHandler(event:Event):void {
    // Only move the Player's darts if their container has at least one dart within
    if (playerDartContainer.numChildren > 0) {
        movePlayerDarts();
    }
}

```

And finally, this is the code that actually moves all of the player's darts:

```
        // Move all of the Player's darts
public function movePlayerDarts():void {
        for (var pdIns:int = 0; pdIns < playerDartContainer.numChildren; pdIns++) {
            // Set the Player Dart 'instance' variable to equal the current PlayerDart
            playerDartIns = PlayerDart(playerDartContainer.getChildAt(pdIns));

            // Move the current dart in the direction it was shot. The dart's 'x-scale'
                // factor is multiplied by its speed (5) to move the dart in its correct
                // direction. If the 'x-scale' factor is -1, the dart is pointing left (as
                // seen in the 'createDart()' function. (-1 * 5 = -5), so the dart will go
                // to left at a rate of 5. The opposite is true for the right-ward facing
                // darts
            playerDartIns.x += playerDartIns.scaleX * 1;

            // Make gravity work on the dart
            playerDartIns.y += 0.7;
            //playerDartIns.y += 1;

            // What if the dart hits the ground?
            if (HitTest.intersects(playerDartIns, floor, this)) {
                playerDartContainer.removeChild(playerDartIns);
            }

            //trace("Dart x: " + playerDartIns.x);
            trace("Dart y: " + playerDartIns.y);
        }
}

```

# Answer
> 2 votes
You must have added `playerDartContainer` to the player sprite during your setup, or to another display list container that also holds the player sprite, thus you're moving them both. In that case, the `playerDartContainer` will always have it's local coordinates as (0,0) as you mentioned -- in terms of it's direct parent, it is not actually moving.

---

**Follow up** If you place your player in the middle of the screen, and you place your dart container in the middle of the screen and don't move it, that's where the container's going to stay -- thus the darts will look relative to the player, because their container always stays in the same screen pos as the player. You have to move your background and your darts container, relative to the player. The player's the only thing that should never move (i.e. remain centred). In fact, you have this:

* document/application class (eg. "YourGameName" or "Main")
* + background sprite (presumably moves relative to player)
* + player sprite (stays in middle of screen)
* + dartContainer sprite (yours stays in middle of screen with player, but should move relative to player)
* + - dart 1 (moves relative to container -- which is in same place as player!)
* + - dart 2 (moves relative to container -- which is in same place as player!)
* + - etc.

I would just have this:

* document/application class (eg. "YourGameName" or "Main")
* + background sprite (moves relative to player)
* + player sprite (mid screen)
* + dart 1 (moves relative to player)
* + dart 2 (moves relative to player)
* + etc.

That's your choice though. As long as you make sure the container moves in the same way your background does (if you have a scrolling background?), it will work.

```
public function movePlayerDarts():void {
        //shift the container screen pos relative to the player, since they have
        //different world positions and screen pos is a derived from world pos.
        playerDartContainer.x = (stage.stageWidth / 2) - player.x;
        playerDartContainer.y = (stage.stageHeight / 2) - player.y;

        for (var pdIns:int = 0; pdIns < playerDartContainer.numChildren; pdIns++) {
            // Set the Player Dart 'instance' variable to equal the current PlayerDart
            playerDartIns = PlayerDart(playerDartContainer.getChildAt(pdIns));

            // Move the current dart in the direction it was shot. The dart's 'x-scale'
                // factor is multiplied by its speed (5) to move the dart in its correct
                // direction. If the 'x-scale' factor is -1, the dart is pointing left (as
                // seen in the 'createDart()' function. (-1 * 5 = -5), so the dart will go
                // to left at a rate of 5. The opposite is true for the right-ward facing
                // darts
            playerDartIns.x += playerDartIns.scaleX * 1;

            // Make gravity work on the dart
            playerDartIns.y += 0.7;
            //playerDartIns.y += 1;

            // What if the dart hits the ground?
            if (HitTest.intersects(playerDartIns, floor, this)) {
                playerDartContainer.removeChild(playerDartIns);
            }

            //trace("Dart x: " + playerDartIns.x);
            trace("Dart y: " + playerDartIns.y);
        }
}

```

---
Tags: actionscript-3, platformer
---


# Question
Title: How do you map a 3D scene to a stero image pair?
I'm a novice. I'm working in XNA studio with simple models.

How can I turn a 3D image into two images meant for the left and right eyes respectively?

Note: I'm not referring to "magic eye" - I'm wondering how you calculate the left and right images starting from the 3D scene info.

# Answer
> 2 votes
Basically, you place two cameras pointing in the same direction a short distance apart, like a person's left and right eyes, and render the scene from each camera.

There's a lot of details to get right. You need nonstandard projection matrices for the stereo cameras to make the images mesh properly when viewed on a 3D TV or similar device; you have to decide how far into the scene you want the focal plane to be, and where the user's screen is relative to the scene (for instance, does anything in the scene "pop out" of the screen, or is it all behind the screen); there are also issues with comfort zones, where you can cause people to experience headaches or strain while viewing the image if you deviate outside the comfort zone.

Here is a good set of presentations that go into these issues in a lot more detail: http://developer.nvidia.com/siggraph-2011-stereoscopy-course. Once you know the key terms, I'm sure you can find more on the Web as well.

---
Tags: algorithm
---


# Question
Title: How well does Unity 3d work for both Android and iPhone?
First off this question might be a bit broad so I apologize if it is. I am really just looking for peoples experiences and personal knowledge on the subject. I am looking to create a game for both Android and iPhone platform. I know Unity is a great game engine and my question is how well does it work for creating one code base to build for both Android and iPhone platforms? Time is a constraint on this project so I am very interested in how smoothly the process usually is when trying to build both applications and how much custom code must be written for each specific application. Any insite that people have on this topic would be much appreciated thanks.

# Answer
Depends on the scope of your project. As long as you don't need anything fancy, Unity3D works pretty much the same on Android and iOS. However, there are times when you need to access OS services, and when this happens, you have to write plugins. These plugins, of course, have nothing in common between Android and iOS.

Also, Unity3D imports all art assets, converting them to a format used on target device. This means that when you switch targets from iOS to Android and back, everything needs to be reimported. This process takes anywhere from several minutes to hours, depending on project size.
> 5 votes

# Answer
Unity3d is based off of mono. Mono is an open source API that runs on tons of OSs which includes android and IOS. Check out : http://en.wikipedia.org/wiki/Mono\_(software)

For development, unity3d has created libraries ontop of the Mono platform that make it easy to get inputs from the device in a standard way. Example for the accelerometer leaning the mobile device forward will be detected by the same code regardless of the device/OS. See : http://unity3d.com/support/documentation/ScriptReference/Input.html

Hope this helped.
> 1 votes

---
Tags: android, iphone, unity, ios
---


# Question
Title: How should I do 3D games through Java on a mac?
I have been self-teaching myself Java on the mac mostly because the language is cross-platform. Recently, I have been only able to develop 2D games using the Graphics2D class. Now, I want to learn how to make 3D games in Java. I used to model and animate stuff in 3D, so my knowledge of 3-Dimensional stuff is okay.

I have spent the last 3 hours using google to look up ways of making 3D games in java. Apparently the best one to use is OpenGL, so i looked up a tutorial on it and i cannot find a tutorial that shows how to (if there is a way) install JOGL on the Mac platform.

Should i continue to use Java?

How can i make 3D games using Java?

What is the best way to make 3D games on a mac?

# Answer
> 8 votes
I would recommend using LWJGL. It's an OpenGL library for Java that works on Mac, Linux, and Windows.

You can make 3D games in Java just as easily as you would in C or C++ using LWJGL. Although some may complain that Java is slow, modern Java is fast enough for game purposes.

An example of a successful game created using LWJGL: Minecraft. Another: Revenge of the Titans (cannot post link.)

If you're looking for more game-development tutorials, there are many available on the LWJGL wiki / website / forums. Also, you can follow many C or C++ OpenGL tutorials as the OpenGL functions work almost exactly the same on Java.

# Answer
> 4 votes
I would suggest to go for jMonkeyEngine with my eyes closed. Its based on LWJGL. But, starting form pure LWJGL can be quite a lengthy road. jMonkey engine is based on LWJGL and all the necessary things are already done for you. You just need to have a game concept and jump right into programming, which is very easy with jME. As you have mentioned your skill level as beginner in your post, I would suggest not-to-start with LWJGL.

Its on Beta right now. But, don't back of. Its quite stable and full of feature. Most importantly its a shader based engine. There are some fixed function rendering pipeline support, but hey, who should pick an old tech unless s/he has a very specific reason to do so?

Documentations are absolutely fantastic. Very rich and covering a wider variety of concepts. Anyone with a basic java skill can jump right in. Community forum is vibrant. If you stumble upon any bug, its fixed very quickly.

jME isn't just a java library. It comes with a game development environment which is based on NetBeans. All 3rd party tools like, Font Converter, Blender/mesh/obj importer, Scene Editor all are included, they just work!

I can't emphasis it enough. There are lots of other java based game engine out there. But trust me your time with jME, you wont regret it.

oh, did I mention...jME has just announced a Game contest as its stable release is nearing. join it if you can. :)

If you still wish to know about other java engines, just give a knock.

---
Tags: opengl, java, jogl
---


# Question
Title: How can I cull non-visible isometric tiles?
I have a problem which I am struggling to solve. I have a large map of around 100x100 tiles which form an isometric map. The user is able to move the map around by dragging the mouse. I am trying to optimize my game only to draw the visible tiles.

So far my code is like this. It appears to be ok in the x direction, but as soon as one tile goes completely above the top of the screen, the entire column disappears. I am not sure how to detect that all of the tiles in a particular column are outside the visible region.

```
    double maxTilesX = widthOfScreen/ halfTileWidth + 4;
    double maxTilesY = heightOfScreen/ halfTileHeight + 4;

    int rowStart = Math.max(0,( -xOffset / halfTileWidth)) ;
    int colStart = Math.max(0,( -yOffset / halfTileHeight));

    rowEnd = (int) Math.min(mapSize, rowStart + maxTilesX);
    colEnd = (int) Math.min(mapSize, colStart + maxTilesY);

```

EDIT - I think I have solved my problem, but perhaps not in a very efficient way. I have taken the center of the screen coordinates, determined which tile this corresponds to by converting the coordinates into cartesian format. I then update the entire box around the screen.

# Answer
The method you are using in your question is the way I have also done culling for my isometric game (personally I think the best way to cull an isometric map, would be interested in other ways though). To go into some of the specifics, this is how I solved the same problem.

My main drawing loop looked something like:

```
for (int y = yMin; y <= yMax; y++)
{
    for (int x = xMin; x <= xMax; x++)
    {
        //drawing here using x and y as index on arrays
    }
}

```

Before this is called, I updated my `xMax` and `yMax` which was based on camera location, zoom and resolution of the screen. `midTile.X` and `midTile.Y` are the rows and columns values of the centre tile (starting point). Then half the screen resolution is then divided by number of tiles (rows or columns) between the centre tile and the edge of the screen to a distance in tiles from the centre tile. Zoom is taken into account if needed to scale.

```
 midTile = GetCentreTile(gameCamera);
 xMax = (int)(midTile.X + Math.Round((HalfScreenResX / (TileWidth / 2)) / Zoom));
 xMin = (int)(midTile.X - Math.Round((HalfScreenResX / (TileWidth / 2)) / Zoom));
 yMax = (int)(midTile.Y + Math.Round((HalfScreenResY / (TileHeight / 2)) / Zoom));
 yMin = (int)(midTile.Y - Math.Round((HalfScreenResY / (TileHeight / 2)) / Zoom));

```

Personally I render the map with an offset by 1X to make other calculations easier, so in this case you'll want to compensate by + 1 on the rows (X) that you are dividing the screen resolution by.

Also a good idea to make sure your values are valid inside the map to avoid invalid index array problems.

```
xMin = xMin >= 0 ? xMin : 0;
xMax = xMax <= map.Width - 1 ? xMax : map.Width - 1;
yMin = yMin >= 0 ? yMin : 0;
yMax = yMax <= map.Height - 1 ? yMax : map.Height - 1;

```

I've found this method to be more efficient than checking every tile's visible property, also, isometric drawing order is very important once to get to objects walking 'behind' and 'in-front' of other objects you are rendering associated with tiles on your map.

Hope this helped.
> 2 votes

# Answer
The bug is not in the code you've shown us.

Anyway, your tile drawing loop should look something like this pseudocode:

```
for each row from rowStart to rowEnd do:
    for each col from colStart to colEnd do:
        draw tile at row,col;
    end
end

```

I'd guess that you're doing something else, and that this is causing the bug. Perhaps if you actually showed us that code...

(Ps. All of this assumes that your rows are in fact shown horizontally and your columns vertically on the screen. If you're storing your map so that your rows and columns actually look diagonal on the screen, the math gets a bit more complicated.)
> 0 votes

---
Tags: maps, isometric
---


# Question
Title: What are some good game programming short courses?
I'm from Brazil, and I want to take a short course on game programming, 2 months at most, in a country that lectures are given in english. I'm almost a BSc in Computer Science alredy.

Can you tell me what you think about this courses? What are some good courses in that format?

# Answer
> 2 votes
> Can you tell me what you think about this courses? What are some good courses in that format?

You haven't told us much about, what is this **this course** you are talking about. So, really there is not much room for us to suggest you the right and/or wrong. Like everybody else I am going to take the generic route.

Another thing I want to point out is, you haven't told us about your skill level. Let me assume that you are a good programmer with a fair knowledge on algorithm.

### 1st Scenario

Ok, now I am going to chunk up my answer on different stages. And first I am going to assume you are the main programmer and programmers art is gonna flood in. Most of the time you will be busy in reading/writing code and some sample asset will be ok for your game.

When you start developing game you will notice how different it is form solving individual problem found on ACM, TopCoder or CodeChef. As I have already assumed you are no guru level programmer, I am taking this as a granted that you are going to work with different modules(for graphics, for physics, for audio for etc) and gonna marge them in a single framework that suits your need.

Here is the catch, most of the time you will be going to good/bad documented/commented code to figure out how they work and or how to make them work. So, here the skill you will be needed is *the patience* and the necessary skill to going through others code and of course the mathematical knowledge to understand the implementation.(With a good debugging skill.)

So, now you answer me, does this 2 month course is going to help you to have any of these skills? If you are a good/moderate programmer already, then you already know this and of course wont be needing any extra guideline(Even if you need, you will be able to pick it up along the way). These are the bread and butter of any programmers life.

Give yourself a checkride, Making anything simple using any of the following engines :

* OGRE : As the name says its a open graphics rendering engine. Its not a complete solution for game development. Its just provided the rendering module and all other modules, like physics and networking, have to marge by you.Which is not a trivial task. Its based on C++.
* jMonkeyEngine : This is a complete solution for game development. Its based on java. I guess you are more inclined to learn the game development terminologies, so starting with this one will pay off. Its shader based, with little fixed function rendering support. So, when you are wroking with this engine, you will learn all the high end thingies that will come in handy in the long run, on any engine that you end up with. Its easy to start with.

Try to make something, using any of this 2 engines. Upon successful completion you will find out your skill level and demand of any training by yourself.

### 2nd Scenario

Now, let me assume that you are the only programmer and want to make games instead of messing around with lots of libraries. High quality asset is not a low priority here. You want an magic box that does all the boring stuff for you so concentrate on the game logic itself.

Here are the options,

Unreal development is notorious for its learning curve. But I've found it not that hard once you understand the underlying structure. Here you have top notch editor for world building, cinematic editor, particle editor, visual game logic constructor etc etc. All you need to make a game. Unlike OGRE or jMonkeyEngine, here you only have to code when you want to specify a veery specific behaviour to a particular entity. Other then that, most of the things are just drag and drop, point and click. Its fun, but takes away the pleasure of programming.

Roughly speaking Unity is like UDK. Most of these are a high level game development kit that just requires some fundamental understand current tech jargon.CryEngine is similar to above 2 mentioned. You have to try out all of them(dont worry, you will feel right at home after a few hour spending with them)

Ok, now these game development toolkit are a complete package with different use restrictions. And all of these tools have *EXTENSIVE* documentation hooked up in their website. Massive Community. Regular Update. Just about almost everything any game developer could ask for. (of course I am talking about beginners)

Make anything using these toolkit. Give a checkride. See how fast/easy/comfortable you feel with these. Then ask yourself again, do you need to have a training to get used to with some tools? If you can't even teach yourself a simple tool where everything is almost ready, then I would suggest you to back off from the whole game development thingy.

### Now ask yourself again

After doing any of these 2 tests you will automatically understand your strength and weakness as a game programmer/developer. Along the way you will learn all the necessarily technical knowledge required. At first things might look hard, yes as beginners its always a bit steep to step into the game programming/developing realm. But, trust me it very rewarding when you get a hold onto something that you did't knew half an hour ago. But, if you get yourself enroll into a training(of 2 month only), yes those jargon will sound familiar to you when you read the doc, but that's not a good way to start.

### Do you need a 2 month training?

Not necessarily. Just start with something. Make something. On that way you will find out what you know and what don't. Always keep pushing the limit. And if you really want to learn form ABCD...well, what can I say...Google a bit. Read whatever you find.

Just a foot note, don't waste you time reading OpenGL 1 tutorials. :)

# Answer
> 6 votes
If you're almost a B.Sc., then take that knowledge today, get a couple good books, and start leveraging the vast resources across the web to learn the basics of game development. (Welcome to the industry.) If you haven't learnt enough about technical programming during your bachelors studies to do that, then short courses aren't going to help you very much anyway.

The point is, from where you stand now, you should already have the most important knowledge you need to get going -- without paying someone else to teach you things you can easily learn yourself.

You get out what you put in, and that applies to short, cheap courses as much as anything else.

# Answer
> 3 votes
I wrote and presented a short crash course on the world of game programming; you can find the slides here: http://iki.fi/sol/gpc/

..and the practical stuff here: http://iki.fi/sol/gp/

Apart from that, I wholeheartedly agree with Nick, there. It's also best not to do this alone; find same-minded people and start a local game programming club! =)

# Answer
> 3 votes
Let me start by saying, I can not answer your question. I do not know any courses in the two month range that would influence me (as someone with decision making authority) to hire you which I assume is ultimately your goal.

There are educational programs that provide concentrated programs related to game development. These types of concentrated programs *can* provide canidates that have a useful base exposure to the problems of game programming...they are not a guarantee that **you** personally will finish the program as an person desirable to the game industry.

As your subsequent responses indicate, networking is a consideration...but honestly any company that is hiring is going to consider a good candiate. So...what makes a good candidate?

Someone who...

1. is interested in solving problems
2. solves problems outside of class and finds it to be "fun" (sample programs you personally developed are a plus, even if they do not work show me the code and you might impress me)
3. is curious
4. learns on their own (sorry, school only teaches you a fraction of what you need to know and how you need to approach problems). READ STUFF!!! EXPERIMENT!!! There are numerous articles on this site of books and basic concepts of which you should be at least aware.
5. understand after gradutation you really know nothing. A degree (even a PhD) does not mean you know how to program for a environment requiring a networked, asynchronous application development involving high performance networking, persistence and graphical (client) layers in a mid-large sized team. Programming for Massive Multiplayer Online games combines all of the really hard computer science problems you have studied (and a bunch of others you have never heard of...) in spades. No shame here, after decades in the industry we are still learning stuff too!
6. I want to know that you can THINK. I will ask you oddball questions in an interview and listen to your response. I do not care if you are "technically" correct...how do YOU solve problems is what matters. You get good at this...by solving problems.
7. Game programming tends to be a meritorcacy, I (we) do not believe we know everything. Show me I am wrong, and I'll listen (but you better be able to prove it with stats...and I'll rebut with other companies trying to do X and the problems they encountered).
8. Be humble, but stand your ground when you strongly believe in something. No matter what you think you know, someone will always know more...but sometimes you might be right too. At the end of the day, accept sometimes your manager might have other considerations that affect the ultimate decision.
9. We do not care if you have an idea for a game design...ideas are pennies per dozen. Execution of the idea is what matters.

As an unknown, what YOU KNOW and CAN DO is much more imporant to me than who you know. At my company we have a standarized test which we hope a slightly trained C++ monkey (most of whom fail...which I fear reflects badly on the educational establishment) could pass and the multiple levels of interviews that test the extents of a candidate's personal knowledge. We do not care if the candidate knows exactly how C++ templates work or all of the stupid edge conditions that some (dumb) interview "tests" ask. Know what you do not know, and know how you could expand your knowledge to cover that weakness.

There are a variety of articles on the over reliance on "riddles" and obscure language trivial being examples of lazy/poor Human Resources filtering mechanisms...you really do not want to work there anyway.

Know what you want to become...work towards that goal...and prove you know what you know. I do not care if you do not know everything (I know you do not...so do not try to lie about it), prove you know how to ask (relevant) questions and know how to take feedback and learn.

---
Tags: software-engineering
---


# Question
Title: Actionscript 3.0 - Enemies do not move right in my platformer game
I am making a side-scrolling platformer game in Flash (Actionscript 3.0). I have made lots of progress lately, but I have come across a new problem.

I will give some background first. My game level's terrain (or 'floor') is referenced by a MovieClip variable called 'floor.' My desire is to have the Player and enemy characters walk along the terrain. I have gotten the Player character to move on the terrain just fine; he walks up/down hills and falls whenever there is no ground beneath him.

Here is the code I created to allow the Player to follow the terrain correctly. Much more code is used to control the Player, but only this code deals with the Player character's following of the terrain and gravity.

```
    // If the Player's not on the ground (not touching the 'floor' MovieClip)...
    if (!onGround) {
        // Disable ducking
        downKeyPressed = false;
        // Increase the Player's 'y' position by his 'y' velocity
        player.y += playerYVel;
    }

    // Increase the 'playerYVel' variable so that the Player will fall
        // progressively faster down the screen. This code technically
        // runs "all the time" but in reality it only affects the player
        // when he's off the ground.
    playerYVel += gravity;

    // Give the Player a terminal velocity of 15 px/frame
    if (playerYVel > 15) {
        playerYVel = 15;
    }

    // If the Player has not hit the 'floor,' increase his falling
        //speed
    if (! floor.hitTestPoint(player.x, player.y, true)) {
        player.y += playerYVel;
        // The Player is not on the ground when he's not touching it
        onGround = false;
    }

```

Since getting this code to work for the Player, I have created a 'SkullDemon' class, which is one of the planned enemies for my game. I want the 'SkullDemon' objects to move along the terrain like the Player does. With lots of great help, I have already coded the EventListeners, etc. necessary for the 'SkullDemons' to move.

Unfortunately, I am having trouble getting them to move along the terrain. In fact, they do not touch the terrain at all; they move along the top of the boundary of the 'floor' MovieClip! I had a simple text diagram showing what I mean, but unfortunately Stackoverflow does not format it correctly. I hope my problem is clear from my description.

Strangely enough, my code for the Player's movement and the 'SkullDemon's' movement is almost exactly the same, yet the 'SkullDemons' do not move like the Player does. Here is my code for the SkullDemon movement:

```
    // Move all of the Skull Demons using this method
protected function moveSkullDemons():void {
    // Go through the whole 'skullDemonContainer'
    for (var skullDi:int = 0; skullDi < skullDemonContainer.numChildren; skullDi++) {
        // Set the SkullDemon 'instance' variable to equal the current SkullDemon
        skullDIns = SkullDemon(skullDemonContainer.getChildAt(skullDi));

        // For now, just move the Skull Demons left at 5 units per second
        skullDIns.x -= 5;

        // If the Skull Demon has not hit the 'floor,' increase his falling
            //speed
        if (! floor.hitTestPoint(skullDIns.x, skullDIns.y, true)) {
            // Increase the Skull Demon's 'y' position by his 'y' velocity
            skullDIns.y += skullDIns.sdYVel;
            // The Skull Demon is not on the ground when he's not touching it
            skullDIns.sdOnGround = false;
        }

        // Increase the 'sdYVel' variable so that the Skull Demon will fall
            // progressively faster down the screen. This code technically
            // runs "all the time" but in reality it only affects the Skull Demon
            // when he's off the ground.
        if (! skullDIns.sdOnGround) {
            skullDIns.sdYVel += skullDIns.sdGravity;

            // Give the Skull Demon a terminal velocity of 15 px/frame
            if (skullDIns.sdYVel > 15) {
                skullDIns.sdYVel = 15;
            }
        }

        // What happens when the Skull Demon lands on the ground after a fall?
            // The Skull Demon is only on the ground ('onGround == true') when
                // the ground is touching the Skull Demon MovieClip's origin point,
                // which is at the Skull Demon's bottom centre
        for (var i:int = 0; i < 10; i++) {
            // The Skull Demon is only on the ground ('onGround == true') when
                // the ground is touching the Skull Demon MovieClip's origin point,
                // which is at the Skull Demon's bottom centre
            if (floor.hitTestPoint(skullDIns.x, skullDIns.y, true)) {
                skullDIns.y = skullDIns.y;
                // Set the Skull Demon's y-axis speed to 0
                skullDIns.sdYVel = 0;
                // The Skull Demon is on the ground again
                skullDIns.sdOnGround = true;
            }
        }
    }
} // End of 'moveSkullDemons()' function

```

It is almost like the 'SkullDemons' are interacting with the 'floor' MovieClip using the hitTestObject() function, and not the hitTestPoint() function which is what I want, and which works for the Player character.

I am confused about this problem and would appreciate any help you could give me. Thanks!

# Answer
I also think that the problem is at the line

```
skullDIns = SkullDemon(skullDemonContainer.getChildAt(skullDi));

```

I had a similar situation once and found that is better to store the enemies in an Array that has no children and is not added to the stage. Simply add enemy instances to an Array and loop through them. Then your `SkullDemons` will not have a parent container in the scene tree and will be children of the stage (or some level object).

Make your `skullDemonContainer` an Array like this:

```
var skullDemonContainer:Array = new Array();

```

Then add you `SkullDemons` to the `skullDemonContainer` not as children but like this:

```
skullDemonContainer.push(skullDemon1);

```

Finally change the loop code in your `moveSkullDemons()` method

```
for (var skullDi:int = 0; skullDi < skullDemonContainer.length; skullDi++)
{
    skullDIns = skullDemonContainer.[skullDi] as SkullDemon;
    ...

```
> 1 votes

# Answer
I am not an ActionScript developer. It seems to me that this line

```
skullDIns = SkullDemon(skullDemonContainer.getChildAt(skullDi));

```

constructs a new SkullDemon object and assigns it to the skullDIns variable. Subsequently you modify this copy instead of the object in the container.

I think you should have more success doing this:

```
skullDIns = skullDemonContainer.getChildAt(skullDi);

```
> 0 votes

---
Tags: flash, actionscript-3, movement, platformer
---


title: how large should a map be in blender

text:
# Question
Title: how large should a map be in blender
I'm learning blender and am wondering what size(blender units) I should be making my characters and maps. should i consider 1 blender unit as 1 inch, foot, meter or does it not not matter?

# Answer
> 6 votes
The build-in physics engine assumes 1 BU (Blender Unit) = 1 meter. However, you can use whatever you like, and since Blender 2.5 you can also set an explicit conversion to real-world units (properties editor -\> scene tab -\> units panel). Keep in mind what kind of values your game engine expects, too - most exporters can re-scale the model during the export (same for importers), but not all of them do.

Whatever your choice is, keep in mind that the practical *smallest* unit you can work with is 0.001 BU (Blender will happily record and create smaller or more precise values, but will *not* display them to not clutter the UI), and that the maximum clip distance is 5000 BU - anything bigger will be hard to work with.

If you want to model mostly human-sized entities, including clothing and most tools for such, it makes sense to have 1 BU be equal to 1 mm. If you're more comfortable with "imperial" sizes roughly the same scale would be using 1/20th or 1/24th of an inch. This will make the smallest features you'll likely care about be about 1 BU in size and - for comparison - human hair have 0.01 to 0.2 BU in diameter.

For typical architecture, 1BU = 1m (or one yard for imperial units) will work fine. This will allow you to easily model almost every building (excluding some bridges) and vehicle built to date.

---
Tags: maps, models, 3d-meshes, blender
---


title: physics model simulation

text:
# Question
Title: physics model simulation
I am building a game for which I want to simulate certain rigid body dynamics.Could someone suggest me some engines which work on Ubuntu.Also as I have dont have much time to implement it,so it would be helpful if it is a easy one to work with. I have some across one namely ODE.Am looking for others which would help me simulate collisions and angular movements.

# Answer
> 2 votes
You haven't specified your environment and/or language bindings.

For 2d scenario Box2d is a very elegant choice and it has a lot of language bindings. Its quite easy to use. You just need to hookup your billboard/model/image(s) with its physics object and see the magic happen.

I don't know much about ODE. But have some experience with Bullet.Bullet is faster then ODE. It also has a lot of advanced features i.e. OpenCl cloth simulation.

For closed source PhysX from Nvidia and Havok from Intel. They are also free for commercial use.(there are constrains)

There are others but, above mentioned are most famous. What you want is Rigid body collision and angular movement. Only these 2 feature, shouldn't be very hard or time consuming to integrate. Go through their documentations. Most of them has individual doc part where is explains how to integrate.

---
Tags: opengl, physics, physics-engine
---


# Question
Title: What are some great and useful resources for an Isometric game built on the XNA Framework?
I'm currently working on an isometric game using the Microsoft XNA Framework. I'm looking of resources that would be of use for making this a successful project, such as isometric engines, physics engines, sprite engines(for isometric games), event handlers for ...

Any input would be greatly appreciated.

# Answer
The isometric projection is not so much relevant for the underlying tools you choose, it's just the way (angle, no perspective distortion) you look at things, but that doesn't change the underlying principles of how things behave. That means you don't need to particularly search for isometric tools.

The physics for instance is the same, no matter how you look at it. The math of a car crash does not change, whether you look at it from the left or from the right, it does not depend on the observer. The same is true for a bouncing ball, it does not care if you watch it from the left or from top, it will bounce the same way always.

If you have particular doubts about how to implement such things in terms of isometric projections, please tell us an example and we can go into details :)
> 6 votes

# Answer
I followed the tile engine tutorials on this site: xnaresources.com. The tile engine tutorial starts out as a regular square tile map but on Part Four they convert it to isometric. They cover drawing, tile depth, tile picking (i.e. "What tile did I click on?"), and adding a controllable character.
> 3 votes

# Answer
It's not an engine, but I made a fork of Nick Gravelyn's TiledLib project that shows an example of that library rendering an isometric Tiled map. Not perfect, (probably buggy) but might help you start and if you have any problems, post a bug and I'll see if I can help out.

HTH
> 1 votes

---
Tags: xna, c#, animation, assets, isometric
---


title: Basic A star implementation tutorial

text:
# Question
Title: Basic A star implementation tutorial
> **Possible Duplicate:**
> Pseudo-code examples of A\*?

Hey guys Iam making a TD game and now I am stucked in implementing A star algo. I know there are many 3d party softwares but they are difficult to understand and modify. I want to make own for my game. I need a step wise programming tutorial for implementing A\* OR if someone has basic snippet. I am using unity and c#.

# Answer
As for some snippets, I've written a few articles about A\*. Anyway my latest C# based A\* algorithm is here: http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/ you can use it freely. It also links to some of the articles.
> 2 votes

---
Tags: path-finding, grid
---


# Question
Title: How many threads should an Android game use?
At minimum, an OpenGL Android game has a UI thread and a Renderer thread created by `GLSurfaceView`. `Renderer.onDrawFrame()` should be doing a minimum of work to get the higest FPS. The physics, AI, etc. don't need to run every frame, so we can put those in another thread. Now we have:

1. Renderer thread - Update animations and draw polys
2. Game thread - Logic & periodic physics, AI, etc. updates
3. UI thread - Android UI interaction only

Since you don't ever want to block the UI thread, I run one more thread for the game logic. Maybe that's not necessary though? Is there ever a reason to run game logic in the renderer thread?

# Answer
Google's Chris Pruett talks about this issue in his Replica Island blog. Because eglSwapBuffers() is a blocking call in the GLSurfaceView thread, having game logic code in another thread allows it to run while the swap buffers call is blocking. This is important if your game is complex and you want to achieve 60 frames per second.

You can download the source code for Replica Island and see how they did it. I've implemented something similar for my game (with the three threads you talked about) and it works great.
> 18 votes

# Answer
Android supports standard Java Threads . You can use standard Threads and the tools from the package java.util.concurrent to put actions into the background. The only limitation is that you cannot directly update the UI from the background process.

If you need to update the UI from a background task you need to use some Android specific classes. You can use the class android.os.Handler for this or the class AsyncTasks.

For more details please check out the following link....

http://mindstick.com/Articles/7a9205de-bae7-48ba-81b5-2b2ec161d672/?Thread%20in%20Android
> 2 votes

---
Tags: android, multithreading, opengl
---


# Question
Title: Check if an object is facing another based on angles
I already have something that calculates the bearing angle to get one object to face another. You give it the positions and it returns the angle to get one to face the other.

**Now I need to figure out how tell if on object is facing toward another object within a specified field** and I can't find any information about how to do this.

The objects are **obj1** and **obj2**. Their angles are at **obj1.angle** and **obj2.angle**. Their vectors are at **obj1.pos** and **obj2.pos**. It's in the format \[x,y\]. The angle to have one face directly at another is found with **direction(obj1.pos,obj2.pos)**.

I want to set the function up like this: isfacing(obj1,obj2,area){...} and return true/false depending if it's in the specified field area to the angle to directly see it.

I've got a base like this:

```
var isfacing = function (obj1,obj2,area){
   var toface = direction(obj1.pos,obj2.pos);
   if(toface+area >= obj1.angle && ob1.angle >= toface-area){
       return true;
   }
   return false;
}

```

But my problem is that the angles are in 360 degrees, **never above 360** and **never below 0**. **How can I account for that in this?** If the first object's angle is say at 0 and say I subtract a field area of 20 or so. It'll check if it's less than -20! If I fix the -20 it becomes 340 but x \< 340 isn't what I want, I'd have to x \> 340 in that case.

Is there someone out there with more sleep than I that can help a new dev pulling an all-nighter just to get enemies to know if they're attacking in the right direction? I hope I'm making this harder than it seems.

I'd just make them always face the main char if the producer didn't want attacks from behind to work while blocking. In which case I'll need the function above anyways.

I've tried to give as much info as I can think would help. Also this is in 2d.

# Answer
> 3 votes
```
var isfacing = function (obj1,obj2,area){
    var toface = direction(obj1.pos,obj2.pos);
    var left = toface - area;
    var right = toface + area;

    // Wrap the left and right angles
    if(left < 0){ left += 360; }
    if(right >= 360){ right -= 360; }

    // Do 2 checks:
    // - Where the left is smaller than the right, we should be between both of them.
    // - Where the either the left or right has wrapped around 360 (left > right),
    //   we only need to be facing such that we are either greater than the
    //   left OR less than the right
    if ((left < right && obj1.angle > left && obj1.angle < right) ||
        (left > right && (obj1.angle > left || obj1.angle < right))
    {
        return true;
    }
    return false;
}

```

I like to spread things out, and I would invest in a whiteboard.

# Answer
> 3 votes
You want the absolute value of the angle difference to be smaller than `area` or greater than `360-area`.

Based on your code, I believe this should work:

```
var isfacing = function (obj1,obj2,area) {
   var toface = direction(obj1.pos,obj2.pos);
   var difference = abs(toface - ob1.angle);
   return (difference <= area || difference >= 360 - area);
}

```

**Edit**: my first attempt was totally buggy. Sorry.

---
Tags: mathematics, software-engineering, javascript
---


title: Deterministic replay in a modern game

text:
# Question
Title: Deterministic replay in a modern game
I am doing a study in modern games graphics, and as part of the study it would be really helpful to be able to replay a sequence in the game multiple times. For example, recording a series of inputs to get the exact video sequences, but being able to replay them in different computers or different graphics configurations.

I want to do this study with a couple of existing commercial games with sophisticated graphics (something released in the last 1 or 2 years if possible). I was thinking on hooking with detours or something similar, calls to time() or srand() to fix all pseudo-number generated results. It would be ideal to have a general solution that works with any game. Since admittedly that is pretty ambitious, I would be happy just having 2 or 3 games in which it is known that I can get deterministic output for a given input.

In the end, I will be comparing video output, so I want to avoid noise generated by differences on each execution caused by non-determinism. Any sugestions?

# Answer
> 4 votes
Some games let you record "demos". These demos are essentially recordings of everything that happened in the game and can be re-watched exactly as it was. Here are a couple games that I know do this:

* Starcraft II
* Counter-Strike 1.6 & Source

# Answer
> 4 votes
Noel Llopis has some articles in Game Developer Magazine a few years ago about implementing deterministic replay; they're reprinted here and here.

tl;dr version: record all your input and be able to play it back, avoid real randomness (pseudo-randomness is fine for most cases), and implement determinism testing early so that you know when you break it.

---
Tags: c, game-recording, replays
---


# Question
Title: Hero/Character sprite size in comparison to tile size?
So I'm making this simple platformer where the Hero is 16x16 in size, but also, the tile size is 16x16. Which sounds fine right? But my game window/world is 800x416, which makes the Hero is really really tiny in comparison. This really surprised me, but given Ive never made a platformer before it is also a new discovery.

Is there a rule set for scale in platformer games?

I'd like to have my game window remain the size it is (800x416), cause the game involves large levels. But how big should my hero be?

I hope I was clear with the question, and I appreciate any insight.

Thanks

# Answer
> 11 votes
It's mostly a subjective question, and it depends a lot on your intended game aesthetic and mechanics.

The important ratio is feature size to screen size, not feature size to tile size. Some numbers are given here : http://kotiro.petermichaud.com/visual/resolution/. As you might notice, the original Mario Bro featured a really small mario, not only in terms of pixel resolution, but also in terms of screen real-estate (1/20 of the height). You barely knew what your character was supposed to be, and it's hard to build attachment to something that small. Later games in the series (whether it was Mario 3 or Mario World or Paper Mario) had a character roughly 1/8 the height of the screen, regardless of the resolution.

I'd also argue that the speed of your game somewhat influences the size. For example, Super Meat Boy features a fast-moving blob in a unforgiving environment. The view is zoomed out further and the features and characters smaller, but with how fast Meat Boy moves, it would be claustrophobic and deadly obstacles would severely test player reflexes. There's still a lot of times when the camera zooms in, so that you can identify with the character better. For contrast, Castlevania features a slow-moving protagonist and the game centers around interaction between you and nearby enemies, so the larger feature size works well.

# Answer
> 2 votes
> Is there a rule set for scale in platformer games?

No. This is generally a matter of taste and the visual style you want your game to have. You should try a few different ratios of tile size to player size to screen size and see which feels best to you.

As Jimmy pointed out in the comments, the size differential between the player and the screen is likely going to have a bigger impact on the feeling of the game. The size of the tiles relative to the player should be an implementation detail (for example, consider that on many old consoles, hardware sprites were a fixed size, and so in-game "sprites" that were larger were just composed of multiple tiles).

In order to do this, it's important to structure your game so that those ratios can be changed relatively easily -- so you don't want a lot of hard-coded tile bounds in your code, for example.

---
Tags: sprites, platformer
---


# Question
Title: How do I declare the variable "i" and "remove" in actionscript3?
```
public function remove(u:Unit)
{
    for (var i = 0; i < size; ++i)

}

```

The errors are:

```
1008: variable 'i' has no type declaration
1008: return value for function 'remove' has no type declaration

```

# Answer
> 1 votes
You have no braces after your for-loop declaration.

```
public function remove(u:Unit)
{
     for (var i = 0; i < size; ++i)
     {}
}

```

Also, perhaps size is not defined.

Please, in future use stackoverflow.com for pure programming type questions such as this.

---
Tags: actionscript-3, flash-develop
---


title: Make an object slide around an obstacle

text:
# Question
Title: Make an object slide around an obstacle
I have path areas set up in a game I'm making for canvas/html5 and have got it working to keep the player within these areas. I have a function isOut(boundary, x, y) that returns true if the point is outside the boundary. What I do is check only the new position x/y separately with the corresponding old position x/y. Then if each one is out I assign them the past value from the frame before. The old positions are kept in a variable from a closure I made.

like this:

```
opos = [x,y];//old position
npos = [x,y];//new position

if(isOut(bound, npos[0], opos[1])){
    npos[0] = opos[0]; //assign it the old x position
}
if(isOut(bound, opos[0], npos[1])){
    npos[1] = opos[1]; //assign it the old y position
}

```

It looks nice and works good at certain angles, but if your boundary has diagonal regions it results in jittery motion. What's happening is the y pos exits the area while x doesn't and continues pushing the player to the side, once it has moved the player to the side a bit the player can move forward and then the y exits again and the whole process repeats. **Anyone know how I may be able to achieve a smoother slide**? I have access to the player's velocity vector, the angle, and the speed(when used with the angle). I can move the play with either angle/speed or x/yvelocities as I've built in backups to translate one to the other if either have been altered manually.

# Answer
> 1 votes
assuming that path is created from a polyline, your isOut function can do more than just returning whether player is outside of the path or not. it's almost easy to determine which line your player passed when it moved outside, and then it's easy to calculate a vector perpendicular to crossed line and exact position where player went out of boundary. using these data you can create a new movement function which won't go out of path.

another way is the code I'm posting here, it's a code we once used to solve slide problem in a game and it worked well enough. hope you can convert this code:

```
NiPoint3 CTerrainController::GetSlideMovement(NiPoint3 &pOrigin, NiPoint3 &pDir)
{
    const unsigned int SearchCount = 5;
    float start, end;
    float rang;
    NiPoint3 rh, lh;

    NiPoint3 right;
    start = 0.0f;
    end = -NI_PI / 2.0f;
    rh = pOrigin;
    rh.z -= CHARACTER_WAIST_HEIGHT;
    for (unsigned int i = 0; i < SearchCount; i ++)
    {
        float ang = (start + end) / 2.0f;
        NiMatrix3 rot;
        rot.MakeZRotation(ang);
        right = rot * pDir;
        right *= (pDir * right) / right.SqrLength();
        if (mPick.PickObjects(pOrigin + right, -NiPoint3::UNIT_Z) && mPick.GetResults().GetAt(0)->GetAVObject()->GetName() != "collision_no walk")
        {
            end = ang;
            rh = mPick.GetResults().GetAt(0)->GetIntersection();
        }
        else
            start = ang;
    }
    rang = -end;

    NiPoint3 left;
    start = 0.0f;
    end = NI_PI / 2.0f;
    lh = pOrigin;
    lh.z -= CHARACTER_WAIST_HEIGHT;
    for (unsigned int i = 0; i < SearchCount; i ++)
    {
        float ang = (start + end) / 2.0f;
        NiMatrix3 rot;
        rot.MakeZRotation(ang);
        left = rot * pDir;
        left *= (pDir * left) / left.SqrLength();
        if (mPick.PickObjects(pOrigin + left, -NiPoint3::UNIT_Z) && mPick.GetResults().GetAt(0)->GetAVObject()->GetName() != "collision_no walk")
        {
            end = ang;
            lh = mPick.GetResults().GetAt(0)->GetIntersection();
        }
        else
            start = ang;
    }

    if (rang < end)
        return rh;
    return lh;
}

```

some notes:

this function gets player origin and velocity as input and then returns velocity after applying slide effect. it's trying to find some free space in front of player and tells player to move in that specific direction. if statement which checks for picked objects is almost equivalent of `if(!isOut(pOrigin + right))`

---
Tags: mathematics, software-engineering, javascript, linear-algebra
---


# Question
Title: Calculating the rotational force of a 2D sprite
I am wondering if someone has an elegant way of calculating the following scenario.

I have an object of (n) number of squares, random shapes, but we will pretend they are all rectangles.

We are dealing with no gravity, so consider the object in space, from a top down perspective. I am applying a force to the object at a specific square (as illustrated below).

How do I calculate the rotational angle, based on the force being applied, at the location being applied. If applied in the center square, it would go straight. How should it behave the further I move from the center? How do I calculate the rotational velocity?

# Answer
You're trying to calculate the Torque. Torque depends on the applied force F, the point of application, and the center of mass of the object.

1) **Center of Mass**. Define the center of mass of the object.

2) **Point of Application**: Define the point at which the force acts on.

3) **Moment Arm**: The distance between the two points defined above.

```
Point centerofMass
Point applicationPoint
Vector momentArm = applicationPoint - centerofMass

```

4) **Angular force**: Divide your force F into two orthogonal vectors, one Parallel to the line in 3) and one Perpendicular. The parallel component does not affect angular momentum. The perpendicular one does. You can calculate the parallel component by vector projection. You can subtract that from the original to get the perpendicular component. In pseudocode (`dot` means dot-product)

```
Vector myForce
Vector momentArm

parallelComponent = momentArm * (dot(myForce, momentArm) / dot(momentArm, momentArm))
angularForce = myForce - parallelComponent

```

5) **Torque**: The perpendicular component of the force multiplied by the length of the moment arm.

```
Vector angularForce
Vector torque = angularForce * momentArm.Length

```

To get from Torque to angular velocity:

1) **Moment of Inertia**: A definition of how much rotational inertia a given object has. For example, it takes more torque to rotate a long bar than a sphere of the same mass. If you aren't concerned about realism, you can pretend the moment of inertia is relative to the mass, or you could ignore the shape and mass of the object entirely.

2) **Angular acceleration**:

```
Vector angularAcceleration = torque / momentOfInertia

```

3) **Angular Velocity**: The Angular velocity will keep increasing as long as torque is being applied. So a formula will roughly be "Angular Velocity at time *T* is the cumulative sum of Angular acceleration up until *T*." This is expressed in pseudocode as

```
void Update(float elapsedSeconds):
    orientation += 0.5 * angularVelocity * elapsedSeconds;
    angularVelocity += angularAcceleration * elapsedSeconds;
    orientation += 0.5 * angularVelocity * elapsedSeconds;

```
> 45 votes

# Answer
if forces are not too strong it's much more easier to simulate rotation using multiple dots and springs connecting them. in that case you just assume your shape in consist of multiple dots connected by springs. each dot represent mass and every thing else in shape has mass equal to zero.

in above picture black point represent masses and red line represent springs. then to apply the force you just have to apply it to the nearest dot and you'll see your object will rotate just as you like. to make your shape look like a solid structure it's better to define springs with a high damping value and high k value.
> 7 votes

---
Tags: 2d, rotation, physics, vector
---


# Question
Title: how can I specify interleaved vertex attributes and vertex indices
I'm writing a generic ShaderProgram class that compiles a set of Shader objects, passes args to the shader (like vertex position, vertex normal, tex coords etc), then links the shader components into a shader program, for use with glDrawArrays.

My vertex data already exists in a VertexBufferObject that uses the following data structure to create a vertex buffer:

```
class CustomVertex
{
public:
float   m_Position[3];      // x, y, z      // offset 0, size = 3*sizeof(float)
float   m_TexCoords[2];     // u, v         // offset 3*sizeof(float), size = 2*sizeof(float)
float   m_Normal[3];        // nx, ny, nz;
float   colour[4];          // r, g, b, a
float   padding[20];        // padded for performance
};

```

I've already written a working VertexBufferObject class that creates a vertex buffer object from an array of CustomVertex objects. This array is said to be interleaved. It renders successfully with the following code:

```
void VertexBufferObject::Draw()
{
if( ! m_bInitialized )
    return;

glBindBuffer( GL_ARRAY_BUFFER,          m_nVboId );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  m_nVboIdIndex );

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

glVertexPointer( 3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 0) );
glTexCoordPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 12));
glNormalPointer(GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 20));
glColorPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 32));

glDrawElements( GL_TRIANGLES, m_nNumIndices, GL_UNSIGNED_INT, ((char*)NULL +  0) );

glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
glDisableClientState( GL_NORMAL_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );

glBindBuffer( GL_ARRAY_BUFFER,          0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  0 );
}

```

Back to the Vertex Array Object though. My code for creating the Vertex Array object is as follows. This is performed before the ShaderProgram runtime linking stage, and no glErrors are reported after its steps.

```
// Specify the shader arg locations (e.g. their order in the shader code)
for( int n = 0; n < vShaderArgs.size(); n ++)
    glBindAttribLocation( m_nProgramId, n, vShaderArgs[n].sFieldName.c_str() );

// Create and bind to a vertex array object, which stores the relationship between
// the buffer and the input attributes
glGenVertexArrays( 1, &m_nVaoHandle );
glBindVertexArray( m_nVaoHandle );

// Enable the vertex attribute array (we're using interleaved array, since its faster)
glBindBuffer( GL_ARRAY_BUFFER,          vShaderArgs[0].nVboId );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  vShaderArgs[0].nVboIndexId );

// vertex data
for( int n = 0; n < vShaderArgs.size(); n ++ )
{
    glEnableVertexAttribArray(n);

    glVertexAttribPointer(
        n,
        vShaderArgs[n].nFieldSize,
        GL_FLOAT,
        GL_FALSE,
        vShaderArgs[n].nStride,
        (GLubyte *) NULL + vShaderArgs[n].nFieldOffset
    );

    AppLog::Ref().OutputGlErrors();
}

```

This doesn't render correctly at all. I get a pattern of white specks onscreen, in the shape of the terrain rectangle, but there are no regular lines etc. Here's the code I use for rendering:

```
void ShaderProgram::Draw()
{
using namespace AntiMatter;

if( ! m_nShaderProgramId || ! m_nVaoHandle )
{
    AppLog::Ref().LogMsg("ShaderProgram::Draw() Couldn't draw object, as initialization of ShaderProgram is incomplete");
    return;
}

glUseProgram( m_nShaderProgramId );
glBindVertexArray( m_nVaoHandle );
glDrawArrays( GL_TRIANGLES, 0, m_nNumTris );

glBindVertexArray(0);
glUseProgram(0);
}

```

Can anyone see errors or omissions in either the VAO creation code or rendering code?

thanks!

# Answer
If you want to use VAOs with index buffers, you need `glDrawElements()` instead of `glDrawArrays()`. What you are seeing is probably all your vertices being rendered as triangles, as if there was no index buffer.
> 5 votes

---
Tags: c++, opengl, vertex-arrays, index-buffer
---


# Question
Title: What is UVIndex and how do I use it on OpenGL?
I am a noob in OpenGL ES 2.0 (for WebGL) and I'm trying to draw a simple model I've made with a 3D tool and exported to .fbx format. I've been able to draw some models that only have: A vertex buffer, a index buffer for the vertices, a normal buffer and a texture coordinate buffer, but this model now has a "UVIndex" and I'm not sure where am I supposed to put this UVIndex. My code looks like this:

```
GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.VertexBuffer);
GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["vPosition"],3,GL.FLOAT, false, 0, 0);
GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.NormalBuffer);
GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["vNormal"], 3, GL.FLOAT, false, 0, 0);
GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.TexCoordBuffer);
GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["TexCoord"], 2, GL.FLOAT, false, 0, 0);

GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, this.Model.House.IndexBuffer);

GL.bindTexture(GL.TEXTURE_2D, this.Texture.HTex1);
GL.activeTexture(GL.TEXTURE0);

GL.drawElements(GL.TRIANGLES, this.Model.House.IndexBuffer.Length, GL.UNSIGNED_SHORT, 0);

```

But my model renders totally incorrect and I think it has to do with the fact that I am ignoring this "UVIndex" in the .fbx file, since I've never drawn any model that uses this UVIndex I really have no clue on what to do with it.

This is the json file containing the model's data: http://pastebin.com/raw.php?i=G294TVmz

# Answer
> 7 votes
UVIndex represents a series of indices that index into the UV array.

However, OpenGL (and D3D) do not allow you to use *multiple* indices. Each attribute cannot have its own index; the index represents all attributes. Therefore, you need to massage your data a bit, so that everything comes from a single index list.

To put it another way, you cannot take an FBX file, turn it into JSON, load it, and expect OpenGL to render with it. You need to use a tool to regularize the vertex data.

# Answer
> 1 votes
The `TexCoord` array is just an array that stores all the possible values of your texture coordinates, so you can't directly access it. You have to index it via `TexCoordIndices`, much like `Indices` does it for the positions of the vertices.

And I would check for the negative values that you have in `Indices`, I'm pretty sure they represent backward-facing polygons and you have to reverse them manually (I doubt the GPU does this automatically).

---
Tags: opengl, textures, opengl-es, webgl, index-buffer
---


# Question
Title: First Steps. Windows Phone game development
I'm pretty new in game development. Have a couple ideas wich could be cool. First that comes to mind is to develop a 2D game (kinda puzzles) for Windows Phone Mango. You may ask: "Why Windows Phone?". I answer - I've got solid experience in Silverlight and C#. For me, this is a major advantage compared to other platforms.

Please, give advice and suggestions about:

* What should I read?
* Best practices.
* Third party libraries.
* Silverlight(Only) vs XNA.
* Whatever I should pay attention to.

# Answer
> 8 votes
Considering your background, this is a great choice as a way to get into game development.

As far as advice and suggestions go, here are some ideas.

*What should I read?*

There are quite a few sites out there that post tutorials and news regarding Windows Phone / XNA development. Most important (in my opinion) to get you started is the official Education Catalog at the AppHub website. These projects are updated with the latest SDK and have some great examples with full source to get you started. Others sites include:

* Sgt Conker (Not updated as much as it use to but still some great links and tutorials)
* XNA Development (Good tutorials, XNA 3, most lessons still apply even to Windows Phone)

*Best practices*

Very broad question, try going through the AppHub Education catalog first for examples, if none agree with what you are trying to acheive, look here for old questions or ask a new one. Whatever works for you. Getting stuck in design (see Analysis Paralysis) is a horrible problem. Prototype, test, if it works for now, move forward, if not prototype again or move onto another problem and come back to it later. See this question/answer for good practices and some really good advice.

*Third party libraries*

Although finding a library is a good way of getting you up and running quickly instead of re-inventing the wheel, as a beginner, it's always good to start with something simple you can make yourself. Maybe base it off an example and work from there. If you find you want to be able to load a custom file type or overcome a specific problem that you think some one might have dealt with before, have search and if you find a library that solves your problem, use it. I wouldn't start with any libraries from the beginning unless you have a specific design problem in mind. Besides, you'll learn a lot (and hopefully have fun) by making everything from scratch :).

*Silverlight(Only) vs XNA*

XNA is a great framework for games and is supported by Windows Phone. I highly recommend having a crack at using XNA for your game. Windows Phone Mango supports using Silverlight and XNA together, so you have the best of both worlds. Again, have a look at the AppHub education catalog for examples.

*Whatever I should pay attention to*

Your game itself. If you come across problems, deal with them as they come. Optimise when you need to, not before. Finishing projects is hard and a problem a lot of people (myself as the worst offender) have. Great article on this here

Good luck. HTH

---
Tags: xna, architecture, windows-phone-7, puzzle
---


# Question
Title: How should we approach publishing our game from India?
Me and my friends are developing a game using Java for Windows operating system. We have nearly completed our game. As we feel that the game can make money, we wish to sell it. But in India we don't know any game publishing company. We want to know the following if possible. Will game publishers like BigFishGames.com publish our game even though we are not in USA? We are just students in college. Is it required that we can sell only after we start a company? Is it possible to sign contracts if the publisher wishes to publish our game, while the publisher and developer are in different countries? Thank you

# Answer
> 7 votes
As far as I know, its very hard for a beginner to find a publisher unless you have something, that really stands out of the crowd or something really convincing. So, your first choice should be online distributor. Most famous is Steam which of course has a higher entry margin. There are less restrictive distributors like Desura.

There is a new Indie only online game distributor emerging, called IndieCity. It hasn't been launched yet, but you can register as a developer and can have access to their api, sumbit game, go through the review system and so forth. It new so it will be relatively easy to have a place for a head start. There are other online distributors too. Google for more info.

You can also hook up your game profile in Indiedb. Its one of the largest Indie gaming portal.

About BigFish you should check out their FAQ.

Update : check these too, 10 alternatives of Steam

---
Tags: monetization, publishing
---


# Question
Title: In MMO game, how to handle user characters, who are offline?
In my medieval MMO game, players have their own character, that represents themselves inside game. Like a King. Players could have cities and armies, but King acts as main driving force.

Then it comes to player, going offline/vacation/disconnect. How to deal with "offline King", to keep some sort of reality in game, without ruining everything for player. I have never liked unrealistic stuff in games, like appearing/dissapearing from thin air, like in WoW or other MMO RPG's, when it comes to connect/disconnect, like in Matrix movie, when you are disconnected, your "avatar" inside the system just vaninshes.

Ok, if player char stays where it was left, other players who are online could kick his ass like offline player char was frozen? I see only one solution - give player char, while offline, some sort of AI, that controls char. Is there any other solutions? May be, some sort of legend/story, could make users only as inner-voice, leaving King just passively controlled by user, or other stuff... Please, help!

I hope you understand my question.

# Answer
> 7 votes
You have some basic possibilities:

**If the player disconnects, the character vanishes as well.**

Usually, you'd want this vanishing to *not* happen instantaneously. If players could just "pull the plug" whenever they are in a dangerous situation, they *will* do it and they *will* devise strategies to beat areas too hard for them by logging in and out like a madman.

Possible variations are:

* The character re-appears on the same spot as he was when the player logged out.
* The character re-appears in the nearest safe zone, the player or guild housing, or the camp site set up by his party beforehand.
* Some combination of the above, configurable by the player
* Some combination of the above, configurable by the area the player is in (instances and battlefields might send you back, regular XP spots not)
* The character is still barely visible, as a "ghost", for all nearby players.
* Buffs and debuffs on the character might expire, or they might still count - and even *kill* the character while offline.

**If the player disconnects, the character stays.**

This is dangerous by itself, since - especially with PvP on and full looting - there is much possibility for griefing and unfairness. After all, you can't always pick the time when your network goes down. Possible variations are:

* The character quickly runs back to the nearest safe place, camp site, player home or guild home, avoiding (or simply not drawing) any aggro. He can only die to other players.
* The character "ports away" to one of the above spots.
* The character becomes unkillable, but does not fight either.
* The character goes into (player-defined) "shop mode", where he behaves just like a regular NPC shop keeper, either respawning or being unkillable without any negative effects just like them.

For the "shop mode", you could allow the players to inspect and modify the contents of their shops (or other offered services) while not being logged into the game - for example, via a web site or an external API. Same goes for sending and receiving in-game mail.

---
Tags: ai, mmo, character
---


# Question
Title: How to implement an intelligent enemy in a shoot-em-up?
Imagine a very simple shoot-em-up, something we all know:

You're the player (green). Your movement is restricted to the `X` axis. Our enemy (or enemies) is at the top of the screen, his movement is also restricted to the `X` axis. The player fires bullets (yellow) at the enemy.

I'd like to implement an A.I. for the enemy that should be really good at avoiding the players bullets. My first idea was to divide the screen into discrete sections and assign weights to them:

There are two weights: The "bullet-weight" (grey) is the danger imposed by a bullet. The closer the bullet is to the enemy, the higher the "bullet-weight" (`0..1`, where 1 is highest danger). Lanes without a bullet have a weight of 0. The second weight is the "distance-weight" (lime-green). For every lane I add `0.2` movement cost (this value is kinda arbitrary now and could be tweaked).

Then I simply add the weights (white) and go to the lane with the lowest weight (red). But this approach has an obvious flaw, because it can easily miss local minima as the optimal place to go would be simply **between** two incoming bullets (as denoted with the white arrow).

So here's what I'm looking for:

* Should find a way through bullet-storm, even when there's no place that doesn't impose a threat of a bullet.
* Enemy can reliably dodge bullets by picking an optimal (or almost optimal) solution.
* Algorithm should be able to factor in bullet movement speed (as they might move with different velocities).
* Ways to tweak the algorithm so that different levels of difficulty can be applied (dumb to super-intelligent enemies).
* Algorithm should allow different goals, as the enemy doesn't only want to evade bullets, he should also be able to shoot the player. That means that positions where the enemy can fire at the player should be preferred when dodging bullets.

So how would you tackle this? Contrary to other games of this genre, I'd like to have only a few, but very "skilled" enemies instead of masses of dumb enemies.

# Answer
I think your basic idea is sound, but it is not analogue. You need an analogue field of value that runs across the screen. So, 1D diffusion gradient, from which you can derive a value at an exact point on that line, on the fly. Diffusion gradients are **cheap** and can be used by multiple enemies at once, as they describe the environment, and not the entity's view of it (a bit like radiosity lighting) -- probably why you've opted for the approach you have in your question. This gradient should be relatively smooth, so as to evoke organic movement from the enemy, and obviously updates as your gamestate does. Perhaps moving average?

The gradient should combine:

* Proximity
* Velocity
* Breadth of bullet
* (optionally) Position of targets (players)

For dodging, we have to be able to find a solution accurately *whenever a solution exists*. Such is the case whenever there is a gap small enough for the enemy to dodge through. That is, you can only do what you can do, so the gradient approach will work no worse than any other approach in this sense, I'd say.

The diffusion gradient should push the enemy towards local optima (being the peaks in the graph) with less imperative to move, the closer we are to a local minimum, hence a diminishing returns effect on dodging. This opens the door to more intelligent decision-making as to when the enemy has a good opening to fire.

If the need to fire is greater than the need to move, then do so; your code may also determine this *by how much* they differ. You can implement this as part of the base graph, in which case the player position reduces the surrounding values in the graph (assuming enemies gravitate to the lowest point), which combines all decision-making into one graph, or you can keep the "desire to fire" graph separate from the main "desire to dodge" graph, which will offer you more direct control.

IRL, I wouldn't bother dodging a projectile until it's within a distance which I know, at my top dodging speed, is starting to become difficult to avoid. First hand experience from throwing stones as a lad. A bullet at x distance travelling at velocity y has the same danger rating as a bullet at 2x distance travelling at 2y. So this needs to be factored in correctly.

Ways to tweak the algorithm for enemy difficulty include

* introducing a latency on updates to the graph (Born Too Slow)
* introducing random, localised innaccuracies into the graph
* simply not having enemies obey what the graph tells them, over a sequence of updates (say 1 to 10 frames) due to sheer AI laziness.

Again, you can either implement all the factors into one graph (less control, and less useful for multiple enemies), or into several graphs which you look at together to get the results (more modular, probably works better for multiple enemies). It's hard to be more specific, as there are a lot of directions you can take this approach.
> 8 votes

# Answer
This can be looked at as a pathing problem. Instead of thinking how the baddy avoids the bullets, imaging the bullets are static and the baddy must travel through them to the bottom of the screen.

```
    E
B  B**B
  B***B  B
 B***B   B
B**B** B
 B**B**BB
B*****B B
      P

```

E = enemy
B = bullet
P = player
* = path options to bottom of screen

Once the baddy has plotted a successful path it just needs to take the next step each time. There are probably already some good algorithms around for path finding such as this. If the baddy moves at the same speed as the bullets one example algorithm might be;

Start at the baddy and mark safe positions in empty spaces to the below left, directly below and below right. Then consider each safe space you have just created and repeat. If at any time you find there are no safe spaces below then mark the space as not safe and backtrack.
> 7 votes

---
Tags: algorithm, ai, shoot-em-up
---


title: Renderbuffer to GLSL shader?

text:
# Question
Title: Renderbuffer to GLSL shader?
I have a software that performs volume rendering through a raycasting approach. The actual raycasting shader writes the raycasted volume depth into a framebuffer object, through gl\_FragDepth, that I bind before calling the shader.

The problem I have is that I would like to use this depth in another shader that I call later on. I figured out that the only way to do that is to bind the framebuffer once the raycasting has finished, read the depthmap through something like `glReadPixels(0, 0, m_winSize.x , m_winSize.y, GL_DEPTH_COMPONENT, GL_FLOAT, pixels);` and write it to a 2D texture as usual `glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, m_winSize.x, m_winSize.y, 0, GL_DEPTH_COMPONENT, GL_FLOAT, pixels)` and then pass this 2D texture that contains a simple depth map to the other shader.

However, I am not entirely sure that what I do is the proper way to do this. Is there anyway to pass the framebuffer that I fill up in my raycasting shader to the other shader?

# Answer
> 4 votes
You should be able to create the depth buffer as a texture rather than a renderbuffer, and bind the texture directly to the FBO's depth attachment. It's the same way you'd do render-to-texture.

The way you're doing it now is definitely not efficient, since it's copying the depth buffer from VRAM to main memory, and then right back to VRAM. It also forces the CPU to stall waiting for the GPU to finish rendering before it can do these copies.

---
Tags: opengl, glsl, depth-buffer
---


title: rendering a reflection on a texture

text:
# Question
Title: rendering a reflection on a texture
I want to render reflection on a planar surface but the reflecting surface has a texture mapped onto it.Would the normal technique of using stencil buffer and then blending in the reflected image with the reflecting surface in this case? If not then could some one suggest me how to render reflection on a surface that has a texture mapped onto it? Thanks

# Answer
> 0 votes
Yes that should work as long as you use the proper blending technique.

---
Tags: graphics, reflection-rendering
---


# Question
Title: Better data structure for a game like Bubble Witch
I'm implementing a bubble-witch-like game (http://www.king.com/games/puzzle-games/bubble-witch/), and I was thinking on what's the better way to store the "bubbles" and to work with. I thought of using graphs, but that might be too complex for a trivial thing. Thought of a matrix, just like a tile map, but that might get too 'workaroundy'. I don't know.

I'll be doing in Flash/AS3, though.

Thanks. :)

# Answer
You may not want to use a graph, but ultimately the problem is one of planar 6-connectedness. I challenge you to find a simpler and better-suited structure than a graph for this :) I wouldn't be intimidated by the data structure for this -- when you consider how trivial the implementation will be, it's not like you'd be writing Boost Graph Library all over again.

```
class Bubble
{
   private static const NEIGHBOUR_TOP_LEFT:int = 0;
   private static const NEIGHBOUR_TOP_RIGHT:int = 1;
   private static const NEIGHBOUR_RIGHT:int = 2;
   //etc.

   var neighbours:Array = [];
}

```

...That's your graph data structure.

As for algorithms, in your main class, run through a loop that arrays them according to their connectivity. And when a player shot collides with the rest, join it at the closest grid position, and then walk all neighbours in the connected graph that match the player shot colour, adding these to a list to "pop", and disallowing walks over neighbours that are already in that list (prevents infinite loops from walking cycles of nodes).
> 6 votes

---
Tags: algorithm, matrix, data-structure, puzzle, graph
---


# Question
Title: What is the most secure way to archive a GKScore to be re-submitted later?
I'm looking for the safest way to archive and store a GKScore that needs to be re-submitted to Game Center (say, because the user didn't have a network connection at the time the score was earned). I would like to archive the GKScore instance in case the app is terminated before it can be successfully re-submitted to Game Center.

My worry is that if it's archived to an instance of NSData and saved in a .plist, it would be easy to manipulate. Perhaps this worry is unjustified?

NOTE: I posted a similar question on Stack Overflow only to realize that it's better asked here.

# Answer
> 1 votes
If you app is not hacked, user can only access the documents folder from iTunes. So, just save it as you do to the Library folder.

If user can't access the file, it will be no problem even if the data is archived as plain text.

# Answer
> 1 votes
I don't think there is any way around this because the real weak link is the connection to Game Center. I faced that same problem as you have, so I encrypted all data saved to the device while it waited to be uploaded, yet, 1 day after my App was released, the high score tables were filled with bogus scores. Obviously the data has to be un-encrypted before it's sent and my theory is that the information is intercepted at this point and altered, or people are just connecting to Game Center directly via computers and uploading whatever they want. Does anyone know what safeguards Apple does for this?

Even big name games like Angry Birds have this problem. I have yet to see any game that doesn't have it's high score tables filled with junk. I think that's one of the reasons that the "friends high scores" is more important to a lot of people. If your friend hacks the high score tables to beat your score you can just punch him.

If anyone has a fool-proof way to securely store and upload game center scores, I'd love to know it as well, although I don't think it's possible.

---
Tags: ios, objective-c, game-center
---


# Question
Title: Why am I seeing streak artifacts on the cube map I'm rendering?
I'm getting strange streaks on my cube map when rendering to it. He is my code that is being called each frame:

```
void drawCubeMap(void)
{

int face;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBindFramebuffer(GL_FRAMEBUFFER, fbo);
//glBindTexture(GL_TEXTURE_CUBE_MAP, cubeMapTexture);
//glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glViewport(0,0,sizeT, sizeT);

for (face = 0; face < 6; face++) {

   glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, cubeMapTexture, 0);
   drawSpheres();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glViewport(0,0,900, 900);
}

```

Any idea what it might be? The streaking occurs when I'm rotating the spheres around the main sphere.

# Answer
> 1 votes
Since you're rendering six images to the cube map, you should set the glClear and glClearColor inside of the loop, clearing it six times. In this case, the clear color should be black, so it keeps a black background.

The same principle applies to any dynamic environment mapping techniques you use, be it a cube map, dual paraboloid map, etc.

---
Tags: opengl, glsl
---


# Question
Title: Dynamically creating astar node map by triangular polygonal map
My game's map format uses a bunch of triangles to make up the platforms and terrain in 2d. Right now I can set up a 2d array of nodes for the A\* (A star) algorithm that basically is a bunch of rectangles across the maps x and y that can be set to "wall" if the A\* algorithm should try to go around it.

However I want a function in the map loader to create the node overlay if the nodes are not specified. I was thinking if more than n percent of the A\* rectangle overlaid on map was filled by polygons I could mark that entry in the array as "wall". However I'm stuck on how to do this (or even start) where/when the triangles can be overlapping and also of variable size.

# Answer
You're starting with an image, and trying to overlay pathfinding information onto that. Generally this would be approached in one of the following ways

* Create a background image, then use XML, JSON or some other file-based data format to create the metadata, by hand. This is trial and error, since you have to guess the positions and then test, guess and then test, ad nauseum.
* Create a background image, then use a custom tool to then array an A\* node map over this. If you can't find the tool, you'll need to make one. This is easier than writing this into a file as raw data, by hand. I would just put a different mode into the game engine that allows you to load a map and click to create and join up map nodes over this, and then save this out to file. This is ultimately why many games have editors built in, that you can access from the menu -- it was for the developers' convenience. This, in your case, is probably the most sensible approach.
* Generate image map at same time A\* graph; this is a purely procedural approach and only useful if you are generating only random levels. The idea here is that the topology (connectedness i.e. A\* map) of the level is generated, and then from that, the background image is generated. Of course, this takes control of the art out of the hands of developer and artists, to some degree.

You can try to do it procedurally, it's going to be substantially more difficult though. If you are adamant about going down this route, obviously your approach has to be based on pixel colours, and so you may need to generate a secondary image that is used purely for A\* pathing determination.
> 1 votes

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


# Question
Title: Options for 2D Web/iPhone/Android, with Test Framework
I would like to make a 2D game with one codebase that runs on iPhone, Android, and web (any flavour of web -- HTML5, Flash, Silverlight, etc.)

What are my options? I should be able to write my code once, and run it anywhere. I also absolutely need the ability to write unit tests (or write a unit-testing framework) -- I cannot make sizable games without testing.

Unity is good, but unity is 3d; even with hacks, the graphical assets will still be 3d. I'm after 2d, not 3d.

(If you need a Mac or separate licensing for the Mac part, that's okay.)

# Answer
> 2 votes
There really is no such thing as WORA (write once, run anywhere). Seriously. That's the big dream of HTML5, but due to the number of browser vendors even that dream will be tainted by the time it becomes realised in the larger sense. Tainted not just by functional differences (compositing is one extant example) but also by performance differences. In the meantime, these issues already exist.

For now, for a simple 2D game, you really still can't do much better than Flash/AS3. It has ASUnit, based on JUnit.

Java's another option, and while I love the language itself, Java deployment, particularly to the web, is depressing and was one of the reasons Java, which had all the potential Flash had and far, far more, never made it big on the web games scene. Also, Android uses Dalvik, which is a proprietary version of the JVM -- not really the same thing. So Android at least would be out of the picture, unless you ported your Java code across platforms... which is what you wish to avoid. ;) Java obviously has JUnit (*the* unit testing framework). If going for Java, check out PulpCore for a fast software renderer; the scene graph / display list approach they use is almost identical to using the AS3 core.

Silverlight's a joke in this sense, it's not even near universally cross-platform.

You can also check out SDL -- I believe it's not a half bad option in this regard. I'm using it but I haven't gotten as far as cross-platform deployment yet. However, writing cross-platform C/C++ code is not quite the same as a Flash or Unity codebase which is totally platform-agnostic, for those platforms it does support (most).

You can see why whenever this matter is brought up, people suggest Unity. The fact is, it's probably the most cross-platform solution out there, being even better in that regard than Flash (iOS).

# Answer
> 1 votes
Try Adobe Air. With the end of mobile Flash, Adobe recommends to use it. With Adobe Air, you can develop standalone apps for many platforms (Android, iOS, BB, ...). I'm not a great fan because of performance...

Pro:

* Cross Platform
* It's Flash

Con:

* Your standalone app asks to install Air
* Performance (It's flash)

Exemple of game using Air: Dillo Hills

http://www.adobe.com//products/air.html

Ps: i don't use it.

# Answer
> 0 votes
Exen is not bad. It uses XNA, so it deploys to web (Silverlight), iPhone (MonoTouch), and Android (MonoDroid) -- albeit that you require a $400 for each of (MonoDroid, MonoTouch).

Unity runs the same price, and also supports all three platforms; but it doesn't support 2D too well.

# Answer
> 0 votes
You should try Corona SDK, it is amazingly simple to use LUA but that would only be to fulfill your urge to program on mobile devices. You can program it in html5 plus javascript and theoretically it could run on all platforms, but personally doing games in HTML5 + javascript using the canvas element doesnt sound fun at all

# Answer
> 0 votes
Have you tried PlayN? It's a cross-platform library that compiles to Flash/HTML5 (web), and Android; iPhone is in the works. I haven't used it, but it looks promising. (Be warned that the Android bindings are also very new.)

---
Tags: cross-platform
---


# Question
Title: 3DS Max 2012 OBJ file import missing polygons
I started learning OpenGL. I got to a point I want to import some "real" objects. After "Googling" I decided I will go with OBJ file for start, since it is simple to understand, and there are plenty of tutorials on how to read them properly.

I have from university access to 3DS Max 2012. So I tried to create very simple model (just deformated cube) and exporting it using OBJ file, just to vertices and triangles for the moment, without textures, so I can examine its structure by myself. But if I imported it right back to 3DS from OBJ file, now it renders somewhat strange, like its smoothen, and with lightsource, even I have none in scene. But the geometry, its wireframe is intact.

So I thought maybe it is problem of exporting only vertices and triangles so I downloaded Enterprise-D model from internet, exported with everything on (normals, textures everything), and again imported it. Now, some polygons are missing.

So, I want to ask, am I doing something terribly wrong, or is there some incompatibility issue between .max and .obj file ? Even it is only simple textured model without any lightsources, animation etc.? Thanks.

Edit: I tried objects with MeshLab, the first, deformated cube was absolutelly OK. But still bothers me that 3DS Max doesen´t render it properly. In Enterprise-D model, there are polygons missing even in MeshLab. I uploaded rar archive with .max model of Enterprise, same .obj model exported from 3DS, and obj model of deformated cube. Download here (2.5 MB, filesonic).

# Answer
> 0 votes
The first problem you described sounds like the normals getting smoothed. I notice your Test.obj file was exported without normals; when it was re-imported, 3DS would auto-generate normals for it and probably assumed they were to be smooth. In this case exporting with normals should fix the problem.

As for the Enterprise model, I opened it in Maya and saw some odd-looking, possibly malformed faces on the bottom, but no actual holes that I could find. Are you sure the problem is not with the original model?

---
Tags: opengl, 3dsmax, obj
---


# Question
Title: What are the GPU requirements for XNA 4.0?
I tried to build a sample application using XNA, but I got an error saying that Pixel Shader 1.1 was required, so I got a used Radeon X300 GPU that supports Pixel Shader.
I tried to build it again, but I got another error saying that "Your current graphics card does not support the XNA HiDef profile" and would not build.

Since that card seems to not be compatible, I guess I need to buy another one. What features should I look for to make sure that it's compatible with XNA?

# Answer
> 4 votes
You need a DirectX 10 compatible GPU for running `HiDef` XNA games. Just change your project settings to `Reach` or get a compatible graphics card.

You can find more info on the differences between HiDef and Reach on this post from Shawn Hargreaves.

---
Tags: 3d, xna-4.0, directx9, compatibility
---


# Question
Title: In a 2D tile-based game, how should NPCs and tiles reference each other?
I'm making a tile engine for top-down 2D games. Basically the world is composed of a grid of tiles.

Now I want to put for instance NPCs that can move on the map.

What do you think is best:

1. each tile has a pointer to the NPC that is on its tile, or a NULL pointer
2. having a list of NPCs, and they have the coordinates of the tile they are on.
3. something else?

I think

1. is faster for collision detection but it would use much more memory space and it is slower to find all NPCs in a map.
2. is the opposite.

# Answer
> 11 votes
Why not both? There are times when you'll want to look to see if there's any NPC on a specific tile (such as for collision detection, as you mentioned), and other times when you'll want to iterate over all the NPCs in the world (such as for running their AI methods every frame).

A pointer per tile is not that much memory unless you're working on a memory-constrained platform or you have a *really* huge map.

# Answer
> 0 votes
How do you handle collisions with the map? If you have a collision layer, a very easy way would be to first create a list of NPCs with coordinates indicating on which tile they are on and then iterating through that list and marking the collision layer tile under the NPC as a collision tile. That way, the collisions against NPCs would be handled at the same time as rest of the map. That is, of course, if the NPCs don't move...

---
Tags: tiles, data-structure
---