# Question
Title: Level editor event system, how to translate event to game action
I've been busy trying to create a level editor for a tile based game i'm working on. It's all going pretty fine, the only thing i'm having trouble with is creating a simple event system.

Let's say the player steps on a particulair tile that had the action "teleport" assigned to it in the editor. The teleport string is saved in the tile object as a variable. When creating the tilegrid an actionmanager class scans the action variable and assigns actions to the variable.

```
    public static class ActionManager
{

    public static function ParseTileAction(tile:Tile) {

        switch(tile.action) {

            case "TELEPORT":

            //assign action here

            break;
        }

    }

}

```

Now this is an collision event, so I guess I should also provide an object to colide with the tile. But what if it would have to count for collision with all objects in the world? Also, checking for collisions in the actionmanager class doesn't seem very efficient.

Am I even on the right track here? I'm new to game design so I could be completly off track. Any tips on how handeling and creating events using an editor is usually done would be great. The main problem i'm having is and efficient way to read out and react to the given actions in the editor.

Thanks in advance.

# Answer
> 1 votes
I'm not really familiar with action script, but it looks pretty familiar to C# and I think I understand your question/dilemma.

It might be beneficial to have certain triggers (like when a player steps on the tile or when anything steps on the tile). These triggers could be part of a tile or possibly part of a map.

Then you assign actions to do to when these triggers fire/occur.

Basically, this event system is split into two parts. One part (the trigger) alerts the action to be executed. The second part actually executes the action and possibly checks for extra conditions.

If you did this then your map editor would be able to assign triggers to a tile (or a map). Then you could specify an action to execute for that specific trigger. So your trigger for the teleport tile would do the collision check (or hook into some physics/collision system in order to be notified when a collision occurred with the tile) and then fire off the teleport action.

PS: I would consider having the action being specified with more than just a string (or at least a string that can also have arguments in it). How would you specify where that tile teleports the player if the string has to be "TELEPORT". Just some food for thought.

Also, part of your question (near the end) seems to be missing? "The main problem i'm having is the \[missing part?\]"

# Answer
> 0 votes
Action/Result is a function of a bunch of variables e.g. f(x,y,z ... )

First, establish what the x, y, z etc are and then what the resulting action will be. Think of x, y, z as tile (its position, state etc.), current level, current environment variables etc. Then decide who will act on the action. Will it be the tile or a controller OR both? Once you have answered the first two questions, you will know what variables/values you need to send back to the tile or send to a controller.

# Answer
> 0 votes
In your map there should be "Zones"/"Triggers". In my game my triggers have an action field, and a parameter field specifying how the action should be done.

Example: The player, when entering a teleporter-trigger, should only teleport when there is a button activated. The condition should be tested inside the engine. Your trigger could look like this: Type: Trigger Region: ... Action: Teleport Conditions: Button1.Active == true Parameter: 100, 200 (the target coordinates)

Your game should therefore have condition functions, and Actions (with parameters). That's the exact way it's handled in all major games. Warcraft3 engine, the SourceEngine, Unreal engine... Warcraft3 being a perfect example. Its script editor consists of Events, Conditions and Actions. Look it up, maybe you can get inspiration from it.

Tip: I don't know the abilitys of actionscript but try to parse the level data into static arrays. the iterate over them every frame to see if anything is triggered. In my game there is also a field that describes how often this entitys logic should be updated.

Ask if anything's unclear, I'm happy if I can help.

# Answer
> 0 votes
The trick to this is really just finding a way to balance the amount of data parsing and hard-coded behavior. I'm sure that a teleporter is not the only type of behavior you'd like to add to your tile. Ideally you'll be able to add new behaviors quickly, and have an obvious way for describing them in a data format.

You didn't provide a lot of details on your tile class, so I'm gonna make some crap up. Let's assume you have some sort of base `GameObject` class, which has some basic variables like position and group. I'm assuming `GameObject`s are things that are generally dynamic in your game. Things like static scenery wouldn't fall under this category. `Group` is just something I tacked on to illustrate the effect of checking for just the player, all NPCs, etc.

```
public class GameObject {
    public static const PLAYER_ONLY:int = 1;
    public static const ALL_CHARACTERS:int = 2;
    public static const ALL_ENEMIES:int = 3;
    public static const ALL_FRIENDLY_NPCS:int = 4;
    public static const INTERACTABLES:int = 42;
    public static const BLOCKS:int  = 99;
    public static const TREASURE_CHESTS:int = 20384293;

    public var Group:int;
    // assuming you have some Point class encapsulating X/Y coordinates
    public var position:Point;
}

```

Now for a tile class. I'm using a library called as3signals (alternative library: TurboSignals). It basically allows you to create C#-style delegates to get around the hassle of having to use Flash's standard event system with strings and EventDispatcher. You can accomplish the same thing using the EventDispatcher method, but it's much less sexy.

The way it works is you have fields in your class that are of type Signal. Each signal has an add() function, which behaves like eventDispatcher.addEventListener, except that the listener you are adding is for *that* specific signal, and nothing else. It makes your events type-safe, so it's good for events where you know you will absolutely need them, such as OnObjectEnter and OnObjectLeave. Sure, you don't get the flexibility of arbitrarily defining event string literals to shoot out into the ether, but these things are pretty easy to use. And nothing stops you from using EventDispatcher in conjunction with signals.

One thing that's nice about as3signals is you can define the type of argument that you send with the dispatch. In the case of the Tile, it will send a GameObject parameter, so that whoever is interested in the event will know *which* game object entered the tile.

I just created two signal slots: `OnObjectEnter` and `OnObjectLeave`. These serve to notify other objects when a `GameObject` has entered/left the tile. This is what we will use to implement the teleporter.

```
public class Tile {
    // Useful to know when GameObjects enter and leave this tile
    public var OnObjectLeave:Signal = new Signal(GameObject);
    public var OnObjectEnter:Signal = new Signal(GameObject);
    public var position:Point;

    // Use Vector.<T>s, they're faster than plain Arrays
    private var properties:Vector.<TileProperty> = new Vector.<TileProperty>();

    public function addProperty(property:TileProperty):void {
        properties.push(property);
        property.attachToTile(this); // Because we have no double dispatch :(
    }

    public function Update(deltaTime:Number):void {
    // This update function is kinda dumb, it just serves the purpose of
    // having a starting point for reacting to an object entering the tile
        if (someIndicationThatThisTileWasEntered) {
            OnObjectEnter.dispatch(getObjectThatJustEntered());
        }

        if (someIndicationThatThisTileWasLeft) {
            OnObjectLeave.dispatch(getObjectThatJustLeft());
        }

        for (var property in Properties) {
            if (property.NeedsUpdating) {
                property.Update(deltaTime);
            }
        }
    }
}

```

You'll also see the properties field in there, a vector of `TileProperty`s. If you want to code special behavior and be able to duplicate it in multiple areas (such as a teleportation behavior), then you subclass this. It provides an overridable `Update(deltaTime)` function, information about the parent tile and an overridable function that notifies you when the parent changes (good for object pools), and a bool for toggling whether it gets `Update()` called on it every frame or not.

I put an update function in the Tile, but it's really just to have some point in this example where you can follow the chain of collision detection -\> trigger teleportation. In a real game I would leave the responsibility of firing the signals to some larger collision system class.

```
public class TileProperty {
    public var NeedsUpdating:Boolean;

    private var parentTile:Tile;
    protected function get ParentTile():Tile { return parentTile; }

    public final function attachToTile(tile:Tile):void {
        var oldTile:Tile = parentTile;
        parentTile = tile;
        onNewParent(oldTile);
    }

    protected function onNewParent():void {
        // Override this
    }

    public function Update(deltaTime:Number):void {
        // Override this
    }
}

```

So now we've got a TeleportTriggerProperty class, and this is where the teleportation actually happens. When OnNewParent() is called, it adds a listener (`teleportObject`) to the OnObjectEnter signal. That way, whenever an object enters the tile that this TileProperty is attached to, it can teleport that object.

```
public class TeleportTriggerProperty extends TileProperty {
    private finalDestination:Point;

    public function TeleportTriggerProperty(destination:Point, group:int) {
        finalDestination = destination;
    }

    override protected function OnNewParent(oldTile:Tile):void {
        // I'm not sure if trying to remove a null listener, or
        //   a non-existent listener throws exceptions
        // If it does, then wrap it in try-catch.
        // Or better yet, modify the library so it DOESN'T :P
        oldTile.OnObjectEnter.remove(teleportObject);
        parentTile.OnObjectEnter.add(teleportObject);
    }

    private function teleportObject(thing:GameObject):void {
        // Maybe in some scenario this OnObjectEnter could get called if a
        //   chest gets placed on the tile, so it's good to confirm the Group.
        // And maybe you want to be able to configure it to only teleport
        //   the player, or only enemies.
        if (thing.Group == GameObject.ALL_CHARACTERS) {
            // BAM! Teleported. Insert special effects as necessary.
            thing.position = finalDestination;
        }
    }
}

```

So now you've got all this infrastructure. How does this apply to the level editor?

Well, notice that really the only thing that a TeleportTriggerProperty needs to work is a Point and a Group ID. These are the two fields that you can expose in your level editor. Then you can presumably export your level structure in XML or some other data format to look like this (I used XML, since its hierarchical nature makes sense in this scenario, and as3 parses it natively):

```
<Tile>
    <Position>24,42</Position>
    <Properties>
        <TeleportTriggerProperty destination="42,24" group="2" />
        <TriggerMusicProperty track="NeverGonnaGiveYouUp.mp3" />
        <BrutallyMurderPlayerInFutureProperty time="3m30s" />
    </Properties>
</Tile>

```

It probably isn't ideal to store a big XML hierarchy for each and every tile in your game, but this was the most straightforward example I could think of.

Then in your parser routine, you could iterate through and construct your TileProperties as needed. You could conceivably automate this process with serialization. I haven't done serialization in as3 though, so that's homework for you if you're interested. If you don't use serialization, I'd recommend having a few separate classes responsible for parsing specific types of elements (a GameObject parser, a Tile parser, and maybe even a separate TileProperty parser).

