# Question
Title: How to keep the questions in Math game application ?
I would like to create a simple Math game application in android phone but I don't know what kind of data storage which I should use to keep the sets of numeric for the questions. At this time, I am hesitating with the SQLite and text file. Please suggest me. And If you have any tutorial or example, please give me them.

Appreciate your help.

# Answer
> 5 votes
You have lots of choices with android. As the Luis has sated, SQLite or text files (XML, JSON). But you could also store the data in a key-value list, such as a dictionary list or storage list.

Depending on how complex the data is, and what works easiest for yourself will determine what is the best option

# Answer
> 5 votes
What kind of questions are you going to be asking in this application?

something like?:

```
1 + 1 = ?
6 / 2 = ?

```

any type of storage is possible, you can use a comma delimited file such that every line would have the question and the answer like so:

```
"1 + 1","2"
"6 / 2","3"

```

If you are going to use SQL then you can make a table with the Questions & Answers. You would have two columns "Question" & "Answer" same thing as above.

---
Tags: android, mathematics, storage
---


title: Polygon Collision Detection Android

text:
# Question
Title: Polygon Collision Detection Android
I am starting to try and figure out polygon collision detection in my Android game. I am currently doing pixel level collision detection and it just seems to be too slow (though it works). I was looking at this tool and it seems like it would be really handy to give me a set of vertices for my images. Does anyone have any ideas about how I should go about implementing this? Basically once I have a list of vertices that form a polygon, how can I detect if polygon A intersects polygon B? I can see that these vertices can be used easily with Box2D but I want to try to do this without Box2D first.

# Answer
Separation Axis Theorem
> 2 votes

---
Tags: android, java, collision-detection, graphics
---


# Question
Title: Level design: compute minimum time between two items for player traversal
Do any game toolsets offer a means of computing the minimum time it would take a player to move between two objects (or positions, more generally) in a level? I'm not asking about *how* one would go about calculating this, but rather just whether or not it has been done, and if so, examples.

# Answer
Starcraft 2 has a map analyzer:

http://www.sc2mapster.com/assets/sc2-map-analyzer/pages/analysis-details/

Calculating paths is not the only thing it does. It also gives information on the openness of the map, and other neat features.
> 6 votes

---
Tags: path-finding, tools, level-design
---


# Question
Title: As an indie developer, what should I learn about the business end of game development?
I assume I should look into intellectual property law, copyright law, and money management, but what else would be good to know? My ideal goal is to be able to handle all legal/monetary business internally, without hiring an outside lawyer.

# Answer
I'm also starting an indie development company. I'm not very experienced in this matter, but here is what I'm going to do:

Have a low-risk pay model (no-one gets paid a cent until the company has recouped the initiation costs of the project, after that people get paid a percentage of money from that project depending on how much work they did, the company gets a percentage too)

Learn about bankruptcy - If you're in a business structure with Unlimited Liability it is important that you understand the risks you are taking. If the risk is too big you may wish to fork out extra to get a Limited Liability business.

Don't copy other people's stuff unless it is free domain or you have written permission. Even then be careful.

If you ever need to take someone else to court because they copied your stuff, hire a lawyer. Seriously.

It's not much info, but I hope it helps.
> 1 votes

---
Tags: business
---


title: libgdx sprite position relative to body

text:
# Question
Title: libgdx sprite position relative to body
Apologies if this is a reiteration, as I couldn't find another discussion of this over the past couple days.

***Issue:*** I'm using libgdx and box2d, and I'm currently updating the sprite's position to the body's current position every render call. Using a debugRenderer to see the bodies, I see that there is fairly noticeable lag between the movement/position of the body and the sprite that is being moved relative to it.

***Question:*** Is this lag normal, possibly to perform collisions ahead of time? If not, should I be manipulating/relating the positions differently?

Thanks in advance!

**\[Solution\]** This was a coding error on my part. Pointed out by a good reply below, I was updating the position of the sprite relative to the body and then stepping the physics. Thus never actually setting the sprite to the body's CURRENT position. Thanks!

# Answer
\[Solution\] This was a coding error on my part. Pointed out by a good reply above, I was updating the position of the sprite relative to the body and then stepping the physics. Thus never actually setting the sprite to the body's CURRENT position. Thanks!
> 2 votes

---
Tags: sprites, box2d, libgdx, body
---


# Question
Title: Is there a HTML/JS game engine/library that deals with things (HUD, menus, accounts, etc) other than the core gameplay?
I've been looking through the many HTML/Javascript game engines/libraries out there (many of which are found here https://github.com/bebraw/jswiki/wiki/Game-Engines). Most of them seem fairly focussed on the actual gameplay components: sounds, sprites & graphics management, doing 2D and 3D animations, collision detection, etc.

From what I can see most of them lack things to handle all the other stuff that goes into a web game such as menus, HUD, workflows of all the various scenes, management of various points/achievements and understanding of how level progression works with that, integration with Facebook or other external accounts, etc.

Does anything exist that adresses these sorts of pieces? I realize none of them are that difficult to achieve on their own but it would seem to be somewhat distracting overhead that gets in the way of the main game development focus, and is usually very similar from game to game.

Additional question: would something like this be useful, would you want/use it?

# Answer
Most of the functions you're asking about are handled by third party libraries (achiements, integration with Facebook, etc), or can simply be handled with jQuery and basic HTML and Javascript code (menus, HUD, etc). Or, they are things that come about as part of creating the game itself, and as such, aren't part of a standard library functionality (level progression, or workflow of scenes).

Additionally, all games are somewhat different, so most libraries usually only handle the major gameplay components. Handling more than that would result in a library designed for a very specific type of game, and while that's possible, it's less useful than a more generic library.
> 2 votes

# Answer
check http://cocos2d-javascript.org/

Its not completed yet and I am looking forward for this awesome framework to get completed. cocos2d have features to easily create menus, manage screen flows, apart from regular gameplay support. But for handling scoring, level data, facebook/twitter, I you need to go for your own implementation/respective libraries.
> 1 votes

# Answer
I'm always using backbone both for games and regular webapplications and the Views it offers might just be what you are searching for.
> 0 votes

---
Tags: javascript, html5, web
---


title: 2D bullet movement speed problem

text:
# Question
Title: 2D bullet movement speed problem
> **Possible Duplicate:**
> Moving from A(x,y) to B(x1,y1) with constant speed?

My problem is that I can't get my bullet movement right. The current update code I have for it is:

```
speedX = deltaX;
speedY = deltaY;

x += speedX / 100;
y += speedY / 100;

```

`deltaX` and `deltaY` are the distances needed to travel on each axis, which I get from the bullet starting coordinates and the mouse coordinates. I use the divider to prevent the bullet just teleporting to it´s destination.

The problem here is that when you press far from the bullet start point the bullet goes quickly. But when you click near the bullet start point it goes really slow. I can´t figure out what I should do to repair it.

# Answer
You'll want to include the time elapsed during a frame in your calculations if you want to maintain a constant movement.

```
float bulletSpeed = 100.0
x += bulletDirectionX * bulletSpeed * timeDeltaSeconds
y += bulletDirectionY * bulletSpeed * timeDeltaSeconds

```

Or if your bullet direction is stored as a velocity, rather than a unit length direction, then speed and direction are already combined:

```
x += bulletDirectionX * timeDeltaSeconds
y += bulletDirectionY * timeDeltaSeconds

```

The formula for updating position based on linear velocity, over time, when thought of as code is roughly:

```
position += linearVelocity * timeDelta

```

Where `position` is generally a 2D/3D vector representing a point, `linearVelocity` is a 2D/3D vector representing velocity in units per second, and `timeDelta` is elapsed time, generally in seconds, represented by a float or double (e.g. 0.016 is 16 milliseconds, which is the elapsed time you'll generally see when v-sync'd to 60 frames per second).

Now let's plug in some numbers for an example. We'll say that our bullet travels at 100 meters per second, and it's traveling in a direction of 1 x-unit and 1 y-unit. The first thing we'll need to do is convert the (1, 1), into a direction represented by a vector. We need our vector to basically be a line segment that is 1 unit in length, this will allow us to multiply that 1 by the speed of the bullet to get a line segment that represents how far the bullet will travel in 1 second.

If we picture the (1, 1) as sides of a right triangle then to figure out the length of the line connecting those sides we can just use the Pythagorean Theorem, which is:

```
a^2 + b^2 = c^2

```

and in our case:

```
(1^2 + 1^2) = (1 + 1) = 2.
2 = c^2, so √2 = c, which makes c ~= 1.414.

```

Now that we have the length of our vector (1.414), we then divide the each part of the vector by that length:

Our vector is `(1, 1), so (1 / 1.414, 1 / 1.414) = (0.707, 0.707)`.

We now have a vector (0.707, 0.707) that represents the direction the bullet travels. Now we want to factor in how far the bullet travels per second, which we said is going to be 100 meters per second. This part is simple, we just multiply each component in our direction vector by the speed of the bullet:

```
(0.707 * 100, 0.707 * 100) = (70.7, 70.7).

```

Now we have a vector (70.7, 70.7) that represents the velocity of the bullet, in units per second. If we say that our bullet starts at position (0, 0), then after 1 second our bullet would be at that position plus the velocity vector. This means that we can now just take that velocity vector and multiply it by any amount of time to figure out where our bullet will be. So each frame we just multiply the fraction of a second that has elapsed by our velocity, and add that to our position to determine where the bullet's new position is. Let's say that our game is running at 60 frames per second, that means that a single frame would be 1 second / 60, or (0.16667 seconds). Starting our bullet at (0, 0), let's see where that puts the bullet after a single frame.

```
position += linearVelocity * timeDelta
(0, 0) += (70.7, 70.7) * (0.16667)
(0, 0) += (70.7 * 0.16667, 70.7 * 0.16667)
(0, 0) += (1.1783, 1.1783)
(0 + 1.1783, 0 + 1.1783)
(1.1783, 1.1783)

```

So there we have it, our bullet went from position `(0x, 0y)` to `(1.1783x, 1.1783y)` in 1 frame.
> 1 votes

---
Tags: 2d, java, movement
---


# Question
Title: Is there documentation on XNA other than at MSDN?
MSDN documentation of XNA seems to be incomplete and/or bad. Is there another resource available? And by documentation I mean of the library/framework itself, similar to what UNITY, SFML, or SDL all have available.

