title: Android Coordinates

text:
# Question
Title: Android Coordinates
Is their a way to make it where no matter what the screen size is my sprites will always start at a certain position. I am trying to get my sprites to start in the lower right corner area of the screen. I am using a 2D SurfaceView.

# Answer
> 4 votes
Get the screen size (this StackOverflow answer says how) and you'll have a vector (of the mathematical variety) representing the bottom-right coordinate of the screen. Now you can just place stuff relative to this vector in order to place things relative to the bottom-right of the screen instead of the top-left.

I'm assuming that on Android, (0,0) is the top-left corner of the screen. If it isn't, I'll edit this answer to accommodate.

---

### In case it isn't clear how that would work, here's an explanation

*First: please make sure you have a basic understanding of vectors (not the list type, but the mathematical object). The vector tag's description links to a succinct tutorial on vectors within the context of games. Read part one at least. A basic understanding of vectors is critical for game programmers, if only because it will make your life easier.*

Remember that the *origin* of the screen, which sits at the top left, is `(0, 0)`. Consider that when you place something at `(30, 30)`, you're actually placing it at `(0, 0) + (30, 30)`. You're placing it at `(30, 30)` relative to a particular point on the screen - the origin.

So if you want to place something 25 pixels left and 20 pixels up from the bottom-right corner, you're placing it at `(-25, -20)` relative to the bottom-right corner. Assuming `(right, bottom)` represents the bottom-right corner of the screen, that means you just place your sprite at `(right, bottom) + (-25, -20)`.

In code, assuming you have a 2-dimensional vector class named `Vector2`, which represents a mathematical vector (*NOT* the vector list type!):

```
// From the StackOverflow answer linked at the beginning
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

// This is the coordinate of the bottom-right most pixel on the screen
Vector2 bottomRight = new Vector2(width, height);

// This is the position you want the sprite relative to the bottom-right point
// (25 pixels left, 20 pixels up)
Vector2 distFromBR = new Vector2(-25, -20);

// This is the position you should place that sprite to have it in the right position
Vector2 spritePos = bottomRight + distFromBR;

```

---
Tags: java, android
---


# Question
Title: XNA Content Pipeline With Map Creation Utility
I've been looking into how to use the XNA Content pipeline appropriately for a game I am working on. I have however been having a hard time wrapping my head around it and am not sure on the best way to proceed.

The specific example is, I have a top down 2-d RPG style game. I want to create a utility (probably Windows Forms) that will allow me to easily create and edit maps. Each map consists of 1 or more graphic layers, each layer containing a N x N grid of tiles. In turn each tile starts out as a bitmap.

Given the above information I see a few ways to proceed:

1. Store the map info in an XML file compatible with the Content Pipeline XML loader. Each tile is stored as a string reference to the corresponding texture asset. Texture assets are added in the game project.
2. Store the map info in an XML file compatible with the Content Pipeline XML loader. Each tile is stored as the path to the corresponding .bmp/.png files.

Now there are things that I really don't like about both approaches. The main issue with approach one is that the map creation and the .xnb texture asset creation are completely separate. The .xml map file is created by the utility, while the texture asset is added to my content in my game. This becomes an issue trying to make sure the .xml map file and all the texture assets in the project stay in sync.

Approach two would allow me to keep all the appropriate image file next to the map files using the map utility. However, it seems like I shouldn't have to do something like this. Also I would need to be more intelligent about loading the maps so that I am not rapidly loading the same image off disc for each tile.

So my question is: If you want to add a content generation utility (like a map editor), what is the best way to make sure that the custom content (map file) stays in sync with the texture assets. Also, keep in mind that in my map editor I would need the ability to load and display the texture assets.

Any input is much appreciated.

# Answer
What you want is to is get your textures to build based on the contents of the XML file. This way you don't have to add the textures to your content project, the pipeline will automatically include the texture file into the build for you.

To do this you will need to write a custom content processor (you can still use the standard XML importer), and use `ContentProcessorContext.BuildAsset` in that processor to reference the external texture.

I think that you will need to create a custom `ContentTypeWriter` and `ContentTypeReader` to write and then read the `ExternalReference` that `BuildAsset` gives you.
> 6 votes

# Answer
Put all your tile-images into a single image file, and reference them by the tile-number.

This will be much more performant and error-proof, and has the advantage that you can set up your levels in a tile-editor like Tiled.
> 2 votes

# Answer
I'm not 100% sure I got your question clear in my head, but try this:

You'll have to make the map editor leading, don't add any assets to your Content project except for one XML file (game.xml or something). Now have your level editor edit the game.xml file, by adding links to other files. For example creating a new level in your level editor adds the tag `<level rank=5>Content/MyLevel/level5.xml/>` to your XML file.

Now to get everything built you need to write a custom content pipeline extension. *(Make sure to set the new importer and processor on your game.xml file instead of the default XML processor)*

This processor will traverse the XML files and build all the assets by calling the appropriate importers and processor. This will leave you with everything nicely built and not having to go back and forth to the content project and your editor.

Resources: http://msdn.microsoft.com/en-us/library/bb447754.aspx
> 1 votes

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


title: Material vs Material Pass

text:
# Question
Title: Material vs Material Pass
I am trying to figure out the difference between a "Material" and a "Material Pass" (in theory). Is it basically that a Material will have multiple "Material Pass"'es, along with a name. Then the "Material Pass" will have the references to the texture, shaders and property values that need to be set?

# Answer
You haven't given us much context about where you heard these terms. Their meanings can vary, but generally they mean the following.

A ***material*** usually refers to the collection of textures that produce a certain surface look. This can include the ambient/diffuse light texture, the normal map, the ambient occlusion map, the specular exponent map, the specular intensity map, etc.

A ***material pass*** in a forward rendered pipeline refers to using the material textures to apply lighting and color to an object. This is the step where we draw part or all of the colors on objects to the scene texture. With forward rendering, this usually means including all of the lighting effects during this pass. There is often only one material pass, but sometimes multiple material passes are done in order to apply part of an effect at a time, as an optimization, or to overcome hardware/software limitations.

A *material pass* in a deferred rendering pipeline usually refers to the pass where materials are applied. Several "passes" are done in a deferred rendering pipeline. We have a depth pass where we draw all the depths in the scene to a texture, a lighting pass where we draw all the lights to a light buffer texture, a material pass where we draw all of the object colors to a material texture. These multiple textures are then later combined into a final image.

---

In other words, a material is a collection of textures to be applied to a piece of geometry, and a material pass is where we actually apply some or all of the color and light effects that the material represents to the geometry.
> 6 votes

# Answer
The term "Material" usually refers to a specific set of surface characteristics, which are used by a lighting model to compute the reflectance at a point on a surface. But if it does, then "Material Pass" doesn't really make sense.

Therefore, let's assume that by "Material", what you really mean is "a visual effect that I would like to produce, using one or more light sources and arbitrary other data." In which case the term "Material Pass" is a single shader that implements some part of this visual effect.

Note that the typical terminology for this "Material Pass" is "Shader Pass" or something of the like, while the term for what you seem to call "Material" is usually "Effect" or "Technique".

An Effect can be achieved by one or more Shader Passes. A Shader pass is a concrete piece of shader code, which has a number of parameters (uniforms/constants depending on the language). It will take certain inputs and produce certain output value(s). Multiple shader passes are composed with blending operations or possibly with direct shader feedback through render-to-texture.
> 3 votes

---
Tags: architecture, graphics, directx, rendering, graphics-programming
---


title: Non-blocking VSync in Direct3D

text:
# Question
Title: Non-blocking VSync in Direct3D
I have a Direct3D application which uses a PRESENTATION\_INTERVAL\_ONE implementation. Pity, its blocking and eating my CPU waiting for Present. I ended up searching for raster scan (BitBlt) solutions, sample code from the Internet, but none of them actually worked well - failing to do the exact timing prior to Present call.

**Question**

So, ideal solution for me would be using PRESENTATION\_INTERVAL\_ONE (or if its not possible - IMMEDIATE), calling a function

```
// blabla code
waitForVsync(); //loop here with sleeps or whatever, freeing my CPU
()->Present();  //just in time, no blocking wait, yay!

```

And upon a return I call Present, which is, lets say, 1ms for \_ONE and 0ms for \_IMMEDIATE prior to physical top scanline.

I know I am asking a lot and do not hope for a solution in 2011 year, as Microsoft also has failed to improve in this area.

To clarify the issue, I provide a link with a more detailed analysis of a problem: http://www.virtualdub.org/blog/pivot/entry.php?id=157

# Answer
It seems to me that you're trying to achieve a graceful co-existence with other processes on a PC game? I.e. to not occupy the entirety of the CPU all the time, so as to allow other processes to run (and if you're running on a laptop, to allow the speed-stepping to power down the CPU and preserve battery life)?

I've certainly tried to achieve this in the past, and never fully settled on a solution I liked. I never tried Crowley9's method of using the DONOT\_WAIT flag, but to me that smells like closer to the right solution. If Present only blocks when the present can't be queued (because there's already another present queued), then you don't need to call Present 'just before' the VSync happens, you just need to sleep until it's likely that another call to Present will succeed (which will be any time after the next VSync).

The root problem is that you don't really know when the VSync occurs, and a system like that needs to stay synchronised.

The basic gist of my solution was: don't use Present to find out where the VSync boundary is, do the timing yourself, and make sure you're calling Present as close to the appropriate time as possible. If you're late, it won't matter because of the internal buffering D3D does, and if you're early then it will simply block and the worst you'll incur is some extra CPU usage.

What I did do was to use (microsecond accurate) timers, track the elapsed frametime, and sleep accordingly. There's no magic flag or function I know of to say 'wake me when VSync's about to happen', because there isn't an event available that is signalled when a VSync is about to happen. So instead I looked at how long the frame had taken so far, figure out when I thought the next VSync would occur, subtracted a grace period (I think I left 3ms), and call ::Sleep.