I called this thing a `TileProperty` in the hopes that it could possibly accomodate both direct actions like your teleporter problem, or tile effects, such as diminishing the health of whatever character stands on it every few seconds. But, it may be better to implement a couple different systems to get done what you want to. It depends on your game.

---
Tags: actionscript-3, events, map-editor
---


# Question
Title: Is there a design flaw when an entity's state doesn't fully utilize enter(), execute() and exit()?
I'm following Mat Buckland's Programming Game AI by Example, and I find that I don't always have use for enter(), execute() and exit() on an entity's state. For example, in an RPG, a weapon may have an equipped state, and I may use enter() and exit() for that state to add or subtract to a player's ability modifier, but there isn't really a need for execute(). Is this a design flaw in my engine, or a shortcoming of this approach?

# Answer
> 8 votes
Not having read the book, those calls sound like normal entry points for a state machine. To understand the calls, let's look at what they do.

**enter()** \- executed when the state is activated.

**execute()** \- executed *while* the state is activated.

**exit()** \- executed when the state is deactivated.

These fit any kind of state machine. Some machines only need the 'execute' calls, others need the 'enter' and 'exit', and still others need all the three.

**Example 1**: Machine gun trigger.

* Execute: fire bullets at set rate.

**Example 2**: Force bridge

* Enter: make bridge appear
* Exit: make bridge disappear

**Example 3**: Personal power armor.

* Enter: give player extra protection
* Execute: drain batteries
* Exit: remove extra protection

# Answer
> 8 votes
It's not necessarily a sign of any flaw. Not every entity or state will have a use for every available method. Just leaving the execute() method empty would be fine, IMO.

---
Tags: ai, game-mechanics, state
---


# Question
Title: How to write AI bots that can autoplay a shoot 'em up game?
In a shoot 'em up game I want to have AI bots that can take up the player's slot and play the game (such as in this video). However they should come with different flavors (varying competency and playstyles). The problem is the related maths and AI programming are very new to me. Where should I start?

Suggestions for existing sample code/libraries/tools, reading materials or advice on architecture/algorithms are all welcome. Thanks in advance!

# Answer
Let's assume you have to write something yourself. I don't know of any middleware targeted towards 2D side-scrollers but someone may correct me.

I haven't done anything like this before, but it's an interesting intellectual exercise so here's my first thoughts. For simplicity I've talked about only avoiding bullets, not shooting at enemies.

Most side-scrollers are deterministic as to when enemies come on screen, their on-screen path and the bullets they produce. Players tend to learn how to play a level through muscle memory, which is strengthened by repetition, but at an immediate level they're reacting to what's on-screen now.

Of course we could just record human input and replay it (with several different recordings for different play-styles), but that's extremely sensitive to level design changes.

A simple steering-behaviour system could keep the AI away from bullets, maybe peeking at the type of bullet to figure out its future positions for predictive avoidance. For lots of bullets on small systems this may become expensive.

However with this approach the AI could very quickly get stuck in a dead end, with no chance of escape. So we need something above the on-screen reactions, something to replicate the muscle-memory humans use.

If we could get our AI to repeatedly play each level, recording some kind of data as it goes, it could pipe this data into the steering behaviours to avoid dead-ends. Each play-through improves the data and lets our AI make better decisions. But what form does this data take?

One immediate idea is a heat or threat map covering the whole screen, for every frame of the level. Sort of a threat movie. You could imagine it as a movie of the level, with each pixel coloured as to its danger to the AI. Spaces completely enveloped by bullets would be coloured in as very dangerous. Then you could do some post-processing to bleed danger back though time, so the AI could see the problem coming before the area is enveloped.

With this data, you could replace the steering behaviours with a kind of 4-dimensional flood-fill that tried to find the largest safest place on the screen, with each step looking at the future frames to work out a safe path.

If a pixel for every frame for every level sounds data-intensive, you could make the pixels quite blocky - I imagine you don't need resolution below the size of the hitbox of the AI's avatar, and could probably get away with blocks a bit bigger than that. You could also record only two or three frames a second to further reduce data size.

The personalities come from the real-time processing of the threat movie. With steering behaviours, you could have scardy-cat AI that prefer large distances to any threat, or bravado AI that look for pickups despite the danger. Slow AI, that flood-fill the threat movie assuming a lower top speed, which may find different routes to a faster AI, etc.

If it sounds like a lot of work, that's because it probably is, but it also sounds like a lot of fun. :)
> 7 votes

# Answer
I assume these are AI bots that would be utilizing a game/engine you wrote. If not, then you would need to consult specific material related to the engine you use.

I picked up a copy of Game Coding Complete and was able to implement the various systems that are key in having working AI. It did a great job of explaining that the AI used to control computer players is simply an extension of the class used to control your own player. It also showed how to implement an event handler.

No, it won't detail an award winning AI language but it shows you what you need to create one. As far as libraries, I am not sure about them but again if you are just learning, try and shy away from libraries controlling things you are really interested in. For example, I love graphics rendering so I used no libraries at all when learning. Sound control is not something I am too interested in so I ended up going with a third party library.

Finally, Stanford is hosting an online AI class. I am not sure if you can still enroll but if you can it would definitely be worth your time. http://www.ai-class.com/

Even if enrollment is closed it may still be worth your time to e-mail the professor and let him know how eager you are to learn. This would most likely not be a class about the systems of AI but more about how to create AI that is lifelike and convincing.

Hope my answer helped!

http://www.amazon.com/Game-Coding-Complete-Third-McShaffry/dp/1584506806
> 3 votes

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


title: How to handle a huge map?

text:
# Question
Title: How to handle a huge map?
Generically speaking, how would you handle a huge 2D Map of which only a part is displayed? Imagine the old top-down racing games like Micro Machines.

I would know how to do something with a tile-based map, but I want to create completely custom Maps.

Target Devices are iOS, Windows Phone 7, Android, Mac and PC.

Assume the Map is too big to fit to fit into a single Texture. Would I have multiple textures, 4096x4096 each and load them all into RAM? Seems wasteful, and if textures are uncompressed I might actually run out of graphics memory.