# Answer
> 5 votes
You probably won't find documentation available that's as good or better than MSDN, any specific questions / problems, search here and elsewhere online and if you're still not sure post a question.

That said, take a look at the Education Catalog at the App Hub.
While not documentation, it provides many samples and lots of useful information.

Also, take a look at Shawn Hargreves' blog, there are many interesting posts relating to XNA.
There's also an index of older, useful posts.

# Answer
> 2 votes
Just to add to George's great answer:

The DirectX documentation (on MSDN) contains many additional details that the XNA documentation does not provide. XNA is a wrapper over DirectX, after all.

Often you can easily guess (or check using PIX or perhaps ILSpy) the underlying DirectX methods that XNA is using, and then look up the documentation for those to find out what you need.

---
Tags: xna, documentation
---


title: Is this feature copyright infringment?

text:
# Question
Title: Is this feature copyright infringment?
Say there is a card game and they have a feature that allows setting join requirement when hosting a game. These are: Only people I like, No one I Dislike, Invite Only, Everyone.

If I created a card game and had a similar join requirement feature with similar features: eg: Only Buddies, No Enemies, Invitation, Everyone, is this copyright infringement or is it just an idea and not an expression of one?

Thanks

# Answer
> 3 votes
Game mechanics can't be protected by copyright laws as far as I know. At least not where I live (Europe) and I think it would be similar in US as well. Only written documents (like books or story in games), music pieces and graphic assets can be protected by copyright... ok, I probably missed something, but I'm pretty sure you can't protect game mechanics.

---
Tags: game-design, game-mechanics, legal
---


title: Drawback of using multiple bind flags

text:
# Question
Title: Drawback of using multiple bind flags
As far as I understand Direct3D 11 I have to specify certain BindFlags in order to use a resource in a specific stage of the pipeline.

From my experience some combinations are more common like `BindFlags.RenderTarget | BindFlags.ShaderResource` for post processing effects. And I guess it could also be quite handy sometimes to set the ShaderResource flag for DepthStencilBuffers.

So I would like to know what is happening behind the scenes. What is the drawback of simply setting all of them? Would it be a minor performance hit? Or is as bad as an individual copy of the resource for every different flag?

# Answer
> 0 votes
Yes, most likely it will be performance hit (or memory usage increase). Set only those flags which you need.

---
Tags: performance, directx11, slimdx, assets
---


# Question
Title: Does the projection matrix flip winding order in right handed systems?
I am using a right handed coordinate system for my world coordinates (so, positive x goes right, y is up, and z is towards you).

However, after projection and the w divide, nomalised device coordinates range from \[-1,1\] on x and y, with x pointing right, and y pointing up, and z ranging \[0,1\] (or \[-1,1\] in OpenGL) pointing into the screen. This is a left handed coordinate system.

As such, wouldn't the winding order you need to use swap? If my models define front faces using clockwise winding, then it would seem that you must cull clockwise faces in order for the hidden faces to be removed after projection. I don't remember having to do this in XNA (where I wasn't calculating my own matrices and just left the defaults), so have I made a mistake in my reasoning here?

# Answer
> 6 votes
First of all, X points right, not left, in screen coordinates. But yes, the normalized device coordinates are a left-handed system. It doesn't matter for backface culling, though. From the OpenGL FAQ:

> OpenGL face culling calculates the signed area of the filled primitive in window coordinate space. The signed area is positive when the window coordinates are in a counter-clockwise order and negative when clockwise.

It only looks at the triangle in 2D, so if it's anticlockwise-wound in right-handed space before perspective projection, it'll still be anticlockwise-wound afterward; the reflection through the screen plane doesn't affect it. I assume D3D behaves similarly.

---
Tags: coordinates, projection, culling
---


title: Maintain speed in box2D body

text:
# Question
Title: Maintain speed in box2D body
I want to delimit my speed and to maintain that speed constantly, but it gets getting higher and if i apply the linear velocity it doesnt bounce :/, Here is te part of my code

```
double fx = .25f*Math.cos(Math.toRadians(rotation));
double fy = .25f*Math.sin(Math.toRadians(rotation));
this.getBody().applyLinearImpulse(World.toGameCoordinates((float)fx, (float)fy), this.bodydef.position);
this.getBody().setLinearVelocity(World.toGameCoordinates((float)fx, (float)fy));

```

What can i do to maintain the speed constant and it keeps bouncing

# Answer
> 1 votes
I am assuming that your code above is in an update loop (or in a callback)

In a physics engine you should never use anything similar to `set`. This is because the solver can no longer give you proper collisions (especially for a Continuous collision solver like Box2D). So your line:

```
this.getBody().setLinearVelocity(World.toGameCoordinates((float)fx, (float)fy));

```

Should not be there. That sets the velocity immediately and the ship will essentially *teleport* to the new position. As far as maintaining the current velocity goes, if you don't have any drag and you are not losing any energy in collisions, then you should never lose your initial velocity.

---
Tags: box2d, libgdx
---


title: Enabling multisampling in Irrlicht?

text:
# Question
Title: Enabling multisampling in Irrlicht?
I'm working on a little game that uses Irrlicht. I'm pretty new to Irrlicht and I was wondering how I could enable multisampling. The device driver is `EDT_OPENGL` initiated as such:

```
IrrlichtDevice *device = createDevice(video::EDT_OPENGL,
                                        core::dimension2d<u32>(800, 700),
                                        16,
                                        NO);

```

How do I enable multisampling?

# Answer
Here's a solution, but you'll need to call **createDeviceEx** instead of the current function.

You'll have to pass a **SIrrlichtCreationParameters** structure to the above function, with the AntiAlias member set to *true* (or another value ? It seems that the variable is an unsigned integer, and not a bool, never noticed that). Of course you'll have to define some other structure members in order to have the same IrrlichtDevice as the one in your question. ;)

Here's a piece of code if you prefer : (warning : I've not used Irrlicht since 1 year now)

```
SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
params.AntiAlias = true;
params.DriverType = video::EDT_OPENGL;
params.WindowSize = core::dimension2d<u32>(800, 700);
IrrlichtDevice *device = createDeviceEx(params);

```

See here for (unfortunately not much) information. (the Irrlicht doc is in fact not very helpful, unfortunately)

Hope this helps, good night ! :-)
> 4 votes

# Answer
Quick addendum to Minishlink's answer: `AntiAlias` is the number of samples to use in anti-aliasing. The following snippet comes from Irrlicht's COpenGLDriver.cpp.

```
// This value determines the number of samples used for antialiasing
// My experience is that 8 does not show a big
// improvement over 4, but 4 shows a big improvement
// over 2.
if(AntiAlias > 32)
    AntiAlias = 32;

```
> 2 votes

---
Tags: opengl, c++, irrlicht, antialiasing
---


# Question
Title: Linking nodes algoritm for Visual Design
I'm developing an editor for my game, and now it's time to make a visual scripting system to let designer modify behaviours.

This video shows what i have done and the problem

to resolve the link between nodes I'm using an A\* path finding, when a path is set, I add a penalization bonus to each cell of the path, to avoid using the same cells for other path.

I would like that the lines do not intersect unnecesarily.

is there any algoritm or idea that allows me to do this better?

# Answer
> 1 votes
You could check out GraphViz for some inspiration: http://www.graphviz.org/Gallery.php

The tool itself produces static images, but it has a variety of modes for connecting nodes with limited overlap. Also it's open source in case you're interested in studying one of the algorithms that they use. Good luck.

---
Tags: xna, c#, algorithm, path-finding, logic
---


# Question
Title: How to create a hexagon world map in PHP from a database for a browser based strategy game
I'm trying to create a hexagon world map for my PHP browser based strategy game. I've created a table in my database with the following data per row: id, type, x, y and occupied. Where type is the kind of tiles, which are defined in numbers. For example, 1 is grass. The map itself is 25 x 25.

I want to draw the map from the database with clickable tiles and the possibilty to navigate through the map with arrows. I don't really have a clue on how to start with this and any help would be appreciated.

# Answer
\*Edit: Fixed error in javascript that caused error on firefox *

*Edit: just added ability to scale hexes to the PHP source code. Tiny 1/2 sized ones or 2x jumbo, it's all up to you :)*

I wasn't quite sure how to put this all into writing, but found it was easier to just write the code for a full live example. The page (link and source below) dynamically generates a hexmap with PHP and uses Javascript to handle map clicks. Clicking on a hex highlights the hex.

The map is randomly generated, but you should be able to use your own code instead to populate the map. It is represented by a simple 2d array, with each array element holding the type of terrain present in that hex.

Click me to try the Hex Map Example

To use, click on any hex to highlight it.

Right now it's generating a 10x10 map, but you can change the map size in the PHP to be any size you want. I'm also using a set of tiles from the game Wesnoth for the example. They are 72x72 pixels in height, but the source also lets you set the size of your hex tiles.

The hexes are represented by PNG images with "outside the hex" areas set as transparent. To position each hex, I am using CSS to set each tile's absolute position, calculated by the hex grid coordinate. The map is enclosed in a single DIV, which should make it easier for you to modify the example.

Here is the full page code. You can also download the demo source (including all hex images).