E.g. if the frame processing took 2ms, I would get to the Present call early. If I called it straight away, I'd expect it to block (at 100% CPU) for 14ms. Instead, I call ::Sleep(11), and then the subsequent Present only blocks for ~3ms). If the frame processing took longer than 13ms, I'd just call Present without sleeping. If it took longer than 16ms, I'd switch down to 30Hz rendering (with some hysteresis), and adjust the Sleep timings accordingly.

BUT I was never particularly happy with this solution, for several reasons. If you're running on a loaded system, Sleep is by no means guaranteed to give you control back in that 3ms window, you have no good control over the OS time-slicing.

Worse, the minimum sleep time is supposedly 10ms, anything less than that and it ends up sleeping for 10ms regardless of what you specify (in practice it's way more variable than that). So you also have to track how long you actually slept for, and factor that into your logic (so you avoid sleeping if you're running late). And then you end up calling Present late one frame, then avoiding the sleep the next frame and calling it early the next. E.g.

```
0ms (0ms) : start
10ms (10ms) : process frame 1
10ms (20ms) : try to sleep for 3ms, end up sleeping 10ms
0ms (20ms) : present late, succeeds straight away
10ms (30ms) : process frame 2
2ms (32ms) : don't try to sleep, present early, blocks till the next vsync

```

So for managing 60Hz rendering, the granularity of the time-slicing / Sleep function makes this a not great solution. And it also doesn't take into account the actual refresh rate of the system!
> 1 votes

# Answer
To address the specific issue of waitig on present: Present does not work quite the way you think: it does not block and wait for VSync. CPUs have not been synchronous with GPUs in many years. Rather, it queues up a wait-for-a-vsync-and-flip operation, and returns. The GPU will process it when it gets to it.

If you are seeing present take a non-trivial amount of time, that is because it is waiting for an older frame to finish (there is a limit on the number of frames in flight). If you want to do other processing, rather than waiting, you can use the DO\_NOT\_WAIT flag to do a non-blocking present that will return whether or not the present was queued successfuy, or if the hardware was busy.
> 2 votes

# Answer
As this has moved to gamedev I'll assume it's game related, despite nothing that alludes to gaming in the question.

The usual answer to letting the CPU carry on and do work once you hit a 'Present' is to double/triple buffer the backbuffer, which allows the CPU/GPU to start work on the next frame before the one you've just finished rendering has been displayed (if you didn't double-buffer then you'd be rendering the next frame over the one you'd just finished and would be a mess). The flip then is queued up behind the scenes and the CPU can carry on doing other work. If you don't do much in a frame it's possible you could hit 'Present' again before either of the backbuffers have been displayed and it could block again.

Is the question above actually about 'VirtualDub' (as the info there seems to be from 2007), or is it related to making games? I'm still not sure exactly what it is you're trying to achieve or what you want to free the CPU up for prior to the Present occurring.
> 1 votes

---
Tags: c++, directx, pc, vsync
---


# Question
Title: Java tilemap not working, Think it has something to do with my image rendering
Hey can someone help me out, I've been trying to fix this for about 2 hours now, and I'm a noob when it comes to game programming and Java(only been reading and programming with it for a week now, this is my first non-tutorial driven attempt at anything).

Basically from my understanding my tile map class should be done correctly, here's the code in case I am mistaken: (file name is Map.java and its part of the tilemap package)

```
package tilemap;

import java.awt.Graphics2D;
import java.awt.*;
import javax.swing.*;

public class Map{

    private final int TILE_SIZE = 40;
    private Image wall;
    private Image floor;

    private int[][] map = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }};
    public Map() {
        wall = new ImageIcon("wall.gif").getImage();
        floor = new ImageIcon("floor.gif").getImage();
    }

    public void paint(Graphics2D g) {
        // loop through all the tiles in the map rendering them
        // based on whether they block or not
        for (int across=0;across<10;across++) {
            for (int down=0;down<13;down++) {

                if (map[across][down] == 1) {
                    g.drawImage(wall, across*TILE_SIZE, down*TILE_SIZE, null);
                } else {
                    g.drawImage(floor, across*TILE_SIZE, down*TILE_SIZE, null);
                }

            }
        }
    }
}

```

Now I think the issue is in this section here in my GameCanvas.java:

```
public void gameLoop() {
        boolean gameRunning = true;
        long last = System.nanoTime();

        // keep looking while the game is running
        while (gameRunning) {
            Graphics2D g = (Graphics2D) strategy.getDrawGraphics();

            // clear the screen
            g.setColor(Color.black);
            g.fillRect(0,0,1000,1000);

            // render our game objects
            map.paint(g);

            // flip the buffer so we can see the rendering
            g.dispose();
            strategy.show();

            // pause a bit so that we don't choke the system
            try { Thread.sleep(4); } catch (Exception e) {};
        }
    }

```

And the full GameCanvas.java in case its else where:

```
package tilemap;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

import tilemap.Map;

public class GameCanvas extends Canvas {

    /** The buffered strategy used for accelerated rendering */
    private BufferStrategy strategy;

    /** The map our player will wander round */
    private Map map;

    public static void main(String[] args) {
        new GameCanvas();
    }

    public GameCanvas() {
        Frame frame = new Frame("Tile Map Example");
        frame.setLayout(null);
        frame.add(this);
        frame.setSize(500,500);
        frame.setResizable(true);
        frame.setVisible(true);

        createBufferStrategy(2);
        strategy = getBufferStrategy();

        map = new Map();

        // start the game loop
        gameLoop();
    }

    public void gameLoop() {
        boolean gameRunning = true;
        long last = System.nanoTime();

        // keep looking while the game is running
        while (gameRunning) {
            Graphics2D g = (Graphics2D) strategy.getDrawGraphics();

            // clear the screen
            g.setColor(Color.black);
            g.fillRect(0,0,1000,1000);

            // render our game objects
            map.paint(g);

            // flip the buffer so we can see the rendering
            g.dispose();
            strategy.show();

            // pause a bit so that we don't choke the system
            try { Thread.sleep(4); } catch (Exception e) {};
        }
    }
}

```

I think the issue is when I go to draw/paint the screen there's something I'm not taking care of correctly, or maybe I'm not calling the right method (I've seen like 3 ways to draw to the screen, Canvas (which I think I'm using), JFrames/Jpanels, and OpenGL(which I have no idea about))

Please let me know what the issue is if you can spot it, cause I really have no idea without an compilation error poping up.

Thank you!

# Answer
In your constructor, try `this.setSize(500,500);`, and you might also need `this.setVisible(true);`. If that still doesn't work, instead of giving the frame a null layout, try giving it a border layout and add `this` in the `CENTER`.

I wonder whether ImageIcon is not returning a proper image; try following the trail on Reading/Loading an Image.

Looks like you're using BufferStrategy correctly. You could try commenting out `g.dispose();`, but I think that's correct.
> 1 votes

# Answer
I see an out of bounds exception. Try changing 2 lines to this:

```
        for (int across=0; across<13; across++) {
            for (int down=0; down<10; down++) {

```
> 1 votes

# Answer
You're not setting the size of the Canvas before you create the buffer strategy.

```
this.setSize(500,500);

```

Also, you have an out of bounds exception, which d33j has already pointed out.
> 1 votes

---
Tags: 2d, java, rendering, tiles
---


title: How did you learn DirectX 11?

text:
# Question
Title: How did you learn DirectX 11?
How did you learn the DirectX 11 API? MSDN documentation, tutorials, blogs, sample applications, books, etc?

# Answer
Have you tried the documentation & samples comes with DirectX itself?

yeh, its true that MSDN is perfectly capable driving someone crazy. :)

Here is one I like:

http://www.rastertek.com/tutindex.html

there is a book that *will be* released on July 18 this year,

Practical Rendering and Computation with Direct3D 11