Would I only load the max. 4 Textures that I need at any given point (when I'm at the intersection)?

Or would I have one huge image file and load parts of it? In that case, are there any image formats that make it easy (O(1)) to find the file offset and length which I would have to load?

Or is there a completely different algorhithm? Are textures the wrong idea?

How would you implement a game like Micro Machines?

# Answer
In a map that is built from tiles, I have given a fairly full explanation of the approach I've found to work best down on the low end devices:

How should I represent a tile in OpenGL-es

Memory is the memory used by the tiles (not how many times they are reused) and the relatively small amount of memory used to index where to place each tile.

Maps like Terraria are entirely possible!
> 3 votes

# Answer
If you're not making use of tiles, but draw your entire map by hand, just split it into pieces - or tiles (-8

You need to experiment a bit with tile sizes,to balance constant loading/unloading of tiles (when tiles are small) and using more memory (when tiles are large). For example, on iPhone4 with 960x640 resolution, you may use 1024x1024 tiles and have no more than 4 of them loaded at any given moment. Or have 9 512x512 tiles, arranged in a 3x3 grid.
> 4 votes

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


# Question
Title: is it possible to use c# GUI toolbox in an XNA app?
I need both reach GUI features of c# toolboxes and fast rendering features of XNA, is there any way to merge these two into one app? or is there any other way? for example some equivalent to c# toolbox in xna?

# Answer
> 4 votes
I assume you are referring to Windows Forms when you talk about "GUI toolbox". There are two samples available in the App Hub to mix XNA rendering with standard controls:

*(but you lose Xbox360/Win7 Phone/Zune compatibility)*

If you are looking for a GUI library for XNA, take a look at this post from Stack Exchange.

# Answer
> 1 votes
Also check out Awesomium. It's an in-game webpage rendering engine based on the Chromium browser (i.e. Google Chrome). You can use HTML/CSS/JavaScript to build your UI widgets that can communicate with your code. If you know a little bit of web design it's a great choice. Might be overkill depending on your project though.

Here's a couple of video showcasing XNA + Awesomium:

http://www.youtube.com/watch?v=k5mCWkGXoBs

http://www.youtube.com/watch?v=4PDyAoKAfxk

# Answer
> 0 votes
If you are programming for Windows Phone 7, the new Mango update of the OS adds support for XNA games inside a Silverlight application. This way you can create the menus and GUI in Silverlight, and lauch the game inside a frame. It is expected that Microsoft will sometime soon implement this feature on the PC and Xbox360 versions of XNA, but there's nothing official so far.

Check this article: XNA for Silverlight developers

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


# Question
Title: How can I create a lighting engine for BSP geometry in OpenGL?
I am trying to figure out the best way to go about creating a lighting engine for an old game format with BSP based geometry. I have all the relevant information about the light, R/G/B/brightness/radius all that sort. I want to go for per pixel lighting. How can I go about doing this? I have seen tutorials for simple examples like one light revolving around an object but wondered if the same concept applies when having numerous lights illuminating a level.

Also, the BSP geometry does not use lightmaps so that is out of the question.

Also, I am interested in using normal/specular and diffuse maps I generate with Crazybump if that helps influence your advice.

# Answer
Your main problem is shadows and occlusion. It's simply not enough to light for example an old Quake-level with the trivial point-light-on-polygon model no matter if it's forward or deferred shader (the latter is just an optimization). It works fine for approximately convex objects within the scene, but the interior itself is usually highly concave and filled with occluders.

There is a reason many games including the old BSP-games use pre-computed lightmaps - because then you can raycast every point on every lightmap to every light in the vicinity and get perfect shadows, and you can add a costly radiosity-pass which is also needed to get good realism..

Better then is to do shadow volume rendering but this is indeed costly to do for the static lighting of an entire BSP level - you might have multiple point-lights on every section of every wall! Also it does not handle radiosity. On the other hand, the geometry is very simple in the old BSP-games and renders extremely fast as a shadow volume so it might just work.

A combination of the two is probably most common - you precompute either 2D lightmaps or 3D lightmaps for the static or almost-static lights, then for a few dynamic lights you can use some simple non-shadowing point-lights or shadow volume rendering top of this.. and if you're feeling lucky, you can add some realtime radiosity algorithms like CryEngine3's light volume propagation on top of this.
> 1 votes

# Answer
I'm assuming you want to do *dynamic* lighting (rather than, say, baking your own lightmaps).

There are plenty of tutorials out there on dynamic per-pixel lighting using normal maps in OpenGL. I've got some on my website; they're a few years out of date, but might still be useful.

The tutorials there use forward shading, which means that you draw the scene geometry and evaluate all the textures and lighting equation in one pixel shader. If you need multiple lights, you have to re-render the scene geometry multiple times, combining them together with additive blending (you also have to include ambient light somewhere along the line). This is relatively easy and quick to code, but can become too expensive for complex levels with lots of geometry and lights. You'll definitely want to use a culling system to get rid of geometry and lights that aren't needed based on what the camera can see in a given frame.

Forward shading can also become cumbersome if you have many different kinds of materials requiring different shading equations (not just different textures), and many different kinds of lights (point, spot, etc.), because every combination of material type and light type requires its own shader.

In cases where forward shading is too expensive or cumbersome, there is another approach called "deferred shading" that has become very popular recently. You can read all about it online, so I won't explain it in detail here; I'll just say that it can be more efficient if you have highly complex scene geometry and/or large numbers of lights on-screen at once, and it often reduces the number of shaders you have to write. However, it's a more complex system and will be trickier to code, and take longer to implement and debug.

Since you said this is an old game I'd guess forward shading may work well enough for you, as the geometry and lighting are likely not that complex by modern standards. Just be aware that deferred shading is a viable alternative.
> 0 votes

---
Tags: lighting, binary-space-partitioning
---


# Question
Title: Can Flash games packed for iOS and other mobile devices achieve reasonable performance?
I was thinking of developing a game in Flash, as a hobby/educational project.

However, I was hoping I could make it run on a smartphone, but a friend who develops in Flash says that in their experience things will move really slow on the likes of an iPad when the Flash packager is used. So slowly that you can't use it commercially for fast-moving games.

Has anyone else experienced this slowness? Is there a way around it or is the technology just not there yet?

# Answer
> 6 votes
I'm currently using Flash to prototype a game for iOS and performance is decent. It's nowhere near the speed of a native implementation and is also slower than flash running on the desktop. But that's what has to be expected...

The term "commercial" doesn't indicate how much load your game will put on the CPU. Also "fast-moving" isn't a problem if your logic is simple and you're not overly excessive with graphics and animations.

Since flash code all runs on the CPU (unless you make use of the new 3D APIs), you're limited to what the CPU at hand can offer and this is *much* less than any modern desktop CPU. If you design your game in a way that respects these constraints, I see no problem in a Flash game on a mobile device.

# Answer
> 6 votes
I use Flash to build game prototypes, and you can get some great performance out of the packager, but you have to be aware of certain things. First off, it might be tempting to think that an iOS device is just a slower version of a PC. You might think that if you make your code run fast on a desktop, then it'll run decently on iOS. And nothing could be further from the truth.

The biggest difference is on the desktop, when running flash, your actionscript is being JIT-compiled. Its being dynamically interpreted by the flash player and executed. When you are talking about flash, the actionscript is getting precompiled and executed. Its like the difference between optimizing Ruby vs C++. Understanding that your actionscript is going to be compiled down to the iOS instruction set and not interpreted on the fly means that performance bottlenecks and bugs will be different (sometimes very different) between deployment platforms.

A couple quick things that I've noticed:

* Instantiating objects is painful, and slower than you might think. If at all possible use an object pool to reuse existing objects.
* Combined with the last one, garbage collection is painful and non-deterministic.
* Events are slow. Every time you dispatch an event you have have create a new instance, and then flash has a lot of overhead to capture and bubble that event around. Prefer simple callbacks (or even function objects) for simple event rasing.
* Related to the last, only have one listener bound to Event.ENTER\_FRAME. Have a centralized scene manager and takes care calling an `update()` method on children. It may sounds like you are reimplementing the native flash display stack (which you are), but like mentioned the last point you are incurring a lot of overhead.
* Prefer bitmaps over vectors. Vectors are drawn by the CPU, so every render frame the vector has to be redrawn... from scratch. Bitmaps (with the `cacheAsBitmap` property) can be differed to the GPU.
* Optimize your bitmaps for the device. If you are making an iPhone targeted game, dont make a character sprite sheet that is 256x256 pixels big if the character is only going to be 64x64 on the screen.
* Learn to use `cacheAsBitmapMatrix`. You can get a pretty decent performance boost using bitmaps and using this matrix for rotation and scaling over the simple `rotation`. `scaleX` and `scaleY` properties. In fact I would say, even if you aren't using `cacheAsBitmapMatrix` still prefer `.transform.matrix` for moving stuff around. If you are mathematically minded at all, then this will make your life so much easier.
* Understand how bitmaps, filters, and cacheAsBitmap works in flash. Understand how they effect memory usage.
* Prefer strongly typed variables over dynamically typed variables: `var x:uint = 0`. Also mark your classes as `final` if you aren't going to subclass it. There is a little performance boost for that.
* Get Flash Builder 4.5 Pro over Flash CS5.5. Flash Builder (even as an Eclipse plugin/extension) is way more suited for this style of development, and its memory and cpu profiler is one of the best, and well worth the investment.
* Lastly, watch this slideshow by grant skinner. Its probably one of the best over all references on ActionScript optimization. But pay close attention to the first few screens where he says "***optimization without benchmarking is pointless***". I cannot stress that enough. Learn to deploy your game and app to the device and get some instrumentation off of it. Benchmark it and see where you need to optimize before optimization.

But with all that said, iOS apps built by the flash compiler aren't inherently slow. But they are very different.

I haven't had a chance to get my hands on a flash 11 compiler for iOS, so I have no idea what the new molehill api will look like on an iOS device, or what other internal compiler optimization they have done between releases. But it will probably be an improvement.

# Answer
> 2 votes
Molehill is right around the corner... So until Flash Player 11 comes out as bummzack stated things will be very slow assuming what you are doing has a lot of moving parts. If you are making something rather simple, REALLY simple then you should be fine. Also there is always Elips Studio as well, they have emulated the Flex SDK so you can build your apps in their flavor of mxml and as3 and it compiles down to native code... So it runs very smooth and very fast! The SDK is free now and you will feel just like you were coding in Flash Builder.

# Answer
> -1 votes
You can develop small games in Flash that does not do much of processing and run it smoothly on your device. But since Flash utilises the CPU and not the GPU, you cannot expect much of fluidity in your app that uses lot of artwork and does a good amount of processing. But it looks like Flash Player 11, which is said to utilise the GPU, will do the trick of running such applications without a glitch.

---
Tags: flash, performance, platform
---


title: Increasing resolution of a texture?

text:
# Question
Title: Increasing resolution of a texture?
I'm doing some experiments on my own to improve my general skills with HLSL and so forth. In other words, I'm not doing any serious game development, but only looking to expand my knowledge within the field.

I'm trying to figure out how I can increase the resolution of a texture, and multiply it X amount of times.

Consider the following low-resolution picture:

A typical scenario for me would be to scale up this picture 3 times in the shader without interpolation, and draw the new result:

I've been experimenting with a shader that transfers the small picture on to a texture as a variable on the shader. I got that far. Now I just need it to take that texture using tex2D or something else, and scale it up.

How would I do that?

# Answer
It depends because it's not clear whether you want to scale the texture (which would be scaling the UV coords as @Jari said) or if you want to scale the underlying geometry.

For example, you may want to display a square with a texture, such as sprite rendering, then for scaling the sprite you wouldn't be scaling the texture coordinates but the vertex positions themselves. In this case, transforming the texture coordinates will make your texture wrap or truncate according to the relative mapping to the vertices and won't match the underlying geometry.

Anyway, for transforming the texture coordinates alone you can do it simply by scaling the texture coordinates of the vertices (the UV mapping), like this:

```
uniform extern float2 gScale;

OutputVS Vertex( float3 posL : POSITION0, float2 tex0 : TEXCOORD0 )
{
    OutputVS ovs    = (OutputVS)0;
    ovs.tex0.x  = tex0.x*gScale.x;
    ovs.tex0.y  = tex0.y*gScale.y;
    ovs.posH    = mul( float4( posL, 1.0f ), gWVP );
    return ovs;
}

```

The tex2D comes later with the pixel shader, but by then you already have the scaled coordinates, so you don't need to do anything else other than get the colors as `float4 texColor = tex2D(SampS0, tex0).rgba;` or something like that.
> 3 votes

---
Tags: xna, hlsl
---


title: Basic 2D game collision

text:
# Question
Title: Basic 2D game collision
I've been trying to program a game for the past while and I can't ever figure out one thing: collision detection. I can get up+down and left+right to work, but when I put them together, they interfere with each other.

I seriously don't really know how to do it, and I don't want to have to use Box2D or any other premade collision detection system. All I need is something simple and will work in 4 directions.

Here's the code I have now from my Player class:

```
for (int i = 0; i < blocks.size(); i++) {
            Block b = blocks.get(i);

            if (isCollidingDown(b)) {
                b.doTopCollision(this);
            }

            else if (isCollidingUp(b)) {
                b.doBottomCollision(this);
            }

            else if (isCollidingLeft(b)) {
                b.doRightCollision(this);
            }

            else if (isCollidingRight(b)) {
                b.doLeftCollision(this);
            }

        }

```

Here's the actual detection code. I know it's long, but just roll with it:

```
public boolean isCollidingDown(Block b) {
        if ((Float.compare(this.yPos,b.yPos+b.height) <= 0) && (Float.compare(this.yPos,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)>=0)) {

            if (((Float.compare(this.xPos, b.xPos)>=0) && (Float.compare(this.xPos, b.xPos+b.width)<= 0)) ||
                    ((Float.compare(this.xPos+this.width,b.xPos)>=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0))) {

                    return true;

            }
        }
        return false;
    }

    public boolean isCollidingUp(Block b) {
        if ((Float.compare(this.yPos+this.height,b.yPos) >=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0) && (Float.compare(this.yPos,b.yPos)<=0)) {

            if (((Float.compare(this.xPos, b.xPos)>=0) && (Float.compare(this.xPos, b.xPos+b.width)<= 0)) ||
                    ((Float.compare(this.xPos+this.width,b.xPos)>=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0))) {

                return true;
            }
        }
        return false;
    }

    public boolean isCollidingLeft(Block b) {
        if ((Float.compare(this.xPos,b.xPos+b.width) <=0) && (Float.compare(this.xPos,b.xPos)>=0)) {

            if (((Float.compare(this.yPos, b.yPos)>=0) && (Float.compare(this.yPos, b.yPos+b.height)<=0)) ||
                    ((Float.compare(this.yPos+this.height,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0))) {

                return true;
            }
        }
        return false;
    }

    public boolean isCollidingRight(Block b) {
        if ((Float.compare(this.xPos+this.width,b.xPos) >=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0)) {

            if (((Float.compare(this.yPos, b.yPos)>=0) && (Float.compare(this.yPos, b.yPos+b.height)<= 0)) ||
                    ((Float.compare(this.yPos+this.height,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0))) {

                return true;
            }
        }
        return false;
    }

```

Note that I had to do this Float.compare() thing because floats aren't accurate when comparing. Also, I'm not using Java2D, I'm using a framework called libgdx. That shouldn't matter though.

What can I do? Thanks!

EDIT: Guys, that's not the point. I know my code is very unprofessional, but the point is that the collisions don't work the way they're supposed to. I just need a 4-way collision system with boxes. That's all.

# Answer
> 1 votes
I'm not entirely clear on what you're trying to do here. It looks like you only want one of the doXCollision functions to be called, but a lot of collisions are going to intersect two sides of your object at once.

Assuming the Player class inherits from the Block class, I would add four functions for clarity:

```
public float Left()   { return xPos;}
public float Right()  { return xPos + width;}
public float Bottom() { return yPos;}
public float Top()    { return yPos + height;}

```

then you can rewrite your collision function:

```
for (int blockIndex = 0; blockIndex < blocks.size(); ++blockIndex)
{
    Block b = blocks.get(blockIndex);

    if (b.Left() > this.Right()) break;
    if (b.Right() < this.Left()) break;
    if (b.Bottom() > this.Top()) break;
    if (b.Top() < this.Bottom()) break;

    //Collision

    if (b.Bottom() < this.Top() && b.Top() > this.Top()) isCollidingUp();
    if (b.Top() > this.Bottom() && b.Bottom() < this.Bottom()) isCollidingDown();
    if (b.Left() < this.Right() && b.Right() > this.Right()) isCollidingRight();
    if (b.Right() > this.Left() && b.Left() < this.Left()) isCollidingLeft();

    //One object is inside the other - add your solution here
}

```

Apologies for any synax problems in the Java, it's not really a language I'm familiar with. I think I also missed the case where **this** is totally inside **box**, but you should be able to work it out.

# Answer
> 0 votes
What sort of collision detection are you after? just a simple box v. box collision detection (AABB)? If so it is just a simple case of checking to see if the extremities of one box are within the extremities of another and vica versa.

This is just a case of seeing if values are less than or greater than?

Of you can do circle v circle collision detection, where the shapes are approximated by circles, in this case the distance between the centre of each of the circles are calculated which is a simple test (calculating the distance between two points) and if this distance is less than both radius's of the circles added together then they are in collision.

Another good one to use which is slightly more complex is to conduct an on left test, google should have some good suggestions for this, this is good as it can work with complex shapes.

# Answer
> 0 votes
A very quick look at your code suggests to me a very simple cause of your error. You have "else" between all the conditions. That means if you are colliding up or down, the left or right condition will never be checked. I think you want to remove the "else" before the isCollidingLeft test.

# Answer
> 0 votes
The key is not to complicate matters and it seems like you did.

```
 for (int i = 0; i< blocks.length; i++)
    {
        Block b = blocks.get(i);

            return false;

        //bottom y
        if((this.ypos + this.height/2) > (b.ypos - b.height/2))
            b.doBottomCollision(this);

        //top y
        if((this.ypos - this.height/2) < (b.ypos + b.height/2))
            b.doTopCollision(this);

        //right x
        if((this.xpos + this.width/2) > (b.xpos - b.width/2))
            b.doRightCollision(this);

        //left x
        if((this.xpos - this.width/2) < (b.xpos + b.width/2))
            b.doLeftCollision(this);

    }

```

Im basing all of this on the normal coordinate system. (top left 0,0)

Another note would be to try and use pointers.

A better way or initailizing the Block would be something like:

Outside the loop.

```
Block *block = new Block();

Block**blocks = block*[];

blocks[0] = new Block();
blocks[1] = new Block();
etc...

```

you can loop through if you want.

then in your loop you can do ...

```
blocks[i];

```

instead of :

```
blocks.get(i);

```

Although not sure you can fully do this in Java... On an ending note with the code above you shouldnt have to write an code for "being inside another object" considering its impossible if they are squares, although again you havent specified what your actually hitting , or you might have done but i dont do java for gaming.

**Edit** according to stackoverflow ".length" is better than ".size()", especially in arrays

---
Tags: java, collision-detection, libgdx
---


# Question
Title: How to implement cheat proof trading system in a game?
I want to make a game where you can trade items you find from the world, the world would be static, so the master server would always know exactly how much items of X there are etc.

What should i take into account when building such a system?

I want to avoid people being able to cheat and filling the game with free items, but at the same time i want it to be as less server dependant as possible, as i cant afford buying thousands of servers just to run their games on them constantly, even if i had the money, i would prefer not make people to rely on my servers so they can be playing it at any time they want at anywhere, but if they want to ensure the validity of the objects he is going to buy from someone, he would have to connect to the master server if he wants to ensure the objects validity.

But how could i know which objects are genuine and which are fake? So i thought i would give each object in the world an unique ID which cannot be guessed. But then again, wouldnt i have to somehow prove that i collected those items with valid actions? And how could i possibly do that without making the server to run my game from the beginning? And how could i prevent someone trading the same item twice etc.

So i thought i could use a Bitcoin system, but i dont know much about it and im not sure would this be an option since there would be a lot of trading, and a lot more "coins" to trade, so the amount of history information might be too much to handle, not to mention i want to prevent people from cheating in any way, for example you cant trade stuff from the other side of the world and magically teleport the items there (assuming you dont own a teleport atm), you would have to move the items across the world, which would take some time. Also im not very excited about the fact that Bitcoins generation will use intense amounts of CPU power, and im not sure would there be enough Bitcoins for everyone to use; everyone should have equal chance of getting items without depending how fast CPU they have, and im not sure how it would work with fractions of items (like 0.1 of money etc).

Any thoughts and ideas appreciated.

# Answer
> 9 votes
The basic idea is trust. Who can you trust? Nobody. So, don't. Don't let the users decide anything, everything that requires trust happens on the server.

Items only "exist" on the server. Money only "exists" on the server. The clients can do requests (like "I'd like to sell item X"), the server sees who owns what, and thus you can't sell something you don't own. Or buy stuff with money that the server knows you have.

Only delegate things to clients that don't really matter, like particle systems, motion prediction, that sort of stuff.

(Of course you may end up having to trust the client in some things for performance / gameplay reasons, but know that it's always a risk).

# Answer
> 3 votes
Client A invites Client B to trade through the server (so if A is annoying, B can blacklist him).

If A and B decide to trade item N and M, they both sent an 'OK for N and M) to the server.

Server makes the change and sends messages to A and B.

**No P2P, No bitcoins, No 'trust the client just a bit'.**

Simple, fast secure and easy (you can even log the transactions!). What do the world need more than that?

Oh yes, "...I cant afford buying thousands of servers...".

I have a server up and running, the game isn't 100% about trading but you can do it and the bandwith it uses is about nothing. I pay somewhere about 25 dollars or 18 euros a month for the server + a 100Mbit connection. There can be quite a lot of players trading things there before I need an upgrade.

**In this case I'd say:** Do the game, rent a server (don't buy it) and think about scalability later.

# Answer
> 1 votes
As others have said, you can't have a totally secure system without an authoritative server. The best you could do would be some sort of voting system, where clients ask each other if a move is reasonable, and go with a majority vote. That's basically how the bitcoin system you were talking about works, the theory being that a few cheats are going to get overruled by a mass of legit users.

If you want the player to be able to play offline then upload a game state (that sounds like what you're talking about) then it all gets a whole lot harder. The best you can do is close your source, encrypt everything, and hope no-one with decent programming skills cares enough to cheat - which is probably a reasonably safe bet.

As with a lot of these sort of problems for indie games (piracy is another example), if you have to care then you're probably successful already.

---
Tags: anti-cheat
---


# Question
Title: Does a game have to explicitly support SLI/Crossfire to take advantage of it?
This is more of a general curiosity question than a howto question. Just as the title says, do games have to explicitly support SLI/Crossfire to take advantage of multiple graphics cards or are they linked in such a way that you don't need to write extra code?

If explicit support is required, is it common for games to have this support?

# Answer
> 5 votes
No, it's handled at driver level, so even the graphics API doesn't have to know anything about the current hardware state.

---
Tags: graphics
---


title: Farseer engine built for MonoTouch?

text:
# Question
Title: Farseer engine built for MonoTouch?
Does anyone know where I can find a version of the farseer physics engine compiled for MonoTouch, or do most people just download a windows version from codeplex and attempt to build their own solution?

# Answer
Farseer is based on Box2D.XNA, and looking in their repository, I'm seeing what looks like managed C++ (reference). I'm not familiar enough with managed C++ do know if it can be used to generate Mono-compatible .NET DLLs.

However, it looks like there's a native C# port of Box2D here. Just run it through MoMA and then try compiling it in MonoDevelop. I dunno if there's any compatibility scanner for MonoTouch, but last I read the main things you need to avoid are `Reflection.Emit` and unsafe code, and it's not likely those are used in this port of Box2D.
> 1 votes

---
Tags: farseer-physics-engine, monotouch
---


title: Yaw Pitch and Roll question

text:
# Question
Title: Yaw Pitch and Roll question
Yaw is the object turning as if it is spinning on a lazy suzan (one of those spinning plate things you get in chinese restaurants), pitch is pointing the nose up or down, and roll is as if the object is doing a barrel roll.

My question is, do these directly relate to the x, y and z axes? as in, is yaw x, pitch y and roll z? Because If I orient a 3D plane forward using the direct x coordinate system (where z is forward, x is right and y is up) yaw pitch and roll would correspond to the y, x and z axes respectively.

Are they always defined by the axes or are they coordinate system specific?

# Answer
> 1 votes
Yaw, pitch, and roll are coordinate-system-specific. They're also potentially *orientation* specific, if the system also allows 'local' mode in addition to 'global' mode.

For instance, I believe that traditionally engineering/architecure use *z* as the 'up' (out-of-the-page) axis. There are some game engines that do this, as well.

Keep in mind that the actual name of the axis (x, y, z) doesn't really matter - it's what they represent (and the expected order thereof) that does. For instance, if I pass \[front, side, up\], but I'm talking to something that expects \[up, front, side\], things aren't going to be the way I expect.

---
Tags: 3d
---


# Question
Title: Is the STL efficient enough for mobile devices?
When it comes to mobile game development on iOS and Android NDK, some developers write their own C++ containers, while others claim that STL is more than adequate for mobile game development (For example, the author of iPhone 3D Programming uses STL rather than Objective-C in his examples. His defense is that STL is no slower than Objective-C).

Then there are also mobile developers who abandon C++ entirely and develop games entirely (or mostly) in the C language (C89/C90).

What are the benefits and drawbacks of each approach?

# Answer
> 6 votes
Let me tell you one thing first. C++ is faster than Objective-C calls. Objective-C uses message passing systems so it will have some runtime overhead when compared to C++. Just have a look at some of the comparisons here.

Coming to iOS general "app" development, it makes sense to use Objective-C built-in functions as performance cannot be a much criteria to some extent. But in game development, we need to consider these results.

When I was working on my previous project (Robokill), we optimized most of the code where ever necessary with plain-C calls (we converted our Objective-C particles class to a C++ class). Or you can even use Objective-C runtime functions for direct C calls.

Coming to your question, here's my answer: **yes, STL is well optimized for its purpose**. Even though the implementation code is not much readable, it's interesting to check the implementation once.

However, we can optimize Objecive-C code to some extent, by pre-caching the function pointers and making calls with the Objective-C runtime.

Hope this helps!

---
Tags: c++, android, ios, optimization
---


title: Code to tessellate a general quadric

text:
# Question
Title: Code to tessellate a general quadric
Does anyone know of a C/C++ library (or has some source code) that can generate and output (by which I don't mean render) a tessellation of a general quadric, i.e. a 3d surface defined by the matrix equation

X'AX + B'X + c = 0

where X is a 3d point, A is a symmetric 3x3 matrix, B is a 3x1 vector and c is a scalar?

# Answer
I found a relatively simple solution, though the tessellation isn't very pretty or efficient: The quadric defines a scalar value in 3-dimensional space, with the surface lying on the the 0 iso-contour. I therefore create a scalar volume using the quadric equation, and use the marching cubes algorithm to give me a tessellation of the 0 iso-contour.
> 1 votes

# Answer
I don't think there's a quick, easy answer to this, although I wouldn't be shocked to find one somewhere in an old '80s SIGGRAPH article - that's where I'd suggest looking first, FWIW. The approach I would probably take to this:

1. Identify what kind of quadric you have; the best way to do this should be to diagonalizing your matrix A and find its eigenvalues.
2. Translate it to the 'canonical' version of that quadric - that is, eliminate all of the (eliminable) linear terms by setting e.g. x' = x-(B\_x)/2.
3. Use a standard parametrization of your quadric to create a generic tessellation; for instance, for the sphere this would be something like (cos u sin v, sin u sin v, cos v); for a one-sheeted hyperboloid it might be (cos u cosh v, sin u cosh v, sinh v); etc. Note that for an even better tessellation you'll want to use the eigenvalues you found in step 1 to control the relative spacing of your u/v coordinates here, to leave a more uniform final result after the squash/stretch of the first stage.
4. Translate this tessellation back by the inverse of the translation and diagonalizing transforms you had to use to get it into standard form.

In general this will work reasonably well; it's very possible that there will be corner cases for which it's pretty terrible, and if you care deeply about those then you'll really want to dig into the literature to make sure you do this right, but for 95% of what you'll likely need, this should do the trick.
> 3 votes

---
Tags: c++, tessellation
---


title: Increase blitting speed?

text:
# Question
Title: Increase blitting speed?
I'm working on a 2d sidescroller in PyGame. For each map we use one texture (this is the actual size of the texture):

Then we load the image with this code:

```
sprite = pygame.image.load("Maps/MapTesting.png")
sprite.convert()
sprite = pygame.transform.scale(sprite,
              (sprite.get_width()*6, sprite.get_height()*6))

```

As you can see, the texture gets blown up 6 times to create the actual map texture. On average this texture is about 4500x800. This texture has to be blitted to the screen *every frame*, because the whole screen is dirty (thanks to the side scrolling). We do that using this code:

```
screen.blit(sprite, (0, 0),
(cameraposx, cameraposy, windowheight, windowwidth))

```

And it works. The problem is is that it's quite slow: I get a meager 40 FPS on a low-decent PC, and that's without any of the actual AI/objects going on, while we're aiming for 60 FPS. **How can we speed this up?**

---

Note that the above code is sanitized and taken out of context. The full code can be found here: https://github.com/nightcracker/PyGG2

And last but not least, while the above image might look like 8-bit, there are elements in the game which require more bit-depth.

# Answer
> 7 votes
Let me list some general compared optimizations related to Blitting pixels to a surface(from my experience).

1)Usually palette images(indexed images) when blitted, will under go one extra level of redirection (to get the color).So they will be slow when blitting when compared to true color images.

2)True color pixel data (assume With out Alpha - say24 bit data) can be blitted very fast as we can do a memcpy for each scanline of the image(if we are copying a part of the image) on to the device frame buffer.If the data to be blitted is a full image, then we can directly memcpy the whole data which is much faster!

3)Blitting Alpha pixel data will be the costliest as it will include calculating the each component resultant and we need to pack it again to RGB data. In simple terms more operations for each pixel for getting final color!