```
<?php
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// :: HEX.PHP
// ::
// :: Author:
// ::    Tim Holt, tim.m.holt@gmail.com
// :: Description:
// ::    Generates a random hex map from a set of terrain types, then
// ::    outputs HTML to display the map.  Also outputs Javascript
// ::    to handle mouse clicks on the map.  When a mouse click is
// ::    detected, the hex cell clicked is determined, and then the
// ::    cell is highlighted.
// :: Usage Restrictions:
// ::    Available for any use.
// :: Notes:
// ::    Some content (where noted) copied and/or derived from other
// ::    sources.
// ::    Images used in this example are from the game Wesnoth.
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

// --- Turn up error reporting in PHP
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// --- Define some constants
$MAP_WIDTH = 10;
$MAP_HEIGHT = 10;
$HEX_HEIGHT = 72;

// --- Use this to scale the hexes smaller or larger than the actual graphics
$HEX_SCALED_HEIGHT = $HEX_HEIGHT * 1.0;
$HEX_SIDE = $HEX_SCALED_HEIGHT / 2;
?>
<html>
    <head>
        <title>Hex Map Demo</title>
        <!-- Stylesheet to define map boundary area and hex style -->
        <style type="text/css">
        body {
            /*
            margin: 0;
            padding: 0;
            */
        }

        .hexmap {
            width: <?php echo $MAP_WIDTH * $HEX_SIDE * 1.5 + $HEX_SIDE/2; ?>px;
            height: <?php echo $MAP_HEIGHT * $HEX_SCALED_HEIGHT + $HEX_SIDE; ?>px;
            position: relative;
            background: #000;
        }

        .hex-key-element {
            width: <?php echo $HEX_HEIGHT * 1.5; ?>px;
            height: <?php echo $HEX_HEIGHT * 1.5; ?>px;
            border: 1px solid #fff;
            float: left;
            text-align: center;
        }

        .hex {
            position: absolute;
            width: <?php echo $HEX_SCALED_HEIGHT ?>;
            height: <?php echo $HEX_SCALED_HEIGHT ?>;
        }
        </style>
    </head>
    <body>
    <script>

function handle_map_click(event) {
    // ----------------------------------------------------------------------
    // --- This function gets a mouse click on the map, converts the click to
    // --- hex map coordinates, then moves the highlight image to be over the
    // --- clicked on hex.
    // ----------------------------------------------------------------------

    // ----------------------------------------------------------------------
    // --- Determine coordinate of map div as we want the click coordinate as
    // --- we want the mouse click relative to this div.
    // ----------------------------------------------------------------------

    // ----------------------------------------------------------------------
    // --- Code based on http://www.quirksmode.org/js/events_properties.html
    // ----------------------------------------------------------------------
    var posx = 0;
    var posy = 0;
    if (event.pageX || event.pageY) {
        posx = event.pageX;
        posy = event.pageY;
    } else if (event.clientX || e.clientY) {
        posx = event.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        posy = event.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    }
    // --- Apply offset for the map div
    var map = document.getElementById('hexmap');
    posx = posx - map.offsetLeft;
    posy = posy - map.offsetTop;
    //console.log ("posx = " + posx + ", posy = " + posy);

    // ----------------------------------------------------------------------
    // --- Convert mouse click to hex grid coordinate
    // --- Code is from http://www-cs-students.stanford.edu/~amitp/Articles/GridToHex.html
    // ----------------------------------------------------------------------
    var hex_height = <?php echo $HEX_SCALED_HEIGHT; ?>;
    x = (posx - (hex_height/2)) / (hex_height * 0.75);
    y = (posy - (hex_height/2)) / hex_height;
    z = -0.5 * x - y;
    y = -0.5 * x + y;

    ix = Math.floor(x+0.5);
    iy = Math.floor(y+0.5);
    iz = Math.floor(z+0.5);
    s = ix + iy + iz;
    if (s) {
        abs_dx = Math.abs(ix-x);
        abs_dy = Math.abs(iy-y);
        abs_dz = Math.abs(iz-z);
        if (abs_dx >= abs_dy && abs_dx >= abs_dz) {
            ix -= s;
        } else if (abs_dy >= abs_dx && abs_dy >= abs_dz) {
            iy -= s;
        } else {
            iz -= s;
        }
    }

    // ----------------------------------------------------------------------
    // --- map_x and map_y are the map coordinates of the click
    // ----------------------------------------------------------------------
    map_x = ix;
    map_y = (iy - iz + (1 - ix %2 ) ) / 2 - 0.5;

    // ----------------------------------------------------------------------
    // --- Calculate coordinates of this hex.  We will use this
    // --- to place the highlight image.
    // ----------------------------------------------------------------------
    tx = map_x * <?php echo $HEX_SIDE ?> * 1.5;
    ty = map_y * <?php echo $HEX_SCALED_HEIGHT ?> + (map_x % 2) * (<?php echo $HEX_SCALED_HEIGHT ?> / 2);

    // ----------------------------------------------------------------------
    // --- Get the highlight image by ID
    // ----------------------------------------------------------------------
    var highlight = document.getElementById('highlight');

    // ----------------------------------------------------------------------
    // --- Set position to be over the clicked on hex
    // ----------------------------------------------------------------------
    highlight.style.left = tx + 'px';
    highlight.style.top = ty + 'px';
}
</script>
<?php

// ----------------------------------------------------------------------
// --- This is a list of possible terrain types and the
// --- image to use to render the hex.
// ----------------------------------------------------------------------
    $terrain_images = array("grass"    => "grass-r1.png",
                            "dirt"     => "dirt.png",
                            "water"    => "coast.png",
                            "path"     => "stone-path.png",
                            "swamp"    => "water-tile.png",
                            "desert"   => "desert.png",
                            "oasis"    => "desert-oasis-tile.png",
                            "forest"   => "forested-mixed-summer-hills-tile.png",
                            "hills"    => "hills-variation3.png",
                            "mountain" => "mountain-tile.png");

    // ==================================================================

    function generate_map_data() {
        // -------------------------------------------------------------
        // --- Fill the $map array with values identifying the terrain
        // --- type in each hex.  This example simply randomizes the
        // --- contents of each hex.  Your code could actually load the
        // --- values from a file or from a database.
        // -------------------------------------------------------------
        global $MAP_WIDTH, $MAP_HEIGHT;
        global $map, $terrain_images;
        for ($x=0; $x<$MAP_WIDTH; $x++) {
            for ($y=0; $y<$MAP_HEIGHT; $y++) {
                // --- Randomly choose a terrain type from the terrain
                // --- images array and assign to this coordinate.
                $map[$x][$y] = array_rand($terrain_images);
            }
        }
    }

    // ==================================================================

    function render_map_to_html() {
        // -------------------------------------------------------------
        // --- This function renders the map to HTML.  It uses the $map
        // --- array to determine what is in each hex, and the
        // --- $terrain_images array to determine what type of image to
        // --- draw in each cell.
        // -------------------------------------------------------------
        global $MAP_WIDTH, $MAP_HEIGHT;
        global $HEX_HEIGHT, $HEX_SCALED_HEIGHT, $HEX_SIDE;
        global $map, $terrain_images;

        // -------------------------------------------------------------
        // --- Draw each hex in the map
        // -------------------------------------------------------------
        for ($x=0; $x<$MAP_WIDTH; $x++) {
            for ($y=0; $y<$MAP_HEIGHT; $y++) {
                // --- Terrain type in this hex
                $terrain = $map[$x][$y];

                // --- Image to draw
                $img = $terrain_images[$terrain];

                // --- Coordinates to place hex on the screen
                $tx = $x * $HEX_SIDE * 1.5;
                $ty = $y * $HEX_SCALED_HEIGHT + ($x % 2) * $HEX_SCALED_HEIGHT / 2;

                // --- Style values to position hex image in the right location
                $style = sprintf("left:%dpx;top:%dpx", $tx, $ty);

                // --- Output the image tag for this hex
                print "<img src='$img' alt='$terrain' class='hex' style='zindex:99;$style'>\n";
            }
        }
    }

    // -----------------------------------------------------------------
    // --- Generate the map data
    // -----------------------------------------------------------------
    generate_map_data();
    ?>

    <h1>Hex Map Example</h1>
    <a href='index.phps'>View page source</a><br/>
    <a href='hexmap.zip'>Download source and all images</a>

    <!-- Render the hex map inside of a div block -->
    <div id='hexmap' class='hexmap' onclick='handle_map_click(event);'>
        <?php render_map_to_html(); ?>
        <img id='highlight' class='hex' src='hex-highlight.png' style='zindex:100;'>
    </div>

    <!--- output a list of all terrain types -->
    <br/>
    <?php
        reset ($terrain_images);
        while (list($type, $img) = each($terrain_images)) {
            print "<div class='hex-key-element'><img src='$img' alt='$type'><br/>$type</div>";
        }
    ?>
    </body>
</html>

```

Here is a screenshot of the example...

Definitely could use some improvements. I noticed in a previous comment you said you were familiar with jQuery, which is good. I didn't use it here to keep things simple, but it would be pretty useful to use.
> 38 votes

# Answer
You should write a small javascript tile layout engine that maps the database tile coordinates into a view on the web page, because this lets you outsource the cpu processing time to the players computer. It's not hard to do and you can do it in few pages of code.

So essentially you'll be writing a thin layer of PHP of which only purpose is to deliver coordinate data to the client from your database, preferably on response to AJAX call from your web page. You would likely be using a JSON data format for easy parsing, and then the map generating and displaying part would be written in javascript, and executed on client using a library like jQuery as suggested by numo16. This part is relatively easy to do and same concepts apply as in real game applications so communist ducks list of articles will explain you the hex displaying part.

For the displaying of map graphics on the players screen I would recommend that you use the CSS Sprites technique that lets you store all of your map tiles in a single file. For positioning you would use absolute coordinates for the tile image wrapped in a div, which again are in a relatively positioned container div.

If you apply jQuery click events to these image wrapping divs you can make the map clickable easily without having to manually track mouse positions as suggested. Style the container div with a overflow clipping to trim the map edges to be square instead of the jagged line hex tiles to make the map nice looking. :)
> 11 votes

# Answer
My thoughts are that as the data is read in from the database, each tile will be created as a square image with a hexagonal image map in whatever position specified by your (x,y) point. Which means you'll have to create your tile images as hexagons with a surrounding empty alpha channel, so that you can overlap your tiles a little bit to make them appear to fit together. You may want to look into jQuery to help polish up the graphics and UI side of things (animation, quicker and easier ajax, easy event handling, etc..).
> 1 votes

# Answer
I'm afraid I don't speak PHP, so I can't do code examples. However, here is a nice list of resources that may help you. :)

Here is a nice list of isometric/hexagonal grid articles on Gamedev; ranging from how to deal with hexagonal coords to caching tiles. (Of course, some of the stuff won't be relevant since it's mostly...what's the word? on a PC not a web browser.)

As for the graphical display, simply add transparency to a square image of a hexagonal tile.

'Clickable' would be something like:

```
if mouse button down on app:
take screen coordinates of mouse
Compare to screen coordinates of tiles

```

I have no idea of how much in the way of user events and database-hooking-up-to PHP has, so you might have to look into other languages and frameworks for that.

I wish you luck. :)
> 1 votes