(Does ask which way to go, I'm no DirectX guy)
> 3 votes

---
Tags: books, directx11
---


# Question
Title: Error inserting new pass entry into PassGroupRenderableMap
I started playing around with terrain and I am getting this assertion in

`QueuedRenderableCollection::addRenderable: "Error inserting new pass entry into PassGroupRenderableMap"`

I am trying to find out what I have done wrong, but it is hard, so perhaps someone has any idea of what may it be.

I can reproduce it easily on my engine and my scene consists only of:

* 1 terrain page
* 1 mesh (highlander house)
* 1 directional light

If I reload the scene and look again at the house the assertion fires and it is very strange. I have tried to debug the code and the only reason for the assertion to fire that I have found is the hash being changed after the node was inserted on the map.

Any ideas how can I find a solution to it? Which data and information I can provide to help debug this?

Also I have seen in the forum some posts about this assertion, but no one that I have seen explain ways to debug or to fix it.

Ogre version 1.7.1 Windows 7 render Direct3d 9

# Answer
> 2 votes
Here is a bug report with a workaround, probably the same issue?

It was discussed here in the Ogre Forum.

---
Tags: c++, ogre, terrain-rendering
---


# Question
Title: What's the best control scheme for an arena shooter on a touchscreen phone?
I am developing Android an game. It's going to be a top-down shooter with stealth features. I am now thinking about how to the make controls. Most top-down games are now twin stick (joystick on the left and right sides) but I need more buttons (for choosing weapons, commanding your squad, and using skills).

So here are my ideas:

* Two (virtual) sticks like in other games, when you tap somewhere on the display, a circle with buttons appears, where you can choose abilities or weapons.
* One stick on the left side for walking, shoot where the second finger is pressed, weapons and skills on the right side.

What do you think is the best? Or do you have any other idea? I want to choose the most intuitive and simplest.

# Answer
Mouse and keyboard, I love you!

Look at the competition, that has got to be as good as any advice you can get here. It sounds like you have put good thought into it, all the options you mention sounds reasonable. But a lot of it is down to testing. You might spend a lot of time redesigning the interface, but it's a crucial element, so it's worth it, despite the lack of tangible content to show for the time spent.

The best advice I can give:
You can adapt the interface to the game, or you can adapt the game to the interface. There is only so much you can do with a phone as the interface, and while exploring the options is certainly worth it, at some point you have to face the fact that certain game concepts are too complicated for the interface. Is the squad really that important for the gameplay? If you can't make it work well, maybe you should just drop the feature.
> 4 votes

# Answer
As it stands, your game may be too complicated for a touchscreen phone.

*Dual virtual sticks barely work*, and most shoot-em-ups on phones have been moving away from them, switching to auto-fire and drag-anywhere to move. (We've had a question about this in the past, and Cave, Taito, and everyone else have only continued down this path since it was asked).

*Shooting where the player is pressing does not work*. Fingers are too big and completely cover targets.

That being said, here are some basic suggestions:

* Move or aim via the accelerometer. If movement, probably clamped to e.g. 16 directions; if aiming, probably with some auto-aim adjustment.
* Tap to target, and weapons automatically track the active target.
* The player can move or shoot, but not both.

These all require planning ahead in your game design. You can't just bolt them onto a standard twin-stick shooter and get a good game. As a result, you probably can't just bring a standard twin-stick arena shooter to a touchscreen mobile device.
> 6 votes

# Answer
This may not be the answer you're looking for, but to be honest different people find different control schemes comfortable. Many iOS games I've played allow the user to select a control scheme from many different available ones. I believe you should implement the most common control schemes for top-down shooters and allow the player to choose the one he's more comfortable with.

That said, my favourite control method for these kind of games is the traditional "two sticks" setup.

You could also try using motion control (if your phone supports it) instead of buttons to activate special abilities. A fine example is using the "star power" in Guitar Hero by raising the guitar controller.
> 0 votes

---
Tags: 2d, android, touch, shoot-em-up
---


# Question
Title: How do I get access to the SpriteBatch service in my Sprite class using XNA?
I have the following `Sprite` class (leaving out everything that doesn't pertain to my question):

```
public class Sprite
{
    public Texture2D Texture { get; set; }
    public Vector2 Position { get; set; }
    private SpriteBatch _spriteBatch;

    public Sprite(Texture2D texture, Vector2 position)
    {
        Texture = texture;
        Position = position;

        // what code do I put here?
        _spriteBatch = ???
    }

    public virtual void Draw()
    {
        _spriteBatch.Draw(Texture, Position, Color.White);
    }

```

In my `Game1.cs` class, I register the SpriteBatch as a service:

```
protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
    Services.AddService(_spriteBatch);
}

```

Problem is, I don't know what code to put in the `Sprite` constructor to get the `SpriteBatch` object from the service. It doesn't have access to the `Game.Services` object. How would I load the service in this case?

# Answer
> 6 votes
It is completely a matter of taste.

You could pass your `Game` class instance into the constructor of your `Sprite` and access its public `Services` property. This is what `DrawableGameComponent` and `GraphicsDeviceManager` do.

You could pass `Game.Services` as an `IServiceProvider` into the constructor of your `Sprite` class. This is what the `ContentManager` class does. This has the advantage of not depending on an actual instance of `Game` (which you might not have if, say, you end up making a form-based level editor).

You could just pass an instance of `SpriteBatch` in the constructor of your `Sprite` class, but you can then only create `Sprite` objects after you create your `SpriteBatch`, which you can only do during and after `LoadContent`.

You could get especially lazy and create a globally accessible `Game` or `IServiceProvider` or `SpriteBatch` object and just use that (make it a static property on your game class). Advantage: quick and easy; Disadvantage: ugly!

You could pass a `SpriteBatch` instance into your `Sprite.Draw` method. This is pretty easy to do, and **is the method I use** for my gameplay classes - things that might have a `Draw` and an `Update` function (eg: a Player, or an Enemy, etc). One advantage is that it makes it both locally explicit and easy to modify the shared resources that the `Draw` function depends on.

But if your `Sprite` class is simply visual data for `SpriteBatch` (texture, position, etc), which is managed externally (having public setters for these properties, in your example, indicates that it might be), then I would recommend creating an **extension method** for `SpriteBatch` that does the drawing. This allows you to maintain the "feel" of the `SpriteBatch` object. Your extension method might look like:

```
public static void Draw(this SpriteBatch sb, Sprite sprite)
{
    sb.Draw(sprite.Texture, sprite.Position, Color.White);
}

```

Allowing you to draw it with: `sb.Draw(sprite);`. This method is preferable if you are not doing `SpriteBatch.Begin` and `.End` calls in your `Draw` method - as this allows it to work the same as `SpriteBatch`.

Those last two methods are the ones that I use and recommend myself.

**But** you have done something that strikes me as *pretty unusual* by making your `Sprite.Draw` method `virtual` \- indicating that you will be inheriting from `Sprite` and using it virtually. But combining this with public setters, and not calling `Begin` and `End`, makes for a pretty *confused* design.

If this is *really* the design you intend to use, then passing an `IServiceProvider` to the `Sprite` constructor is probably the best method to use as it allows for better encapsulation. (Just fix up those other things, which don't ;)

# Answer
> 3 votes
You have a couple of possibilities :

* Pass it in the constructor
* Pass the Services object in the constructor
* Pass it to your Sprite.Draw function

The right solution depends on your overall architecture.

---
Tags: xna, c#, xna-4.0, design-patterns, game-component
---


# Question
Title: Amateur / Independent (m)MORPG Team management
I would like to ask you all a question about how I should be going about creating and especially maintaining an Amateur/Independent team for quite a big project.

I'm specially interested about common pitfalls like who to Not accept on a team for example but also any information about how to build and maintain a team of non (or very little) payed people for a project that might advance but slo(oo)wly.

Oh yes, before you downvote me for wanting to create a MMORPG, I already have created the game + server (up and running), coded the last 3 years by myself (ie. this is not a modified Ryzom or something likewise)

You can check it out here: www.mindoki.com

So now I'd love to build a team helping me out with things like creating talents, testing, making quests, taking care of the community, scripting, website (forum) etc. etc. etc.

For the story, a guy helped me for like 6 months creating a team doing graphics, plot and sound but not one of them was able to either follow a 'template' (using a texture set up and a pre made skeleton) or finish even Anything.

So how should I structure the "team", how should I recruit (should / must I handle all recruiting myself?) and what are the common caveats in such team management?

Thanks!

**\[EDIT\]** I removed the edit, it messed up the initial question (which is 'What's the Do:s and Don't:s in amateur team management')

# Answer
Questions about money and ownership aside, I have only one piece of advice that I found handy when dealing with a volunteer effort I worked with before:

If you want to build a ship don't herd people together to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea.

* Antoine de Saint-Exupéry
> 10 votes

# Answer
Well after a few minutes of play, I would say it's going to be hard to get people working for you without paying them a proper wage.

This kind of project really needs people that are fully motivated to work on it; the problem is that you've pretty much developed the game yourself and anyone helping out will probably feel much less 'involved' with the project and hence less motivated.

There are also a few points that have to be made :

* The game is *ugly* (no offence) - IMO people will be more reluctant setting aside their free time to work on an ugly game.
* The game is in french (and also with some spelling mistakes I might add :P) - You have done the right thing putting the site in english, but the main language really must be english in game.
* The game doesn't *seem* to offer anything **new** (I haven't tested it enough yet).

Overall I'd say you've done a great job, but it's a very personal game and I think it'll be hard for others to get on-board; that's why I suggest making the whole game more accessible.

I would also recommend that if you can't pay people, you need to find a workflow which makes it stupidly easy for people to add quests, translate stuff, etc. The big problem is motivation and competence. At first you'll have to review everything yourself, but as you get good contributors you can delegate that work.

I would also look into creating an SVN type hub to facilitate adding/modifying content and make clients able to immediately test changes if they so choose.

En tout cas chapeau, c'est un bel effort ;)
> 2 votes

# Answer
This is basically impossible, you can't make an MMORPG as a spare time project. I wouldn't know how you would get people to contribute anywhere near enough, but even if you could manage that you wouldn't be able to make them contribute the right stuff. Contributing content is one thing, making everything fit together another, and that is a lot of hard work requiring great skill, which no-one will do for free.

Don't expect to be able to do anything a lot bigger than what you can do on your own.
> 0 votes

---
Tags: mmo, management
---


# Question
Title: How do I access variables in the Game1 class from another class in XNA?
I'm trying to write a `SpriteManager` class in XNA, but I need access to the `Game` variables. For example, the `Game.Content` property would be very helpful in loading textures, and `Game.GraphicsDevice.Viewport` would be helpful in getting the window size.

For now, I have the following class:

```
public MainGame : DrawableGameComponent
{
    public SpriteManager<Enemy> EnemyManager { get; get; }
    public SpriteManager<Powerup> PowerupManager { get; set; }
    ...
}

```

I can think of three ways of getting access to these variables in the `SpriteManager` class:

1. Make my sprite manager class derive off of `GameComponent`. This would be ideal, except that my sprite manager is used in `MainGame`, which is a `GameComponent`.
2. Use `((Game) Game1)` to access the variables. However, doing this kind of cast is ugly and breaks encapsulation.
3. Pass everything down from `MainGame`. For example, `EnemyManager` needs to load a random enemy type each time it spawns an enemy, so instead of loading the textures in `MainGame`, pass `EnemyManager` the `Game.Content` property and let it handle texture loading. However, I'm not sure if this is the best way of handling the situation. I can't place my finger on it, but it just seems 'wrong' in some way.

I could use some advice on the best way of achieving this.

# Answer
> 3 votes
Don't do that - make the sprite manager a service instead.

# Answer
> 2 votes
Actually #2 isn't so bad (I will assume you meant to down-cast from `Game` to `Game1`). You can enforce the type being `Game1` in your constructor like so:

```
public MainGame : DrawableGameComponent
{
    public MainGame(Game1 game) : base(game) { }
}

```

You could even make a nice convenience property like this. It will always be safe, providing the underlying `DrawableGameComponent` doesn't do anything undocumented.

```
public Game1 Game1 { get { return (Game1)Game; } }

```

Or if you want to be extremely anal about not casting (and there is really **no need** to be), you could do this:

```
public MainGame : DrawableGameComponent
{
    public MainGame(Game1 game) : base(game) { this.Game1 = game; }

    public Game1 Game1 { get; private set; }
}

```

---
Tags: xna, c#, xna-4.0, sprites, management
---


# Question
Title: What Java library provides a high-level communication interface suitable for use in an action-game server?
I need to write a server for an action game, which needs fast communication with the client. There will only be one server, and I'll split the world in zones. The client will be written in Java using jMonkeyEngine and in my opinion I should write the server in Java as well. I don't want to implement any low-level features such as communication, reliable udp, etc.

Is Java the most appropriate language to write an action game server which will run on Linux? Is there a Java library which provides a high-level interface for network communication?

# Answer
> 6 votes
For an action game, you'll want a library that supports synchronization (keeps the players positions' in sync across all the clients and the server). Of course, you'll also want basic messaging features. With this in mind, here are a couple of Java libraries that might work for you.

1. SpiderMonkey. It's part of jME3, and I'm guessing it's one of the more popular networking libraries for jME. It supports sending and receiving messages, serialization, compression, synchronization via UDP, among other things. Also, it seems to be the standard networking library for jME games these days.
2. JGN. It's basically like the other libraries, but it's more mature. It supports synchronization, and a bunch of other features like remote objects, shared objects, and streaming. Although it is no longer being actively developed and it's difficult to get support, it's quite a mature library.
3. Kryonet. It supports RMI and basic messaging. The only problem with this is that it doesn't support synchronization, so it might be a little bit of a hassle. However, it seems to be quite active, so it might be more robust than the other options.

---

Just a note: It's probably better to have a server for each zone/map. With only one server JVM supporting the whole game, if anything goes wrong, the whole game will go down. If you have multiple JVMs running each zone/map server, one error won't bring down your entire game.

# Answer
> 1 votes
I would highly recommend using a commercial socket server (with a free version for development) for real-time games, they're built for scalability and have been optimised to handle a large number of concurrent users. We've developed socket servers for several of our games, but they never scale as well as commercial socket servers.

Commercial Servers:

ElectroServer 5 (Java)

Photon (C++)

SmartFox Server: www.smartfoxserver.com/2X/ (Java)

---
Tags: java, networking, multiplayer, server, linux
---


title: Culling for a 2D, platformer game?

text:
# Question
Title: Culling for a 2D, platformer game?
By culling, I mean, only rendering what is currently seen by the camera. In my game, nothing is tile based. Each object has a center point and that is where it is on the screen. The camera is simulated by doing glTranslatef before drawing anything on that layer.

Here are the constraints:

I have 6 layers. Each of these is an array of IRenderableEntity. Each layer has a scalar that it multiplies the camera position by to simulate Parallax Scrolling. Within these arrays, the object itself could be static or dynamic.

I'm not concerned with collision detection since Box2D takes care of this.

How can I only render what I see on the screen in a logerithmic manner (not n^2)

Thanks

# Answer
There are plenty of resources for culling techniques of this nature -- ideal search terms include phrases like "2D culling quadtree" and "2D spatial partitioning."

A basic approach will use frustum culling (the link describes a 3D approach, but in 2D this boils down to basically a rectangle-in-rectangle test) and a quadtree to partion space hierarchically -- the hierarchical approach allows you to trivially reject large batches of objects, testing only those that are near the viewable area. As long as you update the spatial partitioning structure as objects update, this is suitable for dynamic scenarios as well as static ones.

You may also be interested in this article on an alternative approach (although its old), or this article on using the slightly-more-advanced kd-tree for partioning space. See here for a handful of other scene management structures.
> 9 votes

# Answer
Basically, you use collision detection to detect a collision between whatever your objects are, and a rectangle which is the current view of the camera. If the two collide, the object needs to be rendered.

In order to not have to check this for every single entity on the screen, you should use spatial partitioning structures such as quad trees to reduce the number of collision tests that you have to do.
> 2 votes

---
Tags: c++, game-design, culling
---


# Question
Title: How do audio based games such as Audiosurf and Beat Hazard work?
*Note: I am not asking how to make a clone of one of these. I am asking about how they work.*

I'm sure everyone's seen the games where you use your own music files (or provided ones) and the games produce levels based on them, such as Audiosurf and Beat Hazard.

Here is a video of Audiosurf in action, to show what I mean.

If you provide a heavy metal song, you would get a completely different set of obstacles, enemies, and game experience from something like Vivaldi.

What does interest me is how these games work. I do not know much about audio (well, data-side), but how do they process the song to understand when it is settling down or when it's speeding up? I guess they could just feed the pitch values (assuming those sorts of things exist in audio files) to form a level, but it wouldn't fully explain it.

I'm either looking for an explanation, some links to articles about this sort of thing (I'm sure there's a term or terms for it), or even an open-source implementation of this kind of thing ;-)

EDIT: After some searching and a little help, I found out about FFT (Fast Fourier Transform). This maybe a step in the right direction, but it is something that does not make any sense to me..or fits with my physics knowledge of waves.

# Answer
The term you're looking for is signal processing/analysis There are lots of techniques involved but the fundamental one that those games make use of is Beat Detection. This tries to calculate the tempo of the song and where the beats in a measure are and hence place the obstacles the appropriate distance apart to coincide with each beat.

The way that the games know when to "kick in" etc can range from being very simple and measuring the amplitude (volume) of the waveform or something more complex like isolating the volume of certain frequencies and measuring their volume.

If you're interested, look into Digital Signal Processing to see how you can analyse waveforms, which is essentially what these games are doing in their loading phase.

These links are good to get you started:

Introduction to Sound Processing
Theory and Techniques of Electronic Music
Introduction to Digital Filters

Hope that helps :)

-Ray

EDIT: I just saw your edit regarding Fourier transforms and thought I'll add some insight into it, although I'm by no means an expert on it!

FFT is a way of calculating the actual Fourier transform of a waveform. Basically, if you load up an audio file into Audacity, you'll see the wave form with the timeline along the top, this is known as the *time domain*. The FFT will convert a signal from the time domain into the *frequency domain* (basically all the frequencies that occur within the audio).

This conversion is useful for spectral analysis. In a game example, if you were to do a Fourier transform, you could easily calculate the amount of high frequency occurrences in the audio, and from that you could add twinkly visual effects, stars, or something associated with typically high frequency sounds. For the low frequencies you could have big, gluttonous monsters moving in time to the bass sounds, etc.
> 30 votes

# Answer
Here is a great seven part tutorial series on this topic by Badlogic Games. They cover everything from the basics to implementation.

http://www.badlogicgames.com/wordpress/?cat=18

They try to mimic the Audiosurf algorithme with code and all.
> 7 votes

# Answer
The data that come from the analysis oft the spectral energy variation are enough to generate this kind of maps. Here the problem may be if there are too much data to process: not what kind of data are used, but how.

After seeing some videos, I'm starting to believe that the data are moved further in the feature-domain (time-domain -\> frequency-domain -\> feature-domain). The software generates data by using the spectral energy changes and try to recognise known features, then it use the information about the features to setup the map. Recognition can be done by clusterization, maximum likelihood, neural networks, Genetic algorithm and so on.

After completing the recognition, you have infomations like: *where* the feature if found in *time* and *frequency*, what *type* of featuature is found, the *velocity* the feature vector is moving and so on; you can use these data to feed a map generation algorimth, leaving room for improvements like making better recognition algorithms, recognize more family of features, extract more data, find new ways to "render" these data and so on.
> 0 votes

---
Tags: audio, procedural-generation, levels
---


# Question
Title: DirectX9 rendering missing in Release Build
I have a c++ application which outputs to screen using entirely DirectX9, running on Win7 64 Home.

It runs as normal in these circumstances:

* Debug Build, from within MSVC 2008.
* Release Build, from within MSVC 2008.
* Debug Build, by opening the compiled executable itself.

However, strange things happen when I run the compiled executable of the **release** build. The window is created as expected but no screen output. Nothing.

I can hear the sound working and the log file fills up. I thought maybe the working directory was wrong when running the executable but the log file reports the CWD is correct and indeed all filepaths to data files work.

I am stumped as to why my application will work fine in 3 of the four permutations, but not the most important one - the standalone release executable!

If anyone can contribute, I'd be most grateful.

Thanks

Si

# Answer
Attach the debugger to the version not started from within VS, and debug through to see what is going on. To help you catch the early part of the program, you can put a dialog box or \__debugbreak into the early part so you can attach early and see the DX surfaces being created and so on.

Martyn
> 2 votes

# Answer
the difference between running with the IDE attached at startup is usually that the state of the memory handed to you by the allocator is not the same. If I remember correctly, it's zeroed out or filled with garbage (I can't rememeber which as we don't use standard allocators any more).

Checking memory should be your first approach vector. Make sure all your allocations assume that the memory is dirty and initialise them.
> 2 votes

# Answer
Please use DirectX SDK Utilities - DirectX Control Panel and see if you are not getting an error.

Set Debug level in control pannel, recompile your application and you should see runtime errors in the Output window
> 0 votes

# Answer
Build your program with the highest warning level turned on, see if it catches any uninitialized variables.

Make sure that you're checking all return values from system calls.

Follow the advice to use the debug DirectX/D3D driver and watch its output to see what changes between the working code and the broken.
> 0 votes

---
Tags: c++
---


# Question
Title: Accessing archived assets - what are the options in C#?
We are looking to add an archiving system to our game, where the assets (textures, scripts, sounds, etc.) will be located and directly accessed from memory. The main requirements are:

* Files must not be compressed
* Archive must have an internal folder structure
* Individual files must be accessed directly from the archive without the need to extract them to the hard disk
* If an external API is used, it must be able to run on Windows, Mac and Linux ; optimally, it should be redistributable free of charge

Our game engine is in C#, and we are looking for a managed solution (i.e. no PhysicsFS). What could be our options in this case?

Could it make sense to implement the whole thing by ourselves, using FileStream?

# Answer
You can use Zlib .NET
> 1 votes

---
Tags: c#, assets, asset-management
---


title: AABB of rotated sprite?

text:
# Question
Title: AABB of rotated sprite?
Say I have a sprite. Its AABB is easy to find since I know the width and height. Say I rotate it 45 degrees, I don't think the AABB would be big enough to cover it, so I need a new AABB. How can I calculate the bounding rectangle of a rotated rectangle (given a center point, an angle, and its width and height)?

Note that OpenGL does the rotation so I do not have access to the vertex information.

What I'm trying to do is get AABBs so I can do 2D culling for rendering.

Thanks

# Answer
> 7 votes
The straightforward approach is to

* find the extents of the unrotated bounding box
* apply the same rotation matrix to those extents as you did to the sprite (but on the CPU, so you may need to employ your own matrix math here)
* recompute the AABB of the rotated extents (which should be cheap since there are only four).

It's possible to perform the operation in fewer calculations, if you are concerned about (or interested in) those sorts of things. For example, one (potential) technique for doing so is discussed here.

# Answer
> 1 votes
Consider a box centered at some point in space. Imagine a line from the center to the top-right corner. This length is effectively the hypotenuse of a triangle formed from taking the center of the box and drawing a line right and then up. These sides of the triangle are half-extents. In the picture, the red lines are the half extents and the blue line is the hypotenuse -- the distance from the center of the box to the corner. Call this blue line's length 'dist' If you compute the arctangent of ratio of the half extents (Y / X), then you can get the angle. From there you can simply linearly add Pi/4 to the angle (45 degrees), then use:

`newx = cos(newAngle)*dist;
newy = sin(newAngle)*dist;`

Repeat for each of the four points, and then find max/min boundaries of the AABB.

--

This is super tedious. The better way is to use 3x3 matrix representing rotation and translation. In effect, you take each of the four points, translate them back to origin by subtract the center's coordinates from them so that their new center is on (0,0), then rotate them. Finally, you translate them back to the real center. With the new set of points, once again, simply compute new the AABB for those points. Wikipedia has some great information about matrix math, especially how to do rotations, translations, and more using 3x3 matrices.

---
Tags: rotation, aabb
---


# Question
Title: Graphics capabilities differences between mobile and desktop/console platforms?
I would like to better understand the difference in capabilities between mobile and desktop/console graphics? What exactly are the limitations of a mobile device? What kind of operations can a high-end GPU do that a modern smartphone cannot do? It's clear that games in a desktop look much better but what is behind those differences? I am aware that the APIs supported are different (D3DMobile, OpenGL ES vs full direct3d and opengl), even XNA has the Reach and Hi-Def graphics profile. I can see some of the differences here:

http://my.safaribooksonline.com/book/programming/game-programming/9780132620185/reach-vsdot-hidef-chart/app01lev1sec1#X2ludGVybmFsX0ZsYXNoUmVhZGVyP3htbGlkPTk3ODAxMzI2MjAxODUvNDU1)

What is the impact in let's say a game, what kind of effects or visuals I cannot get in a mobile due to this limitations, and what's the reasoning behind them. What is the bottleneck or restriction that prevents mobile devices to produce them.

Any thoughts or good resources to read about will be very appreciated.

EDIT: I am aware of the price/power/heat/form factor restrictions imposed on mobile GPUs. What I am trying to get at is the implications of those differences. Let's say that you can't use some type or size or textures, or maybe there is a maximum number of polygons, or certain type of transformations are not allowed. And from that I would like to know the practical consequence (i.e. water looks less real, objects up close look pixelated, the lighting is more flat). I am just guessing, but I would like to know for sure. In short, I want to know if I were to do a game with all the features of a high-end gpu (for example, a DX11 compatible one), and write the same game for a phone. What will I be missing, and in terms of visual perception what would look different?

# Answer
> 6 votes
First, the interconnect between the GPU and the CPU is usually very narrow. For example, when developing for the iPhone, *memory bandwidtch* is a huge problem. People pack vertex data using 16-bit integers and use matrices to rescale them. For example, I used 0...1023 to represent \[0.0, 1.0\] range in OpenGL texture coordinate by applying a scaling factor of (1.0/1023.0) to incoming texture coordinates. This allowed me to use 1/2 of the bandwidth when submitting texture coordinates.

Second, the limited heat/power means a lower clock speed. That's pretty intuitive, but worth mentioning. This implies fewer shader units and slower speeds for each unit. However, that also extends to the speed of the video memory and sometimes means dedicated memory isn't even available because it would produce too much extra heat.

Third, architectural pipeline features. DirectX 11 / OpenGL 4.0 have features that require extra stages of the traditional programmable pipeline, specifically geometry shaders, tessellation shaders, hull shaders, etc. These extra stages mean more GPU die space and consequently more cost and heat. These features generally are used to add detail to scenes but aren't critical in implementing algorithms like lighting, shadows, normal mapping, etc. so they aren't really killer features like fixed function -\> programmable pipeline change.

Finally, mobile GPUs lack the generality of desktop GPUs. With technologies like CUDA, OpenGL, and DirectCompute aimed to solve non-graphical problems, GPU makers had to implement more general operations like integer operations, GPU mem pointers, 64-bit floating point values, etc. which require more hardware support. These features aren't really necessary for games and so they generally don't make the cut. More hardware features, even if you don't use them, have a $ and heat cost associated with them.

Really, everything that is said can be traced to power, heat, cost in some form.

# Answer
> 1 votes
Mobile/handheld devices are less powerful. Because they have to optimize the hardware configuration withing a reasonable price range.

But, Desktop is not like that. Its modular and doesn't come as a package that can't be upgraded. You can modify it based on your need. And you are paying for a certain hardware at a time so, you get more powerful machine biased to your demand. These things are not possible in mobile devices.

In case of console, though they are under powered(when you look at the numerical figures) with respect to Desktop PC but, their architecture is different and those machine are fully dedicated for gaming. So, those hardware don't have the overhead to run a general purpose application. That's why they perform better comparing with the same configuration PC.

But, recently handheld devices are getting more and more powerful, supporting many features. But, again you can't just put is stuff into a mobile just because you can. You have a power supply limit and you have to watch out for the price of it.

That's why you can't just stuff in your Intel Core 2 duo processor in your iPhone just because its smaller then you phone. It demands power & cooling system. A handheld device is not physically capable of supporting that.

**EDIT :** I haven't seen any mobile device supporting over OpenGL ES 2.0 but in PC you have OpenGL 4.1 features(with necessary hardware installed). For advance visual effects you need some features from the later versions of OpenGL. One of the most notable feature, Tessellation is only supported on OpenGL 4 supported hardware.(ES stands for Embedded device) And so far its not yet possible to create an hardware supporting OpenGL 4 in an optimized manner that can used with a handheld device.

---
Tags: xna, opengl, directx, mobile, gpu
---


title: How to enable GPU for flash player 11?

text:
# Question
Title: How to enable GPU for flash player 11?
I just install Flash Player 11 and SDK 4.5 (hero), and test it with a small program. But I find it is still using "software" to simulate 3D API, and

```
trace("driver info: " + _context3D.driverInfo);

```

output

```
driver info: Software

```

I'm using windows 7, directX works properly, and option "-swf-version 13 -use-gpu" is already added in compiler arguments.

Who can tell me how to enable GPU in Flash Builder?

UPDATE:

context3d is constructed as :

```
private var _context3D:Context3D;
...
_context3D = stage3D.context3D;

```

And wmode is set to direct in html.

# Answer
For some reason, you might have hardware acceleration disable. Right-click on an instance of the Flash Player in your browser and select settings. In the first tab, you should have hardware acceleration checked.
> 1 votes

# Answer
Maybe your graphics-card isn't supported by the new Flash player? There's some more information about graphics-card compatibility over in this thread in the Adobe forums.
> 0 votes

---
Tags: flash, gpu, flash-develop
---


# Question
Title: How do I implement a Camera in the PushButton Game Engine?
I am playing around a bit with the PushButton Engine for game development in Flash and have come across a need for a Camera like the Camera that follows Mario in Mario Games. Flashpunk has a nice implementation of it.

Does PushButton have it out of the Box?(I searched for it and didn't find, hence the question here). If not then if any of you have written a component for the same, or can guide in the direction, any help would be much appreciated.

# Answer
Well if you have searched for it, I guess it's not implemented. However, it's not extremely hard to do.

If you think about it moving a camera around is the same as moving the world around in the opposite direction. A camera implementation could be as simple as a Rectangle instance. On each frame, you would do something like :

```
world.x = - camera.x;
world.y = - camera.y;

```

If you want to follow a character in your world, it's simple as :

```
camera.x = character.x - camera.width / 2;
camera.y = character.y - camera.height / 2;

```

This will center the character in the screen (given that camera.width is equal to your screen width).

Note that this will not give you a nice camera movement. You might find some insight on good camera movement here : http://replicaisland.blogspot.com/2010/01/elusive-perfect-platformer-camera.html.
> 2 votes

---
Tags: 2d, camera, flash, actionscript-3
---


# Question
Title: Mapping rectangular texture on trapezoid-like shape
I have a problem with rendering rectangular textures on non-rectangular surfaces. While googling, I found a thread with person having a pretty similar problem: http://www.gamedev.net/topic/419296-skewedsheared-texture-mapping-in-opengl/

But in my case, I cannot be sure about surface's exact properties. It's not regular trapezoid, it can be slightly bent. Which means, that I cannot just calculate correct texture matrix, or at least I don't know how.

I've tried to render triangle fan-like shape, but it just changed the characteristics of final distortion.

# Answer
> 1 votes
Depends on what you are trying to achieve, you could define your figure in 3D space to make the distortion as suggested in the link.

If it's not 3D you are looking for then an applicable hack is to use a polygon "net", split the figure into a suitable number of small squares and you can do the transformation as you see fit. For some simple transformations it may be sufficient to stripe the figure using triangles that span the full figure in one direction but are thin in the other.

I suppose you could also use a custom pixel shader to achieve the same result.

# Answer
> 1 votes
You're going to have to recreate your shape as a 3D mesh and run it through a software renderer to get any decent output that isn't a single-purpose hack like the texture matrix solution. If you attempt this in 2D you don't have enough information, like you've noticed.

Let me introduce you to a great article on perspective texture mapping in software: tutorial on 3D software rendering

# Answer
> 1 votes
There is no easy solution to your problem. In common 3D graphics surfaces are composed out of triangles for a reasons (easy to use, always planar, etc..). Even when you order to draw quads GPU renders them as pairs of triangles.

Your problem comes from the fact, that it is impossible to properly split quad into triangles when they are not planar and/or their sides are not equal. It is clearly visible on your linked forum post pictures.

The only solution I could think of is tessellation. It can be done on different stages though:

* On modeling stage, you could ask your artists to use finer grid and manually split bent quads/trapezoids into triangles
* On uploading objects to GPU, you could split quads/trapezoids into number of smaller quads to reduce the distortion effect
* Also you could use GPU tessellation functions

The choice depends on your actual project.

---
Tags: opengl, textures, uv-mapping
---


# Question
Title: How relevant is PHP today for browser games?
I was the lead developer of 2 moderately successful browser games quite a few years back, and plan on working on a new game soon. At the time, I wrote them in pure PHP (no template engine or anything of the sort).

I'd like to start working on a new game, but have been out of the web development world for a while. Reading around, I hear a lot of good about Rails, Django, Node.js, etc., with which I have no experience (although I know my way around Python, Javascript, and the others quite well).

So my question is the following- if I were to go in my old ways and go with PHP again, would I be making things hard for myself? Would picking something more "trendy" have a real impact on my development?

In addition, does anyone have any pointers relating to specifically developing browser games with these more modern tools?

# Answer
> 13 votes
PHP is still relevant for browser games. There are tons of companies (Gameforge, Funzio, Goodgame Studios, etc.) that use PHP for their online games.

I think PHP and Java are most widely used, but learning something like Node.js and Python can be beneficial as well. It really depends on what you want to focus on. Learn new technologies/a new programming language, or create a game with the tools you already know?

As others suggested, you could improve your game-client by using technologies like HTML5 and JavaScript. For the backend you can still use PHP. That might give you enough new stuff to learn while you can still benefit from your PHP programming skills.

# Answer
> 5 votes
PHP is still relevant and widely used.

According to the TIOBE Programming Community PHP is the fifth most popular language. It was in fourth position last year. That decrease could simply be due to an increase in the amount of available technologies.

*I'm assuming there is some correlation between general programming language popularity and game programming language popularity.*

Rails, Django and Node.js are frameworks or libraries so comparing them with PHP won't work so well, instead you could compare them with PHP frameworks such as Symfony and CakePHP. If you're already confident with PHP and don't have experience with Ruby/Python it may be worth using one of these.

Most of these frameworks offer model-view-controller architecture that could speed up development and keep your code cleaner and easier to maintain.

# Answer
> 3 votes
The old brower games of the day have nothing in common with what you can achieve today with what's available.

The big question is about real-time; if you want to keep the same sort of game design as an old browser game, PHP should be fine. Thing is, the type of game was *defined* by the *constraints* at the time; I guess if you've already dabbled in these games, you'll probably want to take things a step further.

If you want to keep an older, static-time based game, you could very well keep with PHP and maybe make profit of the trendy *canvas* in **HTML5**. A step further could be to mix it up with a bit of *AJAX* to make things a bit more *'real time'*; you probably used this in your older games anyway.

I don't know specifics of the other tools you taks about, but I'm familiar with PHP/AJAX games, and with you base knowlege, and the new power of HTML5, I believe that any browser game should work pretty well for you.

Of course; this is taking for fact that you want to make quite a static game.

# Answer
> 0 votes
For more modern tool, you can pick a WebGL powered game engine. Most of them are driven by JavaScript. You can checkout this list, see if any of it fits your need.

---
Tags: browser-based-games, php
---


title: Randomize Sprite moment Help needed

text:
# Question
Title: Randomize Sprite moment Help needed
I am new to Android, I am developing a fighting game in Android with AndEngine. Now I want my enemies to mimic my player behavior and on base of score they should come up with different tactics.

I need to write an AI script. Please help me in that. I want to make my enemies intelligent that they can destroy my player and also engage him in game too.

# Answer
Given the amount of information in your question.

Run a random number generator. Input that value as a parameter to a function that generates parameters for your characters based on the input value.

Then use those generated values as construction information for your enemy character factory.
> 1 votes

---
Tags: game-design, android, game-mechanics
---


# Question
Title: How to protect source code when game is developed in HTML5/Javascript
> **Possible Duplicate:**
> How do you prevent your JavaScript / HTML5 web game from being copied or altered?

If a game client is developed in Javascript, the source code can be found in browser. It's dangerous, because it's easy to hack the game, and patent can't be protected.

Are there any good ways to avoid this, e.g Javascript can be compiled to binary file then browser load and run the compiled javascript?

# Answer
The bottom line is there's no bullet-proof way to protect your HTML5/Javascript code. Obfuscation and minification will act as a deterrent. Closure Compiler is one such minifier.

If you really want to prevent people from cheating, store the state of the game on the server and turn the web page into a presentation/input layer that communicates with the server.
> 10 votes

# Answer
> It's dangerous, because it's easy to hack the game, and patent can't be protected.

If a user hacks your game and cheats he ruins his own fun. The same can be done with desktop applications, it's just not as easy.

For the record flash applications are rather easy to decompile and hack aswell so most web platforms have this problem.

If a user can actively change public data by hacking with the client-side javascript then you have a vulnerability in your server. Any data which a user shouldn't be able to change should either live somewhere the user can't touch it (a server) or have a proper authentication portal in front of it so it can't be changed.
> 2 votes

# Answer
You can't stop people from reading your JavaScript, so consider that part of the game open-source. Design your game in such a way that seeing that code won't matter. Mostly this is done by only implementing the user interface, visuals, and sounds on the client-side; everything else in the game is done on your server and communicated between the client and server using AJAX techniques.

This exact same approach applies to Flash games as well, btw.
> 2 votes

# Answer
One of the first thing you can do to try to prevent people reusing your source code is to obfuscate it, meaning making it unreadable, thus very difficult to understand.

Then there's no javascript compiler, as it's interpreted in the browser (so you'd need to compile it to all existing browser).
> 0 votes

---
Tags: javascript, browser-based-games
---


title: Game development: Art vs Programming

text:
# Question
Title: Game development: Art vs Programming
I'm a programmer and would like to get some perspective on the art / content creation part of game development.

Comparing a 2D platformer like Super Meat Boy and a high-end game like Crysis 2, what do you think:

* What is harder to do / more likely to cause the project to fail: Art or programming?
* Which will consume more time and take more people to work on?

# Answer
> 3 votes
I think you're attacking the question from the wrong angle. What will cause a project to fail is a poor understanding of the field, lack of funding, loss of interest/morale in a team. In other words, given an infinite supply of labor, time, and money, any project of any size can theoretically succeed. If you want to know more about what causes of failures for projects are, then search explicitly for that.

To narrowly define a game as "Art + Code" and ask which is more important is kind of like asking in the food service industry, "Which is more important in the success of a restaurant, food or spices?" I think you would be better off understanding all of the parts that go into a successful game development + launch and then trying to find points of failure in there.

# Answer
> 2 votes
Have you seen post mortem discussions? Any answer will depend on the type of game and you're not going to get any good answer to the "what is harder" question, that's so very subjective. Plus "fail" is a s

I don't think that these are answerable questions, all projects carry risk across both those axes and the two examples given are so wildly different any comparison will be manufactured and not a valid observation in my opinion.

---
Tags: software-engineering, art, planning
---


# Question
Title: Find a unit vector exactly halfway between two connected line segments
Seems like a quick and easy question but I haven't been able to find exactly what I'm looking for so:

How to calculate a unit length vector that is pointing along the line which is exactly 50% of the angle of two connected line segments?

A picture speaks a thousands words (that are also better than my explanation!)
So basically I want to calculate the blue unit vector given the two red line segments (which are actually 3 points and are therefore guaranteed to be connected)

The red segments are of arbitrary length, and the result doesn't have to be a unit it would just be easier for me.
It would also be handy to have a way to force the resultant vector to point in a certain direction (relative to the input segments), this isn't essential as I think I can work this one out - as the input line segments ultimately form an n-gon.

Any examples would be ideal in C++ please, but other languages welcome.

Many thanks for any pointers.

# Answer
Create and normalize two vectors from your red segment, starting from their comon vertex, then add the results (component by component). Then you can normalize the output if you want to get a unit vector.

The problem is that you'll always end up is the second case, because the angle between 2 vectors will always be less than 180°. But then of course you can just create the opposite vector and see which one suits better your purpose.

Also there's a special case when both vectors are aligned and the average will be 0 (but you can easily detect it).
> 13 votes

# Answer
I think you can get the direction to be consistent by treating this as if you're generating a 2D vertex normal. That is:

1. Take each of the red vectors, swap the x and y components and negate one of them to create the normals.
2. Normalize them.
3. Sum those two vectors, and renormalize.

You'll probably also want to test for the case where the two red lines are overlapping each other - the final renormalization will try to divide by zero there.
> 1 votes

# Answer
Let A and B be your vectors:

The summing vectors do not need to be unit vectors but simply equal in length so, if |A| \>= |B|, you can:

which is more numerically stable since you have only a fraction and the bigger denominator

The same result can be obtained by substraction, once again the vectors has to be equal in length

This works only for non-convex angles; you can simply test if your angle is convex and multiply H by -1
> 0 votes

---
Tags: c++, 2d, mathematics
---


title: Where & How to start?

text:
# Question
Title: Where & How to start?
I want to start a new development of a Online 3D Card Game.

I have alot of expirience in C# .NET and Sockets and everything.

I started to play with XNA Game Studio, but i found it a mass.

No Visual Help like in any other Game Engine or like in Windows Forms.

My question is that, i dont know where and hwo to start on the XNA Game Studio, there are not alot of tutorials on the web, and if there are some they are very old.

So i thougt of moving to my favorite Workspace, a normal Windows Forms app with a server managed in a Console Application.

Should i stay with XNA? or go to Windows Form?

And if i go to Windows Forms, will i be able to use 3D objects there? and use some features from the XNA Framework by importing the librarys ?

--

Lets say my game will be 2D does Windows Forms support a game loop? Does it support Full Screen? Does it gives the option to fully redesign so it wont look like Windows Forms app?

# Answer
There are tons of books that you can find on Amazon to get you started. Just search 'XNA' on Amazon, and grab the first book that interests you. One title I highly recommend is XNA 4.0 Game Development by Example: Beginner's Guide by Kurt Jaegers. He'll walk you through several games step by step, the best way to learn, and most fun, in my opinion. You'll even be able to reuse the code in those examples in your own projects. This will only teach you 2D game development in XNA, however. If you want to do 3D, you'll need to graduate to other books and begin to study 3D math, another major topic that's an absolute must to understand before doing any type of 3D graphics programming.

I don't know what the design of your "Online 3D Card Game" is, so I don't know what you require. But if it needs to be in 3D, and more complex than images in a PictureBox object, I'd seriously do it in XNA. WinForms would not be the proper environment to fulfill your game design. If you decide to do completely 2D, then yes, WinForms can support a game loop, if you code one. At its core, a WinForm application is nothing more than an empty Window.
> 7 votes

---
Tags: xna, c#, .net, online, card-game
---


# Question
Title: How do you handle uneven tiles while rendering a tile map?
Here is what I want to do with my tile map that I am unsure of. As you can see the top walls are way larger then the bottom and side ones (this is also an issue with my corners which are odd shapes \[more like an L then a square\] as well as larger then the 40x40px that my current tiles are).

I have also attached the tile sheet I am using for the tiles to show you what the corners and tops look like compared to the rest of the tiles.

What I’m thinking is I might be able to just draw them using the same array I have if I use the tiles width and height instead of a set WxH? I dont know how well this will work, but were the blocks that will have different values will be blocks the player/NPCs can’t step on then it may not be an issue, again I’m not even sure if that is a viable solution.

My code in case you want to see how I'm currently handling it: Map.java (pastebin) (edit:im not handling it, meant how I'm currently doing the map)

tl;dr - how can I take take my 2d looking tile map and change it to have different size tiles? or is there a better way to do what I am trying to do? Is there a name of a method that I should be looking for while googling?

# Answer
> 19 votes
There are two standard ways of doing this.

* Break up your non-standard tile sizes into standard tile sizes. So those strips of walls become a "stack" of square tiles that you just know to place together in your level editor. Games like the early Final Fantasy games worked this way.
* Let any tile piece be taller than your standard tile height. Align tiles to the bottom of your tile rectangle, allowing any extra to draw higher than the usual tile height. When drawing your map, you draw tiles starting from the back (the tile squares higher on the screen), and ending with the bottom tiles (the ones at the bottom of the screen). This ensures that tall tiles in the foreground are properly overlayed on top of tiles in the background. Note that in this approach, your tiles are still limited to a single tile in width.

You can do either or both of these approaches. Even games which do the "break up into stacks of tiles" approach will often allow some objects (trees, etc) to break the tile height limits, and just enforce a top-to-bottom map draw ordering in order to make sure everything layers correctly.

# Answer
> 2 votes
Slice and dice your odd sized tiles to fit the standard dimensions. The whole point of a tile map is that you get a lot of speed and utility by same-sizing everything.

---
Tags: 2d, java, tiles, maps
---


title: Spell Effects/Shaders

text:
# Question
Title: Spell Effects/Shaders
I want to be able to achieve spell effects that cause a fragmenting/discoloring effect on the sprite. The first couple seconds of this video http://www.youtube.com/watch?v=HNCFh7mkvuc shows what I mean. When the enemy gets hit by an electric attack, the effect I'd like to achieve activates (in yellow).

I'll have to use shaders to do this (if I don't, other, practical ways to do it would be extremely helpful). I have no idea where to start with a shader like this (beyond the obvious - using time and base color as parameters), and was curious if someone had something similar I could use as a base, or had a good idea where to start. I know the basic of glsl, but was hoping to spare myself some pain if someone has something like this already or could provide a starting point.

Any help would be appreciated,

thanks

Just to clarify, I'm looking to apply this against a 2D texture in OpenGL using glsl shaders

# Answer
> 5 votes
Looking at the animation, the enemy seems to flash straight to yellow, and it king of 'melts' downwards over time. If you look, the darker and lighter parts of the sprite are inversed during the fade.

I would personally use a shader with the base colour and the time as uniforms.

To tint the sprites colour to yellow, you can first convert it to grayscale :

```
grayscale = (0.299*red + 0.587*green + 0.114*blue)

```

Then simply multiply it by your input colour; here, yellow.

For the fade over time, you could try saturating the grayscale by multiplying it by a base colour over time, say gray, and don't clamp it, make it loop. You could add an effect from 'top to bottom' by also multiplying by `time * uv.y`.

You could make this more interesting by using a smoothed perlin noise texture to add randomness.

This is just a quick idea, so I don't know what it would really look like.

I would prefer using shaders that changing the palette (even though that's a great idea) because it is more suitable to an effect that is useable on different enemies, each with their own palette.

# Answer
> 5 votes
An old trick is to use color indexed images and cycling the color table for some pixels (this gives pretty good animations, you can see an example here and it's explained there.

Using the same idea, you could use simple hue shift or even color mapping in a shader.

Of course to have more control on the graphic output, i'd suggest an animated sprite (ie : making an image sequence for your effect).

# Answer
> 3 votes
I've created something like it in 3d. Youtube movie is at http://www.youtube.com/watch?v=-j442OTfSmM . The trick behind this is to apply a selected color from a gradient to your object, moving through the gradient based on location and time. In other words, if the effect starts from the top, you use the color from the end of the effect at the top and the start of the effect at the bottom to make it appear as if it's going down. You also add a little bit of perlin noise based on the local x/y/z coordinate to get a slightly more perturbed effect - makes it look less synthetic. All three effects are in fact the very same effect routine, just different locations, speeds, gradients and so on.

I can post the code online tonight (in 8 hours or so) if it would help you. It does look a lot better on 3d models as they have depth information, making the effect look like it's not a flat moving image :-).

# Answer
> -1 votes
That effect is 2D frame by frame pixel art.

You could achieve something similar but I do not think it will be possible emulate that exact effect without doing it manually in a raster art program.

---
Tags: c++, opengl, shaders, glsl, graphic-effects
---


title: 2D AI Engines/ Resources?

text:
# Question
Title: 2D AI Engines/ Resources?
i'm wondering if there's any 2D AI source code or engines out there. I'm inspired by the Euphoria engine, and want to use whatever is already out there to make something like it in 2D, where the characters can move left and right, and attempt to preserve themselves. The only new feature i would want to add on is ability to *learn from common results after an action.*

I'm thinking the way it would work is you attach some AI to a character, and it determines movement/detection based on the number of arms, legs, joints, restrictions, and other movement-related body parts.

*anything relating to AI would probablly be helpful as i've never worked with it:*

**How do you guys suggest i get started? *(Btw: i'm using box2D/ SFML at the moment)***

oh yeah and preferably open source =)

# Answer
What it seems you want is completely procedural character locomotion, I doubt very much that this exists in free-interwebs space.

In games like Spore, the locomotion is partially procedural, this means that you already need base data to say what kind of movement each limb can produce, etc. You could really take this as far as you want, the easiest is to start with saying that a character uses his legs for walking, and go from there.

Ken Perlin does research on actor movement and expression.

Here is a semi-procedural (3D) walking in Unity : http://runevision.com/thesis/

And a 2D version : http://blenderartists.org/forum/showthread.php?217356-Procedural-Bipedal-Locomotion-Animation-System

As you can see, the aim is adaptability to a terrain and both use a basic knowledge of how a person walks. The Euphoria engine works in pretty much the same way; simply put it's a mix between ragdoll physics and animations.

On the other end of the spectrum, you could give a creature limbs that can move in a certain way, and let physics show what the end result is.

The hardest part would be to let your creature learn from his mistakes, typically using a Neuronal Network, so it can learn how to walk faster, with more stability, etc.
> 4 votes

# Answer
Its not exactly AI you should be looking for. Its (Human) Motion Synthesis.

Euphoria is the only product is the market that can do so. Googling, bring up some research result, but they are 3d. So, for 2d I think writing your own might be the only solution.
> 2 votes

---
Tags: c++, 2d, architecture, ai, box2d
---


title: Moving from XNA to Android

text:
# Question
Title: Moving from XNA to Android
I've been using XNA to learn game programming for some time, and I'm interested in moving to Android. Having said that; the learning curve to get started seems to have ramped up exponentially. I have a working knowledge of Java (started with it before learning C#). Is there an intermediate step I should take in order to prepare myself for working with Android game programming? And are there any resources that are geared toward moving from XNA to Android?

# Answer
> 4 votes
You could try using MonoGame or wait for ExEn they are both ports of XNA to alternate platforms.

# Answer
> 2 votes
I don't have enough reputation point to comment, but posted as an answer anyway,

this link might be interesting for you android-experiment-porting-my-xna-game

# Answer
> 1 votes
Unity is also an idea. You can script in C#, JavaScript or Boo so it would be that much easier to code in it since you already have some XNA experience. It's not free, though.

# Answer
> 0 votes
Honestly, the best thing to do is to just go for it. Start off small, you have some experience in XNA and it shouldn't be too difficult to apply to a Java environment. Having said that, the graphics side of things can be a little bit hairy but there are lots of tutorials around if you just search for Android Game Development Tutorial.

One such tutorial is here. It's originally in German, but the Google translation doesn't seem to be too bad and it looks fairly comprehensive. There are the odd German phrases in there, but it looks like you can work out what they're saying most of the time.

You could also develop for Windows Phone 7 in XNA 4 to get a feel for developing for mobile devices so that experience could port over to Android too.

Good luck!

~Ray

# Answer
> 0 votes
A lot of the algorithm design you've applied in XNA will transfer over to virtually any programming language. The things that change will be program structure (slightly) and use of a different graphics API to achieve things like drawing. XNA does a lot of the low level boilerplate code for us, thankfully, so you may end up doing more low level coding in Java to achieve the same things you've achieved in XNA, such as game timing.

Killer Game Programming in Java would be a great place to start to learn how to do game and graphics programming specifically in Java. A lot of the core concepts will be immediately familiar to you, but you'll learn to how achieve everything using the Java API.

---
Tags: xna, c#, java, android, moving-platforms
---


title: non-linear interpolation

text:
# Question
Title: non-linear interpolation
I have an object, and i want to interpolate its position between two points over a given time period; but i dont want it to be a linear interpolation. I'm not sure if i'm phrasing this right.

```
vector posA; // Where we start
vector posB; // Where we end
float timeI; // An interval from 0 - 1

```

normally i would just do it linearly

```
vector currentPos = posA  + (posB - posA) * timeI

```

but i want the object to either:

* a) move faster at the start and slower at the end
* b) move slower at the start and faster at the end

Can anybody point me in the right direction

# Answer
One way to move slower at the start and faster towards the end would be to square the time:

```
vector currentPos = posA  + (posB - posA) * (timeI * timeI)

```

If you look at this graph (wolfram) you can see why this works.

To move faster at the start and slower at the end:

```
float t = 1 - timeI
vector currentPos = posA  + (posB - posA) * t * t

```
> 3 votes

# Answer
In video editing (and animation and other fields), the terms used for what you're talking about are "ease in/out" and "smash in/out", with "ease" meaning to begin or end from a standstill, and "smash" meaning to begin or end with full velocity.

Your existing algorithm gives you "smash in, smash out", since it maintains a constant velocity the whole way across the interpolation.

An easy way to get "ease in, smash out" is to square your fraction before performing the interpolation, like this:

```
timeI = timeI * timeI;

```

An easy way to get "smash in, ease out" is to square 1.0-fraction, like this:

```
timeI = (1.0f - timeI) * (1.0f - timeI);

```

An easy way to get "ease in, ease out" is to use a hermite interpolator:

```
timeI = (3.0f * timeI * timeI) - (2.0f * timeI * timeI * timeI);

```

If you need more control than that, you might consider actually moving your object along a hermite spline rather than interpolating. This would allow you far more precise control over starting and ending velocities for your object.

Copying hermite spline maths from my own code:

```
Vector3D Spline3D::PositionAtTime( float t ) const
{
    float tSquared = t * t;
    float tCubed = tSquared * t;

    float a = 2.f * tCubed - 3.f * tSquared + 1.f;  // 2t^3 - 3t^2 + 1
    float b = tCubed - 2.f * tSquared + t;          // t^3 - 2t^2 + t
    float c = -2.f * tCubed + 3.f * tSquared;       // -2t^3 + 3t^2
    float d = tCubed - tSquared;                    // t^3 - t^2

    Vector3D result = (a * m_start) +
    (b * m_startVelocity) +
    (c * m_end) +
    (d * m_endVelocity);

    return result;
}

```
> 3 votes

# Answer
What about Bézier curve? A segment is basically a first degree BC but you can construct second or superior degrees curves that are still segments. I suggest to you to use a cubic BC having the two control point laying on the segment itself. Doing so you can control the speed of the point when moves out the first position and when it reaches the final point.

These are the recursive formula for BCurves

As you can see the first is the linear interpolation of two point (a segment); the second is a "linear interpolation of segments" (a quadric), the third is a "linear interpolation of quadrics".

From this comes that when t is small B ≈ P1 and the tangent is P2-P1; when t is near to 1 B becomes P4 and the tangent is P4-P3.

You should not exaggerate with the lenght of P2-P1 and P4-P3 because the curve can elongate, going over the last point and then coming back.
> 1 votes

# Answer
Use a function of the time to produce a t value for your interpolation, for example an ease-in and ease-out function like this:

http://coc.dev77.com/2009/06/smoothness.html

or use one of the standard parabola results.

ease-in : t = time^2

ease-out : t = 1-(1-time)^2
> 0 votes

---
Tags: mathematics, interpolation
---


title: Let enemies blink when hit

text:
# Question
Title: Let enemies blink when hit
I would like to know how can I go about with an approach, that lets the enemies blink after they are hit with a shot/particle?

Is it better to pre-render colored enemies into an array for a better performance or is it just okay coloring them during gameplay?

For example, you can use the `colorMatrixFilter-` or `colorTransform-` methods for accomplishing this. Pre-rendering it (mentioned before) and storing the colored enemies inside of an array is an option also.

I ask because I'm not sure how those mentioned methods influence gameplay, especially for action games.

Which method is *usually* faster / *the accepted norm*? Are there any approaches I should avoid that will impact the gameplay?

# Answer
**If you are doing blitting with `copyPixels()` then you should definitely pre-render it inside flash when the program launches or the level is loading**

Instead of changing the enemies color when hit, you should probably make a hit animation for the enemies and just play that animation when hit.
> 1 votes

---
Tags: actionscript-3
---


title: Heightmap-based Terrain with a Road

text:
# Question
Title: Heightmap-based Terrain with a Road
What's the best way to implement a detail feature, like a road, on a heightmap-based terrain?

Update: It's a bit hard to see in the image, but the road descends from the top of the quarry to do its base.

# Answer
What is great with images is that they usually embed up to 4 channels (red, green, blue and alpha). As an height map needs only one dimension, you could just use the red channel to store the height informations (you still have 256 levels for the height), and then use other channels for other purposes (like using the green channel to map the roads, blue channel for water / moisture) etc...

Like this you could make sure that when you're building your terrain, the zones where a road should be built will appear flat instead of following the height gradient.
> 14 votes

# Answer
The way I do it is to separate the heightmap (I use floats for example, 513\*513) and splatmap (the "control-texture") that often needs a bigger resolution (I use 32bit bmps, 512x512).

The heightmap creates the mesh (the terrain, the triangles).

The control-map spans the whole terrain and each of its layers (RGBA) says how much say Stone,Dirt,Road etc. you should see On the terrain.

This way you can use an editor to a) create the terrain and b) Paint the terrain (with Rock,Dirt,Road etc.)