```
Finalrgb = Alpha*(Srgb) + (1-Alpha)*Drgb (this is for normal blend equation)
    where Srgb is source-rgb (we need to apply for each of the component for final color)
       Drgb is the color that will be there in the destination buffer.

```

I haven't worked on pyGame before.But , A quick look on souce code of it, lead me to assume that it is using 'sdl' Blit functions under the hood. Usually Sdl blit will be very faster and optimized so, just make a not of the above points and profile once again! Good luck!

**Update:*\*Setting color key is like adding one extra check when blitting each pixel to the surface.Some thing like this -

```
       for(eachPixelColor in allPixels)
         {
            if(eachPixelColor is NOT colorKeyColor)
            {
              copy color to the frame buffer!
            }

         }

```

So, here if you see, we are limited not to use memcpy as we need to check each pixel's color validity!

# Answer
> 5 votes
`sprite.convert()` doesn't do what you think it does.

`sprite = sprite.convert()` is what you need.

---
Tags: pygame
---


# Question
Title: SQl, noSQL, and Doctrine with Symfony 2.0
I've had the idea of creating a webgame for a while now, and as it becomes more and more accurate i started playing around with Symfony 2.0.

## First question :

it seems that it is recommanded to use Doctrine2 (ORM) to manipulate database with Symfony, but i'll feel more comfortable with pure SQL. Am i wrong ?