# Answer
Following up on Fuu's approach, I have got a version working which relies purely on javascript and jQuery in the browser to render the hex map. Right now there is a function which generates a random map structure in JSON (out of two possible tiles) more or less like this:

var map = \[\["ocean, "desert", "desert"\], \["desert, "desert", "ocean"\], \["ocean, "desert", "ocean"\]\]

...but it's easy to imagine having the web page issue an Ajax call to get such a map structure from a server instead of generating the code itself.

The code is up on jsfiddle, from where you can also find a link to a blog post explaining it, and a github link if you're interested.
> 1 votes

---
Tags: tiles, php, web, strategy, hexagonal-grid
---


title: XNA Sprites Not Drawing Correctly

text:
# Question
Title: XNA Sprites Not Drawing Correctly
I have a problem through out my current code where certain Texture2D's are not drawing correctly over each other.

For example, at the start I have sprite font being drawn over a background image and half the text is not shown when I add the image.

```
        _sb.Draw(_background, new Rectangle(0, 0, 800, 480), Color.White);
        if (isPaused)
            _sb.DrawString(_bigFont, "Resume", new Vector2(295, 200), Color.Black);
        else
        _sb.DrawString(_bigFont, "Start", new Vector2(315, 200), Color.Black);

```

The text then seems to appear if I change the value of other text on the screen.

Is there something I am missing here?

Thanks.

# Answer
Unless you are actually playing with the Depth, you should be using `SpriteSortMode.Deferred`. MSDN Doc Here

If you are drawing everything at Depth 0, I'm pretty sure that XNA will pick a draw order for you. There are others discussing a similar issue here: http://forums.create.msdn.com/forums/p/72055/439545.aspx.

In 3D, this is usually called Z-fighting.
> 2 votes

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


# Question
Title: Reading and writing an anti-aliased texture in Direct3D9
I'm slightly confused about textures versus surfaces in Direct3D9. Now, it seems fairly simple that you can only read from a texture and only write to a surface, and when you create a texture then you can get surfaces to set as render targets from it.

What I don't quite get is the CreateTexture function. It's CreateRenderTarget equivalent for a surface which is only rendered to and never read has the options of anti-aliasing parameters, whereas CreateTexture doesn't, even though you can explicitly use it to create render targets.

Does that mean that it is impossible to create an intermediate texture for e.g. shadow mapping which has anti-aliasing?

# Answer
> 1 votes
I'm fairly sure you cannot read an MSAA (antialiased) render target directly as a texture in D3D9. (You *can* do that in D3D10-11, I believe). In D3D9, you must "resolve" an MSAA render target by copying it to a non-MSAA render target using StretchRect. This results in a plain image with the antialiasing baked in, which you can then use as a texture.

---
Tags: directx9
---


title: Working with 3D Noise

text:
# Question
Title: Working with 3D Noise
I am using a simplex 2D noise to generate my worlds so far. This however was never the plan and has the downside that I basically can only generate a heightmap. Instead I want to aim for floating islands scattered in the sky, but I fail to see how I can utilize 3D noise properly for this.

Based on a simplex 3D noise function I am currently generating noise like this:

```
float
sc_perlin_noise3_ex(const sc_perlin_t *perlin, float x, float y,
                    float z, int octaves, float persistence,
                    float base_frequency, float base_amp,
                    float lacunarity)
{
    int i;
    float freq = base_frequency;
    float amp = base_amp;
    float max = 1.0f;
    float total = 1.0f;

    for (i = 0; i < octaves; i++) {
        total += sc_perlin_noise3(perlin, x * freq, y * freq, z * freq) * amp;
        max += amp;
        freq *= lacunarity;
        amp *= persistence;
    }
    return total / max;
}

```

Problems start there: first of all I think I got octaves wrong, at least the outcome is very unpredictable. Persistence would be a value smaller 1 that removes the effect of the higher octaves.

Secondly however I have a general problem understanding how 3D noise works. From my understanding a value \< -1 could mean air, a value \> 1 would be solid and 0 is the thin line between them (the surface). First of all however I get a lot more values below zero than above zero, so I had to flip those two around. That seems odd, do I have the math wrong?

The actual problem however is that I cannot locate "islands" properly. Say I have a container of 256^3 in size and I want to have one large island in there with maybe up to three smaller islands in there I have to ensure that:

1. no island is cut off at the edges
2. that I only get two even sized islands in my block
3. I have some better control of the actual appearance of my island. For instance it would be nice if it had an actual flat-ish surface where I can put a heighmap on top of that for mountains etc.

Based on that I have the feeling I am on the completely wrong track here. Can anyone give me some pointers on where to head now?

Generally speaking I would like to have something that looks like this: floating island

# Answer
> 0 votes
I went with 3D noise again because it produces much nicer things than I could accomplish with 2D noise. I'm currently using a falloff factor for the general form of my island but unfortunately it still sometimes happens that the island will just be too small.

Generally though it works:

```
static int
block_is_solid(const sc_worldgen_t *worldgen, float x, float y, float z)
{
    float noise, density, center_falloff, plateau_falloff;

    /* caves */
    if (powf(sc_perlin_noise3_ex(worldgen->perlin, x * 5.0f, y * 5.0f,
                                 z * 5.0f, 3), 3.0f) < -0.5f)
        return 0;

    /* falloff from the top */
    if (y > 0.9f)
        return SC_BLOCK_AIR;
    else if (y > 0.8f)
        plateau_falloff = 1.0f - (y - 0.8f) * 10.0f;
    else
        plateau_falloff = 1.0f;

    /* falloff from center */
    center_falloff = 0.1f / (
        powf((x - 0.5f) * 1.5f, 2.0f) +
        powf((y - 1.0f) * 0.8f, 2.0f) +
        powf((z - 0.5f) * 1.5f, 2.0f)
    );

    /* noise combined density */
    noise = sc_perlin_noise3_ex(worldgen->perlin, x, y * 0.5, z, 7);
    density = noise * center_falloff * plateau_falloff;
    return density > 0.2f ? SC_BLOCK_STONE : SC_BLOCK_AIR;
}

```

Technique from pyalot.

# Answer
> 3 votes
A floating island? You don't really need 3D noise for that, just get two layers of 2D noise, then overlay them. One layer is the "ground" layer, then the next layer is the "floating islands" layer, and you could even go for a 3rd layer that you consider the "clouds" layer. There really should be no correlation between the ground layer and the "floating islands" layer.

3D perlin noise is basically for animations. Say you had a pool of molten lava that you generated with 2D perlin noise, and you want it to appear flowing. Well you'd use 3D perlin noise for that, and create an animation by selecting "sheets" from the cube of 3D perlin noise. The beauty of it is the noise would appear continuous throughout the animation, because the Perlin noise would be smooth in the 3 dimensions.

But for what you're doing you don't really need 3D perlin noise, just 2 layers of 2D noise will do.

# Answer
> 0 votes
Sounds like you are in over your head. You would probably want to split the two tasks of generating and positioning islands. Try first generating a bunch of islands, and then placing them randomly, if an island is placed so that it collides with an already placed island (or is just too close) reposition it, check again etc.

# Answer
> 0 votes
Like @bobobob suggest just layer two 2 dimensional perlin noise (or similar functions) together, here is an example, (this is assumes you are using voxels, but you can easily adapt it to pretty much any thing with height data) here is the pesudo code:

```
Voxel[,,] voxels = new int[sizeX, sizeY, sizeZ];

for (int x = 0; x < < sizeX; x++)  {
    for (int y = 0; y < sizeY; y++)  {
       for (int z = 0; z < sizeZ; z++)  {
           voxel[x, y, z] = VoxelType.Air;
      }
   }
}

// Bottom half
PerlinNoise[] perlinOctaves = new PerlinNoise[] { new PerlinNoise(freq, amp, seed) } /* Add as many octaves as you feel nessercary*/ }

double[,] noiseMap = PerlinNoise.SumOctaves(sizeX, sizeY, sizeZ, perlinOctaves);

int centreY = sizeY / 2;

for (int x = 0; x < < sizeX; x++)  {
   for (int z = 0; z < sizeZ; z++)  {
       // This basic inverts the "hill"'s created from the perlin noise;
       int y = centreY - (int)noiseMap[x, z];

       // Fill from the bottom of the hill up to the centre of the map
       for (int j = y; j < centreY; j++)  {
           voxels[x, j, z] = Voxel.Solid;
       }
   }
}

// top half, go crazy with this add hills, what ever you want :)
perlinOctaves = new PerlinNoise[] { new PerlinNoise(freq, amp, seed) } /* Add as many octaves as you feel nessercary*/ }

noiseMap = PerlinNoise.SumOctaves(sizeX, sizeY, sizeZ, perlinOctaves);

for (int x = 0; x < < sizeX; x++)  {
   for (int z = 0; z < sizeZ; z++)  {
       // Go about the top half
       int y = centreY - (int)noiseMap[x, z] + centreY;

       // Place the top layer
       voxels[x, y, z] = Voxel.Solid;

       // If the top half is not touching a part of the bottom get rid of it
       if (voxels[x, y - 1, z] == VoxelType.Air)  {
           voxels[x, y, z] = Voxel.Air;
       }

       // If the top part is generated below the bottom half, remove what is above it so the top part is visible
        for (int j = y + 1; j < centreY; j++) {
           voxels[x, j, z] = Voxel.Air;
        }
   }
}

```

So as the top and bottom half are pretty much similar, just inverted and really huge, make the frequency really low but the amplitude really high.

---
Tags: procedural-generation
---


# Question
Title: 3D Procedural Planet Generation - Resource
I don't know if the question fits on this site (if it doesn't I'll gladly accept any invitation to move it elsewhere), anyhow, I have found this Really great resource on 3D Procedural Planet generation and am nearly finished reading it, some things I can grasp quite well, other parts, not a all. However the thesis makes references to its "Enclosed CD" which contains source code for the project that is demonstrated throughout the document, the problem is there is no cd rom (obliviously) and there are no links to an online version of the source code.

I would be highly grateful if I could obtain a copy of it, any ideas, or links to similar tutorials/articles on the topic of 3D Procedural Planet generation would be greatly appreciated.

# Answer
> 0 votes
Consider contacting the author directly. Here is his LinkedIn profile: http://www.linkedin.com/pub/ondrej-linda/10/548/566 . His thesis is mentioned at the bottom of the profile page.

You could try contacting him via LinkedIn, or use the info on the page to contact him somewhere else (looks like he's at the University of Idaho now).

Good luck.

---
Tags: xna, c#, procedural-generation, procedural
---


# Question
Title: PyGame custom isometric engine : caching or not?
In the game I'm making, I need an isometric view with some altitude, which means players can go behind a hill, and be partly or totally hidden. To avoid re-drawing the whole view tile after tile every time a player moves, I decided to put each horizontal line of tiles in cache and draw each line, one after another from top to bottom. This works pretty well, I think FPS are correct and everything, but memory usage could soon be a problem: a 50\*50 map means 99 lines resulting in 98Mo, a 100\*100 map means 199 lines and 388 Mo.

Here is a line:

The memory consumption will grow even bigger if I allow higher altitude (each line will be stored in a higher Surface object).

I'm wondering if this cache system was really a good idea... I could code a bit better so that lines are stored in the smallest possible Surface, but there will still be a big memory consumption.

Do you have any advice, any feedback on my system? Is it worth optimizing, or should I forget this cache-idea ?

# Answer
> 3 votes
From my experience in making a isometric engine in PyGame (using the same tileset even) I think you'll get better performance by keeping track of which sprites are where on the screen. Then, when rendering, you only update the regions of the screen that've changed since the last rendering and when you do this only redraw the sprites that are actually in this space.

My solution to this involved keeping an interval tree with all the visible sprites together with a bounding rectangle that was updated whenever a sprite changed state or position. During rendering the draw could then be clipped to this bounding rectangle and the interval tree queried for sprites requiring redraws.

That said, I'm not sure it's an optimal approach but it worked fine for my hobby projects.

# Answer
> 1 votes
> In the game I'm making, I need an isometric view with some altitude, which means players can go behind a hill, and be partly or totally hidden.

Then you may as well cut this, and just call it a 3D engine with a funny camera angle, because that's what you're realistically implementing here.

And 3D engines use depth buffering to achieve this effect, which does mean re-drawing every vertex and pixel every frame.

---
Tags: python, isometric, pygame
---


title: What is a "Gameplay Programmer"?

text:
# Question
Title: What is a "Gameplay Programmer"?
In job descriptions, I often see positions called "Gameplay Programmer." What do people in that position do?

# Answer
When companies talk about hiring a **gameplay programmer**, what they are talking about is a programmer who will be responsible for code that directly touches on the game experience. That is, the programmer will be responsible for actually constructing the games, rather than engine or larger game systems. But beyond that, things vary a lot:

Some companies expect **gameplay programmers** to implement the user interface. Some don't. Some companies expect them to implement AI code, some don't. Some expect them to implement audio code, some don't. To be honest, the "gameplay" in **gameplay programmer** is an industry shorthand for "everything that we haven't hired a specialist to do". So these programmers need to be very versatile, and need to be able to learn new disciplines quickly.

I spent almost fifteen years being a gameplay programmer in the commercial industry, across five different companies.

My experience was that in some companies, a **gameplay programmer** is considered to be a junior or entry-level position; programmers who are only working on an individual game, after all, don't need to be as sophisticated as those who are working on systems that need to support lots of different games simultaneously, the way that engine programmers need to. In this sort of company, if a gameplay programmer does really well, he might be promoted into the engine team someday, if he can prove his worth. Or he might become a specialist, if he shows an aptitude for a particular area.

In other companies, a **gameplay programmer** is considered to be a medium-level position; programmers working on an individual game need to have some useful experience and be dependable. Inexperienced programmers might be given undesirable jobs to cut their teeth on (data pipelines, tools, etc), and eventually be allowed to move up into a "gameplay programmer" job. In this sort of system, a gameplay programmer who continues to do quite well might move up into a project leadership role, or else onto the engine team.

In still other companies, a **gameplay programmer** is considered to be a senior position, and to be a half-design position as well; these programmers are expected to be excellent, proven programmers, but also to have strong design sensibilities and qualifications, since they're directly touching the code that most strongly affects the player's experience with the game. In this sort of system, a really good gameplay programmer will likely remain a gameplay programmer forever -- this is considered to be the most valuable position which he can fill.

As a general rule of thumb, the better the company's games, the more senior a position they consider **gameplay programmer** to be (and therefore, the more difficult it will be to actually land such a job).
> 47 votes

# Answer
I always find it helps to illustrate by example.

* A gameplay programmer would be given tasks along the lines of: implement the melee combat system, implement the health regeneration mechanic, or implement the player jump controls.
* An engine programmer (what you'd call someone who wasn't specifically a gameplay programmer) would be given tasks along the lines of: implement deferred lighting, or an animation system, or a networking layer.

The key distinction is that of who the 'customer' is. For gameplay programmers, it's the design team - their task is to make the design into a reality. For engine programmers, it's generally **other programmers**. Engine programmers make technology and systems, which gameplay programmers and content creators can then use to realise the design.

Engine programmers write code which is largely game-agnostic - the same technology can often be used in multiple games. Gameplay programmers tend to write code which is very specific to the game being made. And there's always overlap - sometimes to implement the gameplay you need some new engine code.

Gameplay coding isn't any harder or easier than engine coding. It is however definitely a slightly different skill-set; you often need to be more creative, and be able to *bodge* solutions. Your goal is not to create the perfect re-usable system (the ideal for engine programmers), but to create the best game implementation. So what can be an asset in engine programming (attention to detail and well engineered structures) can be a hindrance in gameplay programming (where adaptability and iteration time are more important). A good gameplay programmer knows when to do it right (when the design is solid and the code will be used in many places), and when to do it quickly (when the design is still being worked out, and your code has a good chance of being discarded once tested).

Most of all, gameplay programmers need to be able to collaborate with the design team on a level that engine programmers do not. Aside from the obvious communication skills, that means you need to be familiar with other game designs much more than engine programmers do, so that when a designer says "make it work like Zelda," you know what they're talking about.

To learn to be an engine programmer, you'd drill down on a technology and learn how it works, and maybe implement your own version of it; the game would just be an arena in which to show the technology.

To learn to be a gameplay programmer, you'd take someone else's engine, and use it in as many different ways as you can. In other words, if you want to be a gameplay programmer, **make games, not technology**.
> 19 votes

# Answer
Exactly what it sounds like, a programmer who implements and maintains game play mechanics.

http://en.wikipedia.org/wiki/Game\_programmer#Gameplay\_programmer
> 2 votes

---
Tags: terminology
---


# Question
Title: Order independent transparency in particle system
I'm writing a particle system and would like to find a trick to achieve proper alpha blending without sorting particles because:

* Each particle is a point sprite in a single mesh and I can't use scene graph ability to sort transparent nodes. The system node should be properly sorted, though.
* Particle position is computed on shader from initial velocity, acceleration and time. In order to sort the system I would have to perform all this computations on CPU, which is something I want to avoid.
* Sorting hundreds of particles against camera position and uploading it on GPU each frame seams to be quiet heavy operation.

Alpha testing seems to be fast enough on GLES 2.0 and works fine for non-transparent but "masked" textures. Still, it's not enough for semi-transparent particles.

How would you handle this?

# Answer
> 9 votes
Here's what I would do.

Step 1: Don't sort. Just do it. See if it's a problem. Most likely isn't.

Step 2: Limit particles into such that do not really need sorting, such as:

* Just solids (with possibly alpha-to-coverage edges)

+ let zbuffer take care of the sorting.
* Just additive bits

+ a+b = b+a, so order doesn't matter

Step 3: if more is needed, split particle rendering into bits that have to be in front and the rest, and perform rendering in several passes (could fix complex smoke, for instance)

Step 4: if more is still needed, or if you need a general solution, one thing that comes to mind would be to use MRTs to get a very rough N bucket sorting done; render the particles into N output surfaces and compose them in a separate pass.

Anything further would require more information about your specific use case. But I'm pretty sure you don't really need order independency after all. Just use enough particles in random enough and it'll be ok =)

# Answer
> 6 votes
Just don't write to the depth buffer when rendering the particles. This will allow them to all be rendered and blended with each other. You should still perform depth testing though so that they can be properly occluded by geometry in the scene.

# Answer
> 5 votes
Using additive blending order doesn't matter:

```
glEnable(GL_BLEND)
glDepthMask(GL_FALSE)
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
DrawParticles();

// Now turn depth masking on and blending off, so state is unchanged.
glDepthMask(GL_TRUE)
glDisable(GL_BLEND)

```

This assumes that your sprite texture has a transparent background.

---
Tags: opengl, opengl-es, particles, transparency
---


# Question
Title: Understanding the Entity-Component Model
> **Possible Duplicate:**
> Role of an entity state in a component based system?

So, I've heard a bit about a model of game programming that involves creating entities and then attaching different components to them to change their behaviour. So, an enemy entity might have attached components of AI, collision physics, etc. This seems like an excellent way to solve a lot of the problems in creating an engine, but I don't really have a precise idea of what exactly an entity or component is.

So my question then: what exactly should an entity object encapsulate? How would I go about attaching components to it?

# Answer
> 2 votes
The whole point of a component-based entity system is that it's flexible. Each entity can have exactly and only what it *needs*. If a particular entity needs a collision volume and a place in the world, then it has that. If a particular entity doesn't need an AI, then it doesn't have that.

As to how you go about attaching them, there are two ways to do it: completely free-form, and slot-based.

By slot-based, I mean that there is a set of pre-defined components that every entity *could* have. There are a set of specific classes that is hard-coded into the entity class. You check at runtime as to whether the entity actually has those components or not.

A more free-form system allows you to put any number of components into the system. That is, the set of possible components is not hard-coded into the entity. Components in such a system would be *named*. To access a component of an entity, you would call a particular function and give it a name. It would search its list of components and return that component.

In the latter case, your components would need either polymorphism or some form of type-erasure or something in order to store them in a homogenous list and fetch them components later.

---
Tags: entity-system
---


# Question
Title: Optimize a render call to draw out several semi-transparent sprites
I'm writing a 2D side-scrolling style game in C++ and openGL. In this game I have several cloud sprites which are rendered across the top of the screen. They rotate and scale and such so they're not static. I'm wondering if there is any way that I can optimize this, because currently every time one of these sprites is rendered, GL has to perform blending between everything already rendered (like the background, etc) and these sprites.

I'm thinking something along the lines of rendering ONLY the clouds together all at once, and then performing a single call where the final result is rendered and blended into the main scene. Not sure how to even go about that or if it will even result in a performance gain. Any suggestions would be greatly appreciated!

Just for clarity, here is what a final render looks like. The clouds are formed by several smaller sprites being populated close together around certain points.

# Answer
I dont know much about OpenGL, but in DirectX there is alot of speed to be gained by render to texture techniques

http://ogltotd.blogspot.com/2006/12/render-to-texture.html
> -1 votes

# Answer
> because currently every time one of these sprites is rendered, GL has to perform blending between everything already rendered (like the background, etc) and these sprites.

While rendering with blending isn't the fastest possible rendering mode, it isn't exactly *slow* either. It doesn't go to each "thing" it has rendered before and blend with it. It's just blending with the destination color in the framebuffer.

> I'm thinking something along the lines of rendering ONLY the clouds together all at once, and then performing a single call where the final result is rendered and blended into the main scene.

This is a prime example of premature optimization being the root of all evil. You're "solving" an optimization problem, and your "solution" will not in fact solve the problem. It will create a *new* problem: overlapped blended objects won't work right. OpenGL's blending functions will only work when you're directly compositing with an opaque destination value. Composting with a transparent value, which you then layer on top of the destination, is not going to provide the correct results.

Don't optimize unless you *know* something is a performance bottleneck already. That knowledge can only be gained in one of two ways: having a *lot* of experience in a problem domain or having actual profiling data that shows where the bottleneck is. Just keep making your game; if it turns out to be a problem, you can find a way to solve it later. And you'll know that it *is* a problem rather than just guessing.
> 2 votes

---
Tags: c++, opengl, rendering, optimization
---


# Question
Title: How to adjust GUI to screen resolution ?
I've created a GUI for my XNA game and now I'm stuck with a problem. My GUI element positions are designed for a max resolution of 1920x1080, and if I try changing it to 640x480 they disappear from the screen. What I can change to keep them there?

# Answer
> 10 votes
You can do several things:

-Make your GUI resolution indepentent, scale and position everything based on relative screen positions, this is often a lot of work.

-Render your GUI to render target A of a fixed resolution (720P is often chosen), render your game to the screen, get the texture from render target A and render it upscaled/downscaled over the screen (make sure alphablend is turned on). This way you can work with fixed distances and still have it play nice with all sorts of resolutions.

Make sure to test your approach on a lot of resolutions and beware of mixing aspect ratios. Also mind the text, when downscaling too much it might become unreadable.

# Answer
> 1 votes
When positioning your GUI elements, use variables for the X and Y positions, that will vary depending on the size. Setting these positions to an equation like the one below is call relative positioning or relative space.

X = ScreenWidth / 5 - 5

This would put image at a X of one fifth of the ScreenWidth, with a 5 pixel offset. When developing really tight GUI's even the offsets can be relative.

---
Tags: xna, gui
---


# Question
Title: For learning purposes only, is creating a game engine or using one such as Unity3D or UDK better?
Alright, let me start off by saying this: I've seen multiple threads comparing creating custom game engines to already created game engines such as Unity3D or UDK, but none of the threads I've found have discussed this issue in terms of pure learning purposes. Instead, they've discussed the advantages and disadvantages of using already created game engines in terms of performance, development time, and customizability. Well, at least for starting out, I'm not worried about those aspects.

So, to reiterate, will designing my own game engine offer a firmer grasp on game programming concepts and knowledge than creating a game engine with an already built engine?

At the moment, I've got an intermediate-level knowledge of C++, no knowledge of DirectX or OpenGL, and an extremely limited knowledge of game engine architecture. However, assume that if I were to creating my own game engine, I'd first become acquainted with these required languages and concepts by reading multiple books.

Thanks in advance.

# Answer
It depends what you're trying to learn. If you want to learn how to program a game engine, then you should program a game engine. If that isn't what you are trying to learn, then programming a game engine will be a distraction from what you are trying to learn.
> 8 votes

# Answer
> So, to reiterate, will designing my own game engine offer a firmer grasp on game programming concepts and knowledge than creating a game engine with an already built engine?

No. Designing a game engine will teach you how to create a game engine. You could spend a year writing a rendering engine that handles vertex and pixel lighting, refraction, reflection, lens flare etc.

At the end of the year you'd probably know a whole lot about rendering but nothing new or significant about actually making a game. If you love the concept of game engines, make a game engine. If you love games, pick an engine and make games.

First, figure out what you love.
> 3 votes

# Answer
When creating a game from scratch, you learn about creating a game engine. However, by learning about engine creation, you gain knowlege of how other engines work, and why they do the things they do. Having that experience is key to using game engines correctly and pushing them to their limits.

If you know know the inner workings of a game engine, learning how to use them becomes second nature, or an acquired common sense. I am currently in the Game and Simulation Programming Bachlor Course at DeVry. The difference between a Bachelor degree in GSP and the associates you will get at a place like ITT, or Full Sail, is that DeVry focuses on Engine Development. The reason for this, is that they feel that if they prepare their students for the hardest math, physics, and problem solving, then the rest will come naturally, which from what I've witnessed in my 3 years there, is correct.
> 1 votes

---
Tags: education
---


title: Using ColorFill on a depth buffer

text:
# Question
Title: Using ColorFill on a depth buffer
I'm trying to implement a render abstraction over Direct3D9, and one of the functions I'm implementing is clearing a render target, which includes a depth buffer. However, the `IDirect3DDevice9::ColorFill` method I've been using doesn't seem to be able to clear depth buffers. Is the only means to clear depth buffers to use `Clear()` to clear depth buffers which have been bound to the rendering pipeline?

# Answer
> 1 votes
Clear() is the only way.

To understand why, you need to consider that Direct3D is an abstraction layer itself over the underlying hardware to present a way for you to code against them all. If you dig a little deeper behind the scenes on depth in particular, you start to discover that each manufacturer is free to implement (and therefore optimise) depth as they choose, as long as they adhere to the interface presented.

The link here describes a little about some of the different techniques that have been used, it seems to date from 2002 so things will have advanced since then, but it gives you an idea of why they hide the underlying implementation from you. The Wikipedia link on HyperZ here also talks a little about some of the optimisation methods used and the efficiencies they get from them.

---
Tags: directx9
---


# Question
Title: Which game engine is ideal for a 3D RPG?
I am thinking about making a small RPG. I know some basics of openGL, but I do not want create my own engine.

My criteria are:

1. Ease of use
2. Can do rpg game
3. 3D

Which game engine is ideal for a 3D RPG?

# Answer
it is absolutely Unity3D, and the basic version is for free.

http://unity3d.com/

Good luck
> 8 votes

# Answer
It all depends on the language you want to use. Py-Game or Blender's game engine are easy to use, in python (so easy) and open source. If you're going to make a game that requires a *real* engine though, PeterK is completely correct in saying that unity is by far the best (publicly available) engine on the market.
> 1 votes

# Answer
Take a look at Ploobs Engine, it supports XNA 4, opensource and has lots of features:

www.ploobs.com.br
> 1 votes

# Answer
UDK ia excellent for most jobs, i have yet to find something it cannot do.
> -1 votes

---
Tags: rpg
---


title: Algorithm for random flight of a fly

text:
# Question
Title: Algorithm for random flight of a fly
I'm new to game development. What is a good algorithm to model the random flight of a fly? I've been looking at path-finding algorithms, but they don't give any interesting random behaviour.

# Answer
> 4 votes
Lévy flights or brownian motion should work. These are random walks where at each time step the insect moves a random direction and distance. They differ in what distribution the random variables are sampled from.

The motion of hunting sharks can be modeled as brownian motion when prey is plentiful and lévy flight when prey is scarce.

Depending on what you use it for, you might want to restrict their motion (to keep them near a specific part of a level) or limit the acceleration (to make them appear to have have more inertia).

# Answer
> 1 votes
I made something similar to this a while back for 2D movement, but it should be a similar concept, similar to the way a fly buzzes around.

```
/*
Pick a random direction angle; call it dir.
Pick a random direction for dir to change (clockwise/counterclockwise). Call it accdir.
Pick a random time within a range before changing direction, call it chtime.
Start timer.
Every frame (or time period):
   change dir according to accdir.
   if timer == chtime:
        reset timer
        Pick new random chtime
        Pick new random accdir

*/

```

This should create smooth acceleration, and it should be buzzing around in circles. In two dimensions, accdir would be either clockwise or counterclockwise, so it would be spinning in circles by adding or subtracting from the vector angle, changing direction every so often. In 3D, it might be a bit more complex.

---
Tags: algorithm, random, simulations
---


# Question
Title: What is the "main" implementation of OpenGL?
What is the main implementation of OpenGL?

I see GLUT everywhere, but I want to use whatever is closest to an official implementation, or what ever I will have the most control over.

I might not be asking this right since it's contributed to by different parties. Which is why I have been looking at DirectX, but I see more people using OpenGl so I'd like to use that instead.

# Answer
The "main implementation" of OpenGL is whatever your OS or graphics card vendor provides. For Windows display adapter drivers it's generally OpenGL 3.3 (or at least that's what I got when I updated my driver today). For Mac, it's OpenGL 2.1, or 3.2 if you're on Lion. For iOS it's OpenGL ES 2.0. For Android, it's mostly OpenGL ES 2.0.

GLUT is not an OpenGL implementation. It exists alongside OpenGL and acts as a cross-platform windowing library. It's also kind of old. Freeglut is a little more up to date, but it seems as though people are recommending GLFW as a more modern and featureful alternative. For Mac, I'd recommend installing GLFW via Homebrew, MacPorts, or Fink. Or if you'd rather just go with GLUT, version 3.7 is included on Mac. You just need to include it via `#include<GLUT/glut.h>` instead of `#include <GL/glut.h>` since Apple bundles GLUT and OpenGL as frameworks. You can also create windows and OpenGL contexts with SDL and SFML.

If you're running on Mac, freeglut only works under X11. I don't think it's worth trying to get freeglut working with it. I just spent the last couple of days trying to get Nicol Bolas' tutorials to run on Mac, but by the time I was done #ifdef'ing things out, I realized that the shader code is all different versions as well, and I'm not yet ready to understand how to translate that between older and newer versions. Maybe it'll work on Lion if you fiddle enough with it, but I can't back that up.

There's also the "Unofficial OpenGL SDK" which is a bunch of helper libraries (including freeglut, glfw and some asset loaders \[*note: the version of GLFW bundled with this doesn't cleanly compile on Mac out of the box*\]). Everything but freeglut and GLFW compile fine on Mac with some header tweaks. To install GLFW on Mac, just use Homebrew.