Do a quick goolge on 'painting heightmap', 'heightmap splatmap' and such for a more thorough explanation or download say Unity3D to check out how it might work in 'reality'.
> 1 votes

---
Tags: terrain, heightmap
---


title: GamePlay Patent

text:
# Question
Title: GamePlay Patent
Do you know any patents of GamePlay model? I mean behavior between User as Player and the System? In another words Patent of GamePlay rules. For example "when player's character dies -\> the system must raise him at last checkpoint". If you know any patent please provide a link:)

# Answer
> 10 votes
First, patent legislation varies by country. This GamaSutra article references a number of gameplay patents which have been granted in the US. (The article also recommends that game developers should patent their game mechanics, which I strongly disagree with, but that's another matter entirely.) Specifically:

> 1. United States Patent No. 6,604,008, entitled “Scoring based on goals achieved and subjective elements,” and assigned to Microsoft Corp., describes a method of determining points to be awarded to a player, where the points are based in part on style. (Hint: Speed through the town of a certain caped crusader)
> 2. United States Patent No. 6,695,694, entitled “Game machine, game device, control method, information storage medium, game distribution device and game distribution method,” and assigned to Konami Corporation, describes a game method that detects whether a player has placed his/her foot on a plurality of step positions, and calculates an amount of energy consumed by the player. (Hint: Groovy!)
> 3. United States Patent No. 6,200,138, entitled “Game display method, moving direction indicating method, game apparatus and drive simulating apparatus,” and assigned to Sega Enterprises, Ltd., describes a game method in which movable objects automatically move away from an approaching character. (Hint: Fare approaching!)
> 4. United States Patent No. 6,729,954, entitled “Battle method with attack power based on character group density,” and assigned to Koei Co., Ltd., describes a method of calculating attack or defense strength of a character based on its proximity to other characters in a three-dimensional battlefield. (Hint: Shang, Zhou, Qin, Han, anyone?)

The enforceability of these patents is another issue altogether. Just because the USPTO grants a patent does not mean it will be held as valid in a court of law. The video game industry is young and has relatively few patents, so there are, to the best of my knowledge, few historical precedents to indicate what a judge might rule if patents like these were exercised.

# Answer
> 5 votes
Once upon a time Midway had a patent on "ghost cars" used to race against your previously recorded attempts.

There are more things in heaven and earth, Horatio, Than are dreamt of in your philosophy.

Gamasutra discussion on Ghost Cars

# Answer
> 4 votes
"Skip hard parts in a game (by pushing a 'hint' button) and let the game 'video-walk you through that part' (ie. skip it by seing how it can be done) :

http://kotaku.com/5127251/nintendo-patent-reveals-potential-paradigm-shift-in-design

By Nintendo O\_o

Among others: Namco patent on load-time mini-games (US Patent Number 5,718,632)

http://www.gamasutra.com/view/feature/3562/the\_designers\_notebook\_damn\_all\_.php?print=1

You can definitely, it seems, patent gameplay.

# Answer
> 3 votes
No, you can't patent a game play design. No one can can stop you from making Super Mario clone. They can stop you from calling it SuperMario or using their character design or soundtrack.

**Ideas cannot be patented, only processes.**

# Answer
> 1 votes
IANAL.

Gameplay mechanics cannot be patented, nor copyrighted. You can only patent implementations of them or copyright very specific details, like "A plumber named Mario", for example. You cannot copyright nor patent general game ideas.

---
Tags: game-design, documentation
---