## Second question :

The game i'm thinking of is somewhat a kind of RPG, with the classic character, stats, inventory, etc.

I have some notions of SQL, and i'm improving my knowledge of it at school right now (though i deplore they only teach us oracle environment), but there's a point i need to discuss : How would you modelise the character's inventory ? Is a noSQl databse (mongoDB) usefull here ?

# Answer
> 3 votes
I don't have the *exact* answers you're looking for, but I'll just lay some options out there.

1. I'm biased, but I would say that you definitely want an ORM instead of dealing with SQL directly.

* If you're into the whole OOP thing, then an ORM gives you an object-oriented view of your data, which is usually more helpful than manually pulling data out of rows and stuffing it into records in some weird, custom way that gets smeared all over your sprawling game architecture. Centralize your storage access and Don't Repeat Yourself.
    * A well-written ORM layer gives you a lot of flexibility down the road if you need to switch DB platforms (Oracle to PostgreSQL, or something).
    * You will, inevitably, need to write custom SQL at some point. That's okay, it doesn't mean the concept of ORM is faulty... it's just not an airtight abstraction.

Check out this article on the "Active record pattern" to see what else it gives you. It's a very common architectural pattern for writing ORMs.
2. As far as modeling a character's inventory, you'll *probably* end up with something like this: make Characters, Items, and ItemTypes tables. Each row in Items has the primary key of the row in Characters that the item belongs to (Targ, the barbarian, has this particular sword). Items also has the primary key of a row in ItemTypes *corresponding to the type of item it is* (this sword item is of type sword).

That might not be parseable as English. What I mean is, you don't want to duplicate the attributes of the sword item across every character, monster, and dungeon in the world. You're probably *much* better off making every individual sword item point to a "sword type" and then, when you need to adjust the attributes of swords (and you will), you can change it in one place and **BAM**, it's changed everywhere.

You could extend this to the characteristics of items as well: maybe "of Lightning" is a characteristic that can be added to lots of stuff: weapons, armor, clothes, whatever. So, "of Lightning" gets its own row in the SpecialTypes table and your lowly sword, from the Items table, now points to "of Lightning". **BAM**, one Sword of Lightning coming up.