If you're on Windows, the unofficial OpenGL SDK is actually pretty nice. I'd recommend it. I'm currently working through the aforementioned tutorials with it. I have yet to try OpenGL out on a Linux distribution.
> 8 votes

---
Tags: opengl
---


title: Making filled circles in cocos2d

text:
# Question
Title: Making filled circles in cocos2d
How can you make filled-in circles in cocos2d? I understand you have to create a new method, but I don't really understand how it works/how to do it. Could someone please provide maybe an example or tell me how to go about achieving this? Also, I need to create about 24 filled-in circles, would this cause lags of some sort? Thanks!

# Answer
> 1 votes
I am not sure what do you mean by "***I understand you have to create a new method, but I don't really understand how it works/how to do it.***" but I can tell you how to create a filled circle in cocos2d.

All you need is an image of circle of any color that you want or a white one if you want to change the color of the circle in your game.

With these circles as sprites in the game, the lags should not occur as I have a game that has 70-80 sprites in a game(A Cards game) and it never lagged even when i played pretty complicated animation in the game.

---
Tags: iphone, ios, cocos2d-iphone
---


# Question
Title: Content.Load() throws ContentLoadException when loading a texture in SL XNA
I've developed a while back in XNA but I'm a bit rusty. I've started working on SL XNA but have a problem I can't explain while trying to load content (model -fbx- or texture).

I place the image named `redRect.jpg` in the Content project by right-click -\> *Add existing item* and I've made sure all the properties are ok:

* Asset Name: redRect
* Build Action: Compile
* Content Importer: Texture - XNA Framework
* Content Processor: Texture - XNA Framework

I declare a texture

```
Texture2D redTexture;

```

but when I try to load the texture

```
redTexture = contentManager.Load<Texture2D>("redRect");

```

I get an error telling me that the image is not found

> Error loading "redRect". File not found.

# Answer
You seem to have the content file properties right.

The next thing that comes to mind is that maybe your `redRect.jpg` is not in a root of your content project. This would be the issue. If you have the content file in a subdirectory of content project, lets say "textures", you need to specify path to the asset including that folder name like this:

```
redTexture = contentManager.Load<Texture2D>(@"textures\redRect");

```

If that is not the case and you have `redRect.jpg` in a root of your content project and still getting this error, try setting the root directory for your content manager explicitly like this, before loading the content:

```
contentManager.ContentRoot = "content";

```

Otherwise, if there is still an issue, verify that the content reference to the content project is properly set in your SL XNA project. This reference should be created automatically by Visual Studio when creating the SL XNA project.
> 2 votes

# Answer
This is probably a rather obscure answer, but my symptoms were exactly the same (throwing a ContentLoadException loading redRect) so I hope this helps anyone who is suffering the same unlucky fate.