That all makes more sense if you're modeling this stuff relationally. If you were going the NoSQL route, then you might be better off denormalizing everything into the character object. But I'll let someone else tackle that. ( ;

---
Tags: web, databases, php, sql
---


# Question
Title: Adaptive Characters: AI Solution Needs a Problem
Have sophisticated adaptive programming, will travel - so to speak. I'm part of a group that developed sophisticated learning / adaptive software for robotics. The system "thinks" via its simulator, building and adapting code on its own; and then carries out the best solution. The software can also adapt to new situations, etc. http://mensnewsdaily.com/2007/05/16/robobusiness-robots-with-imagination/

It's easy to imagine using it with automated game characters that will adapt to the players moves and style - the easiest example would be fighting. The more the simulated fighter fights with the human player, the more it learns to counter that players fighting skills. But there should be more.

Anyone have any ideas as to how adaptive characters might be interesting in games?

# Answer
Take a look at Valve's director in Left 4 Dead and Left 4 Dead 2. Using adaptive AI in this aspect may add interesting gameplay dynamics and replayability when the AI learns that there is a set predictable gameplay strategy that players tend to use or abuse.

It would be interesting if AI could evolve to suit an expected gameplay time. So scale harder if a player is blazing through a level, but scale it easier if players are having difficulties. Gameplay valve for a fitness function, maybe someday.
> 3 votes

# Answer
Generally you want to be very careful with this. There's a few reasons why adaptive AI is rare in fighting games:

* Algorithms are significantly more complicated, so the added gameplay must be worth the extra effort, and usually it isn't.
* Having an adaptive AI makes it much harder to have discrete difficulty levels, which removes a lot of the thrill of winning.
* For console games, memory is always bounded (this is one of the TRC/TCR requirements), but genetic algorithms grow unbounded the more experience they get... which basically means you have to force the AI to start "forgetting" things eventually.
* At the end of the day, creating a genetic algorithm is more fun than playing against it. Remember, from a game design perspective, the point of an AI is not to beat the player, but to allow the player to have fun (which generally means "put up a good fight then lose"). An AI that just gets better and better forever eventually sucks the fun out of the game; an AI that adapts to the player by getting better OR worse just makes the player feel like no matter what they do, they never get any better at playing against the AI because it'll always just increase its difficulty to match them, so there's no feeling of 'fiero' mastery.
> 3 votes

# Answer
Adaptive AI is really useful when you need to play a scenario but that scenario can change: i.e. a puzzle, map, turn based adversarial game. A) You can keep the difficulty bounded: You can keep it at different levels based on the performance of the user... if he is blazing through you can ratchet it up to a particular level of difficulty at which point you stop (a lot of games achieve this statically by having easy, medium & hard difficulty, you could do this dynamically but achieve the same point); if he is stuck you can offer hints or ratchet down the difficulty in increments to a certain point below which it does not go (perhaps this is not the game for some users). B) You can have the option to turn off adaptive difficulty. C) You can build adaptive scenarios which alter the course of response and the course of game play based on interactions by the user: Rather than a list of answers, the game has an algorithm set of behaviours based on the choices of the user. This is quite useful. Also this behaviour can be bounded at a certain point if necessary to overcome the difficulty of unbounded "learning". Artificial? Maybe; if it is done right however, it can create unique scenario play each time the same user plays a game which is both challenging and playable. if you can figure out the right balance, it would make an enjoyable game which encourages repeat play.
> 1 votes

# Answer
I feel like this technology has potential in games if you get creative with how you apply it and can really slim down memory usage.

Take the idea of fighting AI, but apply it to player allies. An ally in a game could adapt to better support a player's play style.

There are also likely numerous abstract gameplay ideas that could rely on a system like this. Maybe try releasing some sort of evaluation version of your package for people to experiment with. Kinect really took off because people started hacking on it. You could even try to build relationships with some of the more adventurous game studios and engine developers. Sometimes you just need to let people muck arOund with something before it's potential can be realized.
> 1 votes

---
Tags: android, software-engineering, ai, evolution
---


# Question
Title: Moving players into same square simultaneously?
> Consider a 2 x 2 grid of squares. A player can move onto a square if:
>
> * no other player wants to move into the square next turn
> * no other player has waited and is still occupying the square this turn

I have included the image above to describe my problem.

**Players move simultaneously.**

If 2 (or more) players try to move into the same square, neither move.

# Answer
1. Flag all players as either stationary or moving, depending if they submitted a move this turn.
2. Go through the list of moves. If two moves point to the same location, remove them from the list and set the players stationary.
3. Loop through the list removing all moves that point to a stationary player or other obstacle. Do this repeatedly until the list doesn't change when you pass through it.
4. Move all players.

I think that should work. It certainly works for the case you posted, and a couple of other trivial cases I tested it on.
> 11 votes

# Answer
Collision resolution, instead of collision prevention.

Simply move the objects, then check if there have been any collisions. If there has been a collision with another block move back to previous square, or depending on the game type, a different square.
> 16 votes

# Answer
```
Move all players according to their request.
while there are still some squares multiply occupied:
    For each square that is now multiply occupied:
        For each player in that square that moved there this turn:
            Return them to their previous square
            Mark them as having not moved this turn

```

This requires that each player remembers where they just moved from, so that they can be returned, and also they remember whether they moved this turn. This second check means each piece will only need returning once and should guarantee the algorithm terminates properly. It also ensures that only players that moved are returned - the original occupant gets to remain as they are not considered for removal.
> 4 votes

# Answer
Another solution is to use a map 2x larger than what your are showing. each time you want to move players you move them twice so players always land on tiles with even value for both X and Y. again there will be some rare cases that will need more attention but most of possible cases are resolved (like the one you described) without thinking twice.
> 3 votes

# Answer
Building on SimonW's answer, here's an explicit algorithm:

Let `squares` be an array indexed by the player locations, and containing, for each possible location, either the index of another location or the special value `NULL`. (You may want to store this as a sparse array.) The possible values of the entries in this array may be interpreted as follows:

* If `squares[S]` is `NULL`, the square `S` is free to move into.
* If `squares[S] == S`, either the player at `S` cannot or will not move, or two (or more) players tried to move to `S` at the same time and were both denied.
* Otherwise, `squares[S]` will contain the index of the square from which a player wants to move to square `S`.

On each turn, initialize all entries of `squares` to `NULL` and then run the following algorithm:

```
for each player:
   current := the player's current location;
   target := the location the player wants to move to (may equal current);
   if squares[target] is NULL:
      squares[target] := current;  // target is free, mark planned move
   else
      // mark the target square as contested, and if necessary, follow
      // the pointers to cancel any moves affected by this:
      while not (target is NULL or squares[target] == target):
         temp := squares[target];
         squares[target] := target;
         target := temp;
      end while
      // mark this player as stationary, and also cancel any moves that
      // would require some else to move to this square
      while not (current is NULL or squares[current] == current):
         temp := squares[current];
         squares[current] := current;
         current := temp;
      end while
   end if
end for

```

After that, loop through the list of players again, and move those which are able to do so:

```
for each player:
   current := the player's current location;
   if not squares[current] == current:
       move player;
   end if
end for

```

Since each move can only be planned once and cancelled at most once, this algorithm will run in O(*n*) time for *n* players even in the worst case.

(Alas, this algorithm won't stop players from switching places or crossing paths diagonally. It might be possible to adapt Gajet's two-step trick to it, but the completely naive way to do so won't work and I'm too tired to figure out a better way just now.)
> 0 votes

# Answer
Register all requested moves using an array or map.

If there is a conflict, revert the move request in question. If that returns the object to a square another object is trying to occupy, revert the requesting object's request.

Pseudo code:

```
int[][] game; // game board

var doMoves() {
    int[][] dest = [][]; // destinations; cleared each run

    for (obj in gameObjects)
        if (obj.moveRequest) {
            var o = dest[obj.moveX][obj.moveY];
            if (o) {
                // collision!
                o.doNotMove = true;
                obj.doNotMove = true;
            } else {
                dest[obj.moveX][obj.moveY] = obj;
            }
        }
    }

    // check move validity
    for (obj in gameObjects) {
        if (obj.doNotMove) continue;

        var o = game[obj.moveX][obj.moveY];
        if (o and o.doNotMove)
            revertRequest(obj, dest);
    }

    // process moves
    //etc
}

// recursive function to back up chained moves
var revertRequest(obj, dest) {
    if (!obj.doNotMove) {
        obj.doNotMove = true;
        var next = dest[obj.x][obj.y];
        if (next)
            revertRequest(next, dest);
    }
}

```
> 0 votes

---
Tags: turn-based
---


# Question
Title: How to make a platformer character go DOWN a 315 degree slope?
Alright, so I got this code I'm trying to write, but the player won't go down the slope, it goes down and up perfectly on the 45 degree slope, but the 315 degree one is a mess. it goes "up" the downward slope, get's stuck and some other stuff. Anyway here's the code:

```
//you're in a double for loop going through every tile in the map, the int's being used are x, and y

//check if the tile is a slope
if (lv.type[lv.tile[x, y]] == Tiles.SLOPE)
{
   //create a rectangle collision box
    Rectangle tileCol = new Rectangle(x * lv.tileSize, (y * lv.tileSize), lv.tileSize, lv.tileSize + 1);

    //if player collision "col" collides with "tileCol" and you haven't done this before this itteration (only happens once per full double loop)
    if (col.Intersects(tileCol) && !onSlope)
    {
        //get the angle of the tile
        float angle = lv.angle[lv.tile[x, y]];

        //get the x distance of how far away the player's right is inside the tile
        float dist = (col.X + col.Width) - tileCol.X;

        //constructs the opposite of a right triangle
        float opposite = (float)(Math.Tan(MathHelper.ToRadians(angle)) * (dist));

        if (angle < 90)
        {
            //if player's right is less then or equal to tile's right
            if (col.X + col.Width <= tileCol.X + tileCol.Width)
            {
                //place player on slope. this works properly
                pos.Y = tileCol.Y - opposite;
                //tell the program we don't wanna go through this again until the next full loop starts.
                onSlope = true;
            }
        }

        else if (angle > 90){
            if ((col.X + col.Width) >= tileCol.X)
            {
                //this is where the error is. the player goes "up" a slope that's 315 degrees, instead of down it.
                //how do I make the player go down the slope that's 315 degrees!?
                pos.Y = tileCol.Y + opposite;
                onSlope = true;
            }
        }
    }
}

```