Apparently there is a bug that means the path length can cause referencing problems (in this case my content project wasn't being found). By starting again with a different project name (a longer name!), everything worked fine. (I'm just doing the XNA tutorials so starting again is not a problem, I expect moving the solution directory would also fix this)
> 1 votes

# Answer
Try

```
redTexture = Content.Load<Texture2D>("redRect");

```
> -1 votes

---
Tags: xna, assets, windows-phone-7, asset-management
---


title: SDL, SFML, OpenGL, or just move to Java

text:
# Question
Title: SDL, SFML, OpenGL, or just move to Java
I recently started a new project, and I'm wondering if I should change the technology now before it's too late.

I'm using SDL with C++, I have around 6 classes, and the game is going alright, but I got to this point where I have to rotate my sprite to make it point to the coordinates of the mouse.

It's a 2D topdown game, so if I pre-cached the images, I'd have to load 360 images, which is bad for memory. If I used SDL\_glx, I could do the rotation real time, but I heard it'd drop my frame rate very drastically, and I don't want my game to be slow.

I also read I could use OpenGL, which is faster at these things. The problem is, how much would I have to change my code if I moved to OpenGL with SDL.

So, I considered moving to a completely different language - Java - which is much simpler, and would allow me to focus on the game and handle networking much more easily than with C++.

I am very confused, and would like to hear your opinion - thank you!

# Answer
> 3 votes
If you're fairly new to game programming *and* programming in general, I recommend against starting out learning everything in C++. Either set your sights lower than sprite-based games while you learn C++ (e.g., practice with a text adventure while you get comfortable with the language) or go for the less cerebral, more fun route with another language.

Java is a good language to start game programming in if you're at least somewhat comfortable with object oriented programming. You have libraries like JogAmp, LWJGL, and Java Monkey Engine to get started, as well as tools like Eclipse.

Lua and Python have similar libraries to Java available and are also pretty good for getting something on screen relatively quickly and making it move around, although I have to defer to someone else's experience for starter libraries and tools for these languages.

If you're comfortable with C++ and would like to stick with it, then I think it comes down to a matter of personal experience, priorities, and taste. The options you listed are all good ones generally, but you'll want to read up on the APIs, strengths and weaknesses, and so on to see which one fits you best.

My hunch, though, is that you'd be happier working in another language for a while to get some experience before you come back to C++. There is plenty of general game programming experience to be gained elsewhere.

I hope this helps. Good luck.

---
Tags: opengl, java, sdl
---


# Question
Title: Strings and Variables Inheritance From Another Class in Java
I am working on a program and I want these variables and strings, to be called on another class. So I have these:

```
    public static boolean newgame = false;
/*
 * Declares Character Status
 */
public boolean male = false;
public boolean female = false;
public static String charactername;
public static String characterclass;
public static int hp = 100;
public static int mp = 100;
public static int charstr = 5;
public static int chardef = 5;
public static int charagi = 5;
public static int chararank;
public static int charaprofile;
public static double criticalhit = 0.0;
public static double luck = 0.0;

/*
 * Determines how each classes time fighting.
 */
public static int timeFightSlow[] = {4000, 4500, 4800, 5000};
public static int timeFightMedium[] = {2000, 2500, 2700, 2860,3000};
public static int timeFightQuick[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

/*
 * Declares Items:
 */
public static String gender;
/*
 * Declares Classes
 */

public static String sf = "Swordsman";
public static String sm = "Sword Mystic";
public static String warrior = "Warrior";
public static String duelist = "Duelist";
public static String lancer = "Lancer";

/*
 *
 */
public static int experience = 0;
public static int iniexp = 100;
public static double totalexp = iniexp*2.5;
public static int initialhp = 100;
public static int hptotal = initialhp+10;
public static int initialmp = 50;
public static int mptotal = initialmp*2;

```

The problem I get is how can I call them up on a new class? Can I call them again or I should make another integer for those?

# Answer
> 1 votes
You want to be able to use these variables from another class? If you want them to be different in the class (eg you can change them in one, but it wouldn't affect another class accessing the variables) then do what skyjlv said.

If you mean you just want to be able to access them from another class then put them in an interface and either implement the interface on the class (So you don't have to do Interface.variable) or just use them directly from the other class by going Interface.variable (This is the more advisable approach)

Like this

```
public interface Constants {
  public int blah = 1;
  public String foo = "bar";
}

public class bazz implements Constants {

     public bazz() {
        System.out.println(blah); //Prints 1
     }
}

```

or

```
public class bazz {
     private int blah = Constants.blah;

     public bazz() {
        System.out.println(blah); //Prints 1
     }
}

```

# Answer
> 1 votes
```
public final class Constants
{
  public static boolean male = false;
  public static boolean female = true;
}

```

Elsewhere

```
if (this.isFemale == Constants.female)

```

You probably want to have a look at enums instead for flags though, they are more flexible and powerful.

I know its popular to use interfaces/base classes to inherit constants, but unless your class is supposed to actually BE a constant, it should never inherit or implement a Constants class/interface. Composition is much more preferred than inheritance in cases like this, you only spend a second typing that extra "Constants." but if you decide to inherit to save those keystrokes you spend the rest of the programs lifetime with an inheritance that shouldn't really be there in the first place.

# Answer
> 0 votes
You could create an abstract class which contains all the variables. And then have this class and another class that you're planning to have similar variables both extend the abstract class.

---
Tags: java
---


title: Object updates, internal vs external?

text:
# Question
Title: Object updates, internal vs external?
The title is a bit confusing, but I couln't think of how to explain my question in a short phrase. So here it is:

Whenever I'm writing game engines, wheter it's physics/tilebased etc, I always get to the point where I'm not sure how I should manage things. Should entities in the world handle on their own, or should there be some global system managing them?

Here's an easy example: Moving things. Should each object see the world around him (check for collisions) and move based on that.

*\[note, this is a tile based game where object move per tile, so I'm not using physics to move from tile to tile\]*

```
public class Actor : GameObject
    {
        private void MoveTo(Vector2 location)
        {
            if (world.getTile(location) != solid && world.objAtTile(location) == null)
            {
                Tweener.addTween(this, location);
            }
          }
        }

```

---

Or should the movement of each object be handeled in the world, where the world checks everything?

```
public class Actor : GameObject
    {
        private void MoveTo(Vector2 location)
        {
            world.moveTo(location);
          }
        }

public class World
{

    public void moveObject(GameObject obj, Vector2 location)
    {
      //called from object

      if (getTile(location) != solid && objAtTile(location) == null)
         {
                Tweener.addTween(obj, location);
         }
    }
}

```

It doesn't really matter that much for this example I suppose, but I can see myself getting into trouble later on. Thanks in advance.

# Answer
> 2 votes
I see your examples are in Java, but your tags don't specify any language. In C++, the answer is *neither* \- you should not be using a member function for this!

```
void move_to(actor *a, world *w, vec2 location);

```

# Answer
> 1 votes
There is no simple answer.

As with most things in programming, it's a trade off. Giving more power to individual objects makes them larger-and therefore slower-but makes the engine easier to understand and extend. Having a mega-class that can handle everything together might be faster, but at the cost of having a mega-class; that is, it's generally considered bad form to make supermassive classes.

I've read some articles about component and data driven design, where you have a single class which represents all objects of a certain type, storing their data in lists, and passing around only indexes to get properties of an individual object. Though I can see this as a viable type of architecture, I feel it rather screws with the whole point of object orientation, which has gotten its fair share of criticism too.

I personally recommend giving more power to the objects. It makes more sense in an object oriented language, and (I would imagine) easier to understand and maintain over time.

# Answer
> 0 votes
I'm updating my answer because a lot of things weren't clear before the comments. Please bare with me while I explain my thoughts.

In general, two key aspects to consider in any design is cohesion and coupling. We all know that we need high cohesion and low coupling to be able to make a more reusable and extensible design.

So, if the world has to manage everything, that means that it has low cohesion and tight coupling (because it needs to know and do everything). However, this is also the case when a game entity has to do everything. Update his location, render his texture, etc. etc.

What you are really interested in is to create systems that focus on one aspect of the entity. For example, a game entity could have a Texture, but a Renderer would be responsible to render that texture on screen. The Renderer doesn't care what other properties the entity has.

Taking it a little further, a game entity is simply a bag of properties. These properties are manipulated by systems that are focused on specific properties. And this is where Component-based Entity Systems (CBES) come in, where properties = components.

Specifically, CBES with **Systems** (or SubSystems). This design tends to have a few Systems that are focused on specific components of an entity while not caring about what other components the entity has. Also, the Systems are coupled only with the information they need to process these components.

Let's take your example. Since the input of where to move the entity is based on the player's controller, you would probably have a PlayerControllerSystem. This system, would control, apart from many other things, the entity's PositionComponent. In this case, the PlayerControllerSystem would need to know about the Level and the PositionComponent. If later on you decide to add collision detection, you would create a CollisionSystem that would again use the position of the entities, but this time to calculate bounding boxes (or you could have a BoundingBoxComponent, your call). The fact is, you can easily switch on or off behavior (even on the fly) by simply adding/removing components. So, more behavior means more systems are manipulating the components of an entity, but they are all in a well defined class with low coupling. Want scripting? Add a ScriptComponent. BAM! You just added scripting capabilities with 2 classes. Physics? Sound? Same again.

So, the reason I am advocating CBES with SubSystems is that it is perfectly OO and an overall easy maintainable/extensible system. Adding a behavior to an entity is as simple as deciding what data that behavior needs and which entities need it.

For more information about Component-based Entity Systems with SubSystems, there is an excellent series of blog posts by T=Machine at Entity Systems are the future of MMOG development. The author even went as far as creating a wiki for collecting various implementations named Entity Systems Project

A general (and well-known) post about Component-based Entity Systems in general is the Evolve your hierarchy who created the system for Tony Hawk Pro.

Finally, if you are looking for a library with example code, don't go any further than the Artemis library. Artemis is primarily in Java but here is a port in C# (which I am currently using in my XNA project).

# Answer
> 0 votes
I usually go with a design where objects handle themselves (that's what methods are for, after all) but the base World has lists of all the objects and it uses those lists to coordinate them. So something like:

```
class World {
  var walls = [];
  var actors = [];
  function update() {
    for each (actor in actors) {
      actor.update(walls);
    }
  }
}

class Actor {
  function update(walls) {
    this.move();
    for each (wall in walls) {
      this.collide(wall);
    }
  }
}

```

# Answer
> 0 votes
Keep it DRY, shy and tell the other guy.

It's better to ask the world to move your actor than it is to ask the world if you can move to where you want to go. This way you can change pathfinding algorithm easily in the world class and such. Of course, you could just leave this up to a baseclass for the actor, but that's the direction I would take and the reason why.

# Answer
> -1 votes
I recommend you try to read up on component based architectures. There are quite a few blog posts, presentations and write ups out there about them that can do a better job than I ever could.

AltDevBlogADay has quite a few posts about it, a very good one being this series about game entities: http://altdevblogaday.com/2011/07/10/the-game-entity-–-part-i-a-retrospect/ There are multiple parts that focus on the issue you're trying to solve.

# Answer
> -1 votes
EDIT: Rewritten due to feedback stating I had not drawn the line clear enough for this answer to the original question.

I would like to clarify the question a bit more if possible. Should the logic that acts upon an object be internal or external to that object. The last part of the post specifically mentions about the longevity of the design as the basis for asking the question, to avoid trouble later on.

My simple high level answer is to keep all logic that acts upon an object within that object.

You do not need the world to move an object, all you need is the object to be moved and the vector representing the location to move to it. The world may come into play when a destination is being chosen or when a reaction to the environment is required due to collision, but those are outside of the example given to work upon.

To address the underlying part of the question and achieve longevity of the design I would suggest a component oriented architecture. Component architectures break down an object into discrete sets of data and functionality (assuming you go with my answer above which states to keep the logic with the data). If your structure looks like CEntity-\>CHuman-\>CSoldier-\>CPlayerCharacter then you will invariably get into issues where you need to alter some logic and depending where it goes in that tree (How many other types of humans are there for instance?) it can have sweeping affects on multiple object types.

A component system would instead have a set of interfaces that define what the CEntity object is made up of like ICompRenderable, ICompMoveable, ICompHealth, ICompInventory and so on. Where you would have CCompMoveableHuman and possibly a CCompMoveableSoldier and CCompMoveablePlayer to keep their individual movement patterns separate. So say the Soldier is altered to run in formations. This change will only affect entities built using that component.

So, to sum up I suggest you contain the logic with the data the logic applies to. I also recommend breaking up objects into discrete components to cut down the 'Where do I put this?' questions and provide stability into the future with ease of maintenance and its extensible.

Hope this helps.

---
Tags: architecture, management
---


# Question
Title: 2D Point Light XNA , Why my point light radius is Oval?
I friend of mine , taught me how to make a simple 2d point light with shader, so i follow his steps and finally done it !

but something happend , the light shape is like an oval and not like a circle , my friends couldnt explain me why,

could you help me how to fix it, and explain me why it happend?

here is how it looks like http://dl.dropbox.com/u/2553973/screengrab/PointLight\_07.png

ShaderCode

```
Texture InputTexture;

sampler InputTextureSampler = sampler_state {
    texture = <InputTexture>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = mirror;
    AddressV = mirror;
};

struct VertexShaderOutput
{
    float4 Position  : POSITION0;
    float2 TexCoord  : TEXCOORD0;
    float4 Color     : COLOR0;
};

float4      ambientColor = float4(1.0,1.0,1.0,0.0);
float       ambientIntensity = 0.3f;

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    //float4 color = float4(1, 0, 0, 1);
    float4 texCol = tex2D(InputTextureSampler, input.TexCoord);

    float4 color = ambientIntensity*ambientColor;
    float dist;

    //Light 1
    float  lightRadius = 0.2f;
    float  lightIntensity = 15.0f;
    float4 lightPos = float4(0.3f,0.3f,0.0f,0);
    float4 lightColor =  float4(0, 0, 1, 1);

        dist = distance(lightPos, input.TexCoord);
    color += saturate((lightRadius-dist)*lightIntensity)*lightColor;

    texCol = saturate(color) *texCol;

    return texCol;
}

technique PointLight
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

XNA CODE

```
    GraphicsDevice.SetRenderTarget(normalRender);
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, effectLight);
      spriteBatch.Draw(background, Vector2.Zero, Color.White);
    spriteBatch.End();

    normalRenderTexture = normalRender;

    GraphicsDevice.SetRenderTarget(null);
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();
       spriteBatch.Draw(normalRenderTexture, Vector2.Zero, Color.White);
    spriteBatch.End();

```

# Answer
> 2 votes
You need to take into account the AspectRatio of your viewport (GraphicsDevice.Viewport.AspectRatio), the texture coordinates given to the shader are normalized to a square region so you need to inform the shader of what your AspectRatio is.

In 3D you do this with the Matrix.CreatePerspectiveFieldOfView call, in 2D you simply need to make a float aspectRatio which you initialize in XNA.

---
Tags: xna-4.0, shaders, lighting
---


# Question
Title: A decent design for handling large creation/deletion of random objects?
So I was attempting a 'Hit the X' game (e.g Toss the turtle, spank the monkey) in which an uncontrollable object travels across the screen in hopes of hitting certain objects and avoiding others.

My dilemma is how to efficiently create and destroy these objects with respect to the character - that is, if the player is at, say, (90,34), all objects whose x position is less than 90 are garbage collected while more objects are generated at x \> 90 or 100.

The only solution I could think of was to: randomly populate a tree that organizes by X values at the start of each round and to simply trim off the leaves at every so frames - if the player hits a certain spot, in which the tree is looking scrawny, start adding some more random objects on.

But this seems inefficient and unwieldy. Does anyone have any suggestions?

# Answer
Unless I am misunderstanding the situation you are asking about, this seems like premature optimization to me. I would say implement whatever technique is most straightforward for you. You can optimize it later if you start having performance issues, but for such a simple game I wouldn't expect to have a bottleneck with the creation of random objects.
> 4 votes

# Answer
What you want to do is have an boolean `active` property on your objects that determines whether or not they get drawn/can be affected.

You then create a pool of the objects (i.e. define and initialize an array of inactive (`active == false`) objects as large as the most objects you'll have active at one time). Then, when you want to spawn a new object, find an `active == false` object in the array and set it's properties and then set it to `active = true`. When you want to get rid of objects, loop the array to see what objects have an `x` value less than 90 (or whatever) and set their `active = false`.

This means you won't have any garbage to collect and should help your game run faster.

**Edit**
Actually, if you used a stack (here's an implementation for actionscript) for the inactive objects and an arraylist for the active objects, then you wouldn't have to loop anything to figure out if you have available inactive objects. When you want a new object, you just pop it off of the inactive stack, set its properties and add it to the active list. Then, the game only draws items from the active list. When you want to remove something, remove it from the active list and push it onto the inactive stack.
> 1 votes

---
Tags: 2d, flash, performance, data-structure
---