currently using this code, it makes the player move in a 45 degree angle on the 315 degree blocks.

```
else if (angle > 90)
                            {

                                if (col.X >= tileCol.X)
                                {
                                    pos.Y = tileCol.Y + lv.tileSize + (dist * -1);

                                    onSlope = true;
                                }
                            }

```

# Answer
Handle all slope tiles as a rise/run ratio. Each slope tile will have a ratio, and assuming 45 degrees means going up as you go right, 315 degrees will have a ratio of -1. Think back to basic coordinate algebra. Using the player's X position local to the tile, which is the run, solve for pos.Y by multiplying the X position by -1.

However since y = 0 is likely at the bottom of the tiles, you'll have to offset the height by adding the height of the tile.

So the player is colliding with a downwards sloping tile, the slope ratio is negative and the formula should be

```
pos.Y = lv.tileSize + (pos.X * slopeRatio)

```

Otherwise

```
pos.Y = pos.X * slopeRatio

```

if the slope is going up. Determine if the slope is upwards or downards by the sign of the slope ratio.
> 3 votes

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


# Question
Title: Can the player character and static entities use behavior trees instead of state machines?
When I read discussions about state machines vs. behavior trees, it is often in favor of using one over the other. However, this seems odd to me that you wouldn't still need a state machine to manage the player character and static game entities (weapons, equipment, food, money, etc.). Do behavior trees translate to those concepts as well, even though they aren't technically AI?

# Answer
A behavior tree is essentially a sub-type of a (possibly non-deterministic) state machine. Behavior trees are used not because they can do something FSMs can't, but because they are simpler to follow and understand for us humans.

Generally, AI has tons of states, and behavior trees are used to make them understandable. Other management, on the other hand, usually uses few states, and is perfectly clear even with most brain-dead FSM implementation.

If you, for some reason, have really complex behavior outside the AI - for example, you're making a game about alchemy, with tons of interlocked recipes, item properties, etc - using behavior trees instead of state-machines might be helpful.
> 6 votes

# Answer
Look at it like this, an enemy entity (clearly something in need of AI) is something that needs a behavior of some sort. We need this behavior to be conditional and not totally predictable. A behavior tree (with weighted-random chances when making a choice) is a good fit for something like this.

Now let's take a look at a gun. This clearly is not an item that is in need of a complex behavior, frankly I would not even suggest a (complex) state machine. All the gun needs is a few rules:

* Trigger pulled + clip is not empty = fire bullet
* Trigger pulled + clip is empty = make click sound
* etc...

So that's basically how I see how someone could make an educated guess on what system best to use, of course there are always exceptions but always first try the simplest solution imaginable, often simple rules are the most fun (since people can understand them and mechanics do not become a black-box).
> 5 votes

---
Tags: ai, game-mechanics, behavior
---


# Question
Title: Vector class throwing an error after publishing the FLA for generating .ipa from flash CS5
I am creating a flash game for iPhone using Flash CS5. Everything runs smoothly when creating the SWF via `Ctrl`+`Enter`. But when I am attaching the .p12 and provisioning profile files and publish the FLA to generate the .ipa there is an error thrown by the compiler that is:

`"Incorrect number of arguments, Expected no more than 0"`

```
private static function closestVertexOnOBB(p:Vector,r:RectangleParticle):Vector
{
    var d:Vector = p.minus(r.samp);
    var q:Vector= new Vector(r.samp.x, r.samp.y);

    for (var i:int = 0; i < 2; i++)
    {
        var dist:Number = d.dot(r.axes[i]);

        if (dist >= 0) dist = r.extents[i];
        else if (dist < 0) dist = -r.extents[i];

        q.plusEquals(r.axes[i].mult(dist));
    }
    return q;
}

```

# Answer
> 2 votes
The `Vector` class is actually a native flash class since Flash Player 10 (API docs) and is therefore a class-name you should avoid for your classes.

If you wrote your 2d vector class yourself, you should be able to rename it to solve the ambiguity. If it's part of an external package, you could also use the fully qualified classname if you want to use the 2d Vector class.

Imagine the Vector class is in `com.geom.Vector`, your code should look like this:

```
private static function closestVertexOnOBB(p:com.geom.Vector,r:RectangleParticle):com.geom.Vector
{
    var d:com.geom.Vector = p.minus(r.samp);
    var q:com.geom.Vector= new com.geom.Vector(r.samp.x, r.samp.y);
    ... etc ...

```

I don't know why the code works if you test it locally though. It should produce the same error.

---
Tags: flash, actionscript-3, flash-cs5
---


# Question
Title: Image drawing tools (that aren't Photoshop) that work in the sRGB colorspace
I'm looking for a way to create sRGB raster images. Now, I could use Inkscape and just have it render to a raster format, but are there any image drawing tools other than Photoshop that work in sRGB?

Here's what I want to be able to do more specifically. Let's say the image is all one color. I want to be able to pick color 0x808080, which is in the sRGB colorspace. I want the file to write an image where every pixel is 0x808080. And then, when I read it, I can tell OpenGL that it's sRGB color data, so it will treat the 0x808080 color has being from the sRGB colorspace.

The important part is that, when I'm selecting colors in the tool, the colors I'm selecting are from the sRGB colorspace.

# Answer
sRGB is the default color space for most of todays operating systems. From Wikipedias entry about sRGB:

> ... one can generally assume, in the absence of embedded profiles or any other information, that any 8-bit-per-channel image file or any 8-bit-per-channel image API or device interface can be treated as being in the sRGB color space.

What that means is: Unless you're using a color managed application (eg. Photoshop) where you're specifically using a profile that's different from sRGB, you will actually work in the sRGB color-space. So if you're using an application without color-management (eg. Paint.NET), you will work in sRGB color-space.

As I mentioned in my comment, the GIMP might be a good candidate for your needs (it also uses sRGB as default color-space, but does support color managment if you need to convert from one color-space to another).
> 5 votes

---
Tags: tools, image, color
---


title: 16-Bit textures in XNA 4 on WP7

text:
# Question
Title: 16-Bit textures in XNA 4 on WP7
WP7 textures are supported in the Reach-Profile that WP7 devices falls into. But XNA converts all my ressources upon adding them to a project to RGBA8, that's insane, the displays of WP7 devices are 16 Bit!

**Information:** WP7 SDK 7.1 (XNA 4), Visual Studio 2010

**Question part 1:** How can I add a RGB565 texture to a XNA project and what is the correct way to load them inside a game?

**Question part 2:** Is there a reasonable 16 Bit texture format (within Reach) that supports alpha with MORE than 1Bit?

**Question part 3:** Is the normal rendertarget (I think that's what the screenbuffer is?) already 16 bit?

# Answer
> 3 votes
**Question 1:** When adding a texture with the default **Texture - XNA Framework** content processor it gives you three choices in the **Texture format** property: Color, Compressed and No Change. You must set **No Change** and use a source texture that is already in a 16-bit format; for example a PNG image or a DDS image. Or, you can do your own content processor and force change of all your textures to 16-bit (although it is a bit overkill).

**Question 2:** The available 16-bit formats are 565 (no alpha), 5551 (1-bit alpha) and 4444 (4-bit alpha). Or, you can use DXT5 that has 32-bit alpha, although this will kill your soft gradients and give them a blocky appearance.

**Question 3:** Maybe, maybe not. It depends on the hardware and OS version. Some phones set 16-bit by default, but ALL of them support 32-bit. So, to make sure you have a 32-bit backbuffer, go to the constructor of your Game class and set this line:

```
graphics.PreferredBackBufferFormat = SurfaceFormat.Color;

```

# Answer
> 0 votes
RGBA8 textures on a 16-bit display device are not so insane. The graphics device may very well be performing all of it's calculations at a higher precision internally, then dithering down to 16-bit for the final display (this is not an outlandish concept - 3DFX did it in 1996). RGBA8 can also be faster to operate on, to sample from, etc, as it's just a matter of accessing one byte from a byte\[4\] array; with 16-bit - because the size of each colour component doesn't map to any native data type - the driver will need to so some (very slightly, but overhead can pile up) tricksy stuff with bit shifts and bit masks.

---
Tags: xna-4.0, windows-phone-7
---


# Question
Title: How do I animate a spritesheet in cocos2d Android
I'm trying to animate a sprite in a spritesheet, the goal is to make the character walk from left to right. I subclassed CCSprite: CharacterSprite.

this is my code:

```
    CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames("WalkAnimation.plist");
    CCSpriteSheet spriteSheet = CCSpriteSheet.spriteSheet("WalkAnimation.png");
    w.addChild(spriteSheet);

    ArrayList<CCSpriteFrame> walkSprites = new ArrayList<CCSpriteFrame>();
    for(int i = 1; i<=8;++i)
    {
        walkSprites.add(CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName("walk"+ i +".png"));
    }
    //float randomFactor = (float)Math.random()*10;
    CCAnimation walkAnimation = CCAnimation.animation("walk", 0.1f, walkSprites);

    Log.v("addEnemy", "Show");
    this.character = CCSprite.sprite(walkSprites.get(0));

    Log.v("addEnemy", "Don't Show");

    this.walkAction = CCRepeatForever.action(CCAnimate.action(walkAnimation, false));
    character.runAction(walkAction);

    for(int k =0; k<amount; k++)
    {
        float randomFactor = (float)Math.random()*10;
        character.setPosition(CGPoint.ccp(-randomFactor * character.getContentSize().width/2, winSize.height / 6.0f));
        spriteSheet.addChild(character);
    }

```

This code is in my 2nd scene. And whenever I press on Start Game, nothing happens. But the code is executed till: character = CharacterSprite.sprite("walk1.png");

Can someone provide me of a snippet of animation using a spritesheet?

# Answer
I have found the problem. the images referred from the plist are called 1.png etc while I put in walk1.png
> 2 votes

---
Tags: android, cocos2d
---


# Question
Title: legal disclaimers and lisence type for a free multiplayer browser game
I have created a multiplayer browser game. The game is completely free (donations are welcome) but I would like:

(a) to protect my concept in some way. (b) to provide legal notes that the user should accept before registering.

In some games (i.e. Travian) there are legal notes such as `Terms and Conditions`, `Privacy Policy`. Should I include things like these? Where can I get/create such legal texts? I can barely afford hosting, not to mention a lawyer to write all those things for me.

What should I do?

Chris

# Answer
You can protect yourself with disclaimers (Not responsible for lost work, time, nerves,...) but protecting the concept (=idea) is impossible. The good news (or bad, depending on your skills) is, that idea is only a small portion of success. It's execution that matters.
> 2 votes

# Answer
Protecting your concept, at least in the US and most other countries (I see from your profile you're in Greece) is simply a matter of sticking `Copyright <Name> <Date>` on your game/website somewhere. Without hiring a lawyer, that's about the best you can do (then just hope that no one else steals your concept from you...)

As for `Terms and Conditions` and `Privacy Policy`, it's a good idea to include something like them, mostly since they are there to protect you from getting sued by someone. There's generic versions of these out there on the internet, just do a search. A generic version probably won't be quite as good as something written for you by a lawyer, but it should cover the basics at least.

Obligatory "I am not a lawyer, rules vary by country, this isn't legal advice" text here.
> -2 votes

---
Tags: legal, browser-based-games
---


# Question
Title: Box2d/Farseer how to use the World object?
this question is primarily about farseer but as it is a wrapper around box2d i think it's relevant for both libraries.

I'm in the beginning of developing a simple platform game, and I'm stuck as to how i should use the World object in relation to my "levels". Should I create a new world for each level and load all the contents of my level into this new world. Or should I remove all objects from my world and load in the new contents of the new level?

Any help or suggestions are greatly appreciated.

# Answer
> It seems i should read the documentation (obviously) before posting questions. The Box2d manual states: "Box2D supports the creation of multiple worlds, but this is usually not necessesary or desireable." So I guess I'll just clear the world for each new level. I can't mark this question as answered for another seven hours. –

This part of the documentation signifies that it's not necessary or desirable to have two active instances of the **World** class at the same time.

When loading a new level you can just have the old world object garbage collected. You don't have to pull some fancy tricks to pass the world object from the old, now obsolete level object, to the newly loaded level object. Of course if your world object is static, or managed by something else than level. (Say a LevelManager or something) then clearing the world object and then adding all the new stuff to it is just as good (or maybe even better), but both approaches should not bring any noticeable changes.

Btw, I'm not sure how far you are with learning Farseer, but I do know that it's quite hard to find tutorials, a user called RabidLion updated my Farseer tutorial to Farseer 3 and added quite a few extra things so it might be worth looking at: http://roy-t.nl/index.php/2011/01/12/xna-farseer-platform-physics-tutorial-updated-to-farseer-3/
> 1 votes

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


# Question
Title: How do I implement a subclass of CCSprite?
Can someone tell me how to subclass CCSprite on Android?

I've added this snippet of code into my CharacterSprite:

```
public static CharacterSprite sprite(String fileName) {
  return new (CharacterSprite)CCSprite(
    CCTextureCache.sharedTextureCache().getTexture(fileName)
  );
}

```

But `getTexture()` can't be found. Can someone help me please?

# Answer
> 4 votes
Here is the way generally followed to sub-class a CCSprite.

```
    public class CharacterSprite extends CCSprite
     {
        // Add new custom fields or methods here,
        // or override the specific methods of CCSprite
        // that you want to extend the functionality of.
     }

```

From your question I can understand that you are inheriting CCSprite not to extend the functionality. Usually this should be avoided. There is no need to override the `public static CharacterSprite sprite(String fileName)` method as it will be already there in the super class.

So a call like this will do: CharacterSprite.sprite("sample.png"). This will return a sprite you desire!

In fact, There are two ways you can make CharacterSprite class which you desire.

1. Inheriting CCSprite. Do this only if you are *really* over-riding any functionality of the existing CCSprite (for example, if you want to draw with multi-texturing , override draw and have your code).
2. Have CCSprite instance as an attribute (member) of CharacterrSprite class. This is the better way if you are "not re-defining" the functionality of CCSprite.

For example, the second case will be like this:

```
 class CharacterSprite
 {
   Position m_pos;
   // ...
   CCSprite m_sprite; // The sprite instance.

   CharacterSprite(String filename)
   {
     m_sprite = new CCSprite(filename);
   }
 }

 // Usage:
 CharacterSprite _character = new CharacterSprite("character.png");

```

Now add \_character.m\_sprite to the current scene/layer.

---
Tags: android, cocos2d
---


# Question
Title: How do you setup the Irrlicht and Bullet engines for Android development?
I have begun researching graphics and physics engines to use for an Android 3d game that I would like to make.

While researching I stumbled across this page where he talks about how you can use the Irrlicht graphics engine and the Bullet physics engine for Android development.

I have a few questions about this

1. Will these engines work for Android like he says?
2. Are these good choices for open source engines on Android?
3. What does he meen when he says, "Then we put all the C/C++ source codes under the jni folder". What is the jni folder? Should this go under the src folder?

# Answer
> 2 votes
1. Yes, I don't see why not
2. They're OK. But my engine of choice at the moment is libgdx It has the Box2D physics engine integrated
3. Please look up the documentation of the Android NDK In short, there needs to be a jni directory in your Android project that creates a native C++ library that can be used from your Java code. You can refer to the samples in the NDK to setup your project.

---
Tags: bullet-physics, irrlicht
---


# Question
Title: Best portable console platform for game development?
I'm looking to experiment on a portable console platform ala Nintendo DS and PSP. But it could also be GP32, GP2X, GP2X Wiz or GP2X Caanoo.

So, before I go out and buy one, I'd like to hear from people who have experience with any portable console.

It would be best if each answer talked about one console with a link, pros, cons and personal experience (if any).

*NOTE: I'm not looking for a mobile platform like iOS/Android/etc. I already know the answer to that: Android (I already have an Android device and I know Java). I'm specifically looking for a handheld console. See NopeAndNever's answer.*

# Answer
> 1 votes
*I'm not really a pro but you can look into the following consoles: (both are linux powered --\> ease of development)*

*You can program in every program language that has a toolchain for ARM when developing for Linux in embedded devices, that gives you many possibilites instead of using a propretary SDK*

**Dingoo A320 http://dingoowiki.com/index.php?title=Main\_Page (look for dingux)**

'Made in china' but with a nice community and many emulators, but you have to flash the linux yourself (again, look for dingux), I own one of those, they are 'good' but not 'nice'

**Open Pandora http://openpandora.org/index.php?lang=en**

Made in Germany, a linux handheld with dual analog sticks, a keyboard and overall good hardware (afaik 600 MHz Core + dedicated GPU + 800x480 display) are a +, but the availability of a console may be a problem (they are producing as fast as they can)

**Edit:**

NDS: Weak hardware (except you know EXACTLY how to use it), probably pretty hard to efficiently code

PSP: Good hardware, homebrew is 'ok', can be signed by now (will run on any console) but is hard to use (you should know what texture swizzeling for the GPU is etc. to make a game run halfway decent)

# Answer
> 1 votes
I have only tried development with the DS and the PSP, myself, and I've found the PSP to be a vastly nicer system to work with. The DS required a lot more hardware when I last looked into it -- I imagine some of these limitations have been worked around more recently, however.

Both are, of course, going to be a little tedious because of the fact that they are consoles and the fact that you'd be developing on them via unsupported means (and so jumping through some hoops, et cetera).

Developing on the PSP works best with older machines -- the "fat" original PSP seems to be the most broadly supported. You used to have to obtain a tool-mode battery -- either by purchasing one or making one yourself by taking apart a regular battery and applying a soldering iron. With that battery you could use some software to create a bootable memory stick that would let you install custom firmware to the device.

That may not be necessary any longer, however, it looks like the latest versions of the custom firmware installers available can simply be copied to a memory stick and launched from the standard firmware OS, which seems nice. They have to be re-run every time the machine suffers a hard power off though.

The PSP homebrew dev kit I used is here. They have toolchains for a number of other platforms as well.

I built a (very small) CLR implementation for the PSP using this setup (it could run most C# programs with simple console output as long as they didn't thrown exceptions, because I never got around to implementing that). With some judicious use of batch files or shell scripts you can make the code -\> build -\> deploy -\> test loop fairly quick, although it's always going to be more annoying than simple PC development.

# Answer
> 0 votes
GLBasic is a very simple language with tons of features.

On it's features page, it lists the following as supported devices:

* GP2X
* GP2X-Wiz
* GP2X-Caanoo
* Pandora

It can do 2D and 3D, plus supports many other platforms and devices. They have a free version that you can check out, and when you're ready to test on those devices you can purchase the premium version for fairly cheap.

\[Edit\] Hmm, I don't know why this got down-voted? It is a valid answer, it just doesn't allow Nintendo devices, which most don't, and the OP did state it could be for the GPxx devices, which this does.

GLBasic allows most other platforms and since your main concern is 'ease of development' let me just say that it doesn't get any easier than with this SDK. Using BASIC for it's base language, you can get results quickly. It has most features that you may need, especially if you are new to game programming.

One limitation is that it doesn't have a native physics engine, but there is a Box2D wrapper in the forums. Any questions are usually answered quickly in the forums, and most by the developer himself. Bug fixes are quickly resolved and updates are frequent.

\[Edit 2\] I realize my answer was about how easy GLBasic is to program, and not specifically how easy the listed devices are to develop for. Maybe I should have worded it to say the GPxx devices are easy to develop for since SDKs such as GLBasic exist, which allow you to program your game using a simple language, then compile and deploy to your devices with a few clicks.

---
Tags: console
---