title: Detect Open Space in Farseer

text:
# Question
Title: Detect Open Space in Farseer
> **Possible Duplicate:**
> How do I detect ledges?

I'm working on a 2D platformer using XNA and Farseer. I would like the player's character to be able to grab and climb up ledges. Detecting a collision between the player and the side of a wall is simple enough with the OnCollision delegate, but I have to admit I'm a bit stumped on how to detect that there's enough clearance for the PC to mount the ledge.

Essentially, I want to ensure there's an appropriately sized rectangle above and to the left or right of the PC (depending on their direction) and I'm not sure how I would check for such a space.

Any suggestions on how to determine there is nothing in the simulated world within some bounding rectangle?

# Answer
The video for Overgrowth Alpha 132 shows how they implemented ledge climbing: http://www.youtube.com/watch?v=GFu44oeLYPI

Their method should work in any engine, **even 2D engines** where you'd use a rectangle and circle instead of a cylinder and sphere.

Their ledge detection involves two parts:

### Wall detection (using the sphere)

The game checks if the player's currently colliding with a wall. If there's a wall, there might be ledges the player can grab onto. The second part takes over to analyse the ledges.

### Ledge detection (using the cylinder)

If the player's contacting a wall, a cylinder is swept downwards from a certain distance above the player's position until it touches a ledge. This can determine three things:

* Whether a ledge exists above the player
* The ledge's height
* Whether there is room for the player to climb up onto the ledge, considering the cylinder occupies the same horizontal space as the player.
> 13 votes

# Answer
Well, you already have the tools, you just need to think of it differently. Rather than thinking trying to find empty space, you just need to find space with no collisions. Basically, all you have to do is test the area above the player with a rectangle the size of the player, and then if there are collisions, the player can't climb up. If there aren't collisions, the space is open and the player can get up.
> 5 votes

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


# Question
Title: I want to use Python as a scripting language for my game, can I use it purely with C (not C++)?
I want to use Python as a scripting language for my game, can I use it purely with C (not C++)? It is important to me that I not use C++, and purely use C instead.

# Answer
As the official Python website/documentation suggest, "yes" you can embed Python purely with C.
> 4 votes

# Answer
I know that is not strictly related to your question (for which the answer is simply yes) but you should consider to **extend** Python with your C function or to use **another language for scripting**, *Lua* perhaps.

You can try the first option by compiling your C functions as dynamic library and then use **ctypes**. This gives you the chance to have a **working prototype in almost no time**.

If you profiled your C app before, you can profile the protype too, comparing the two to evaluate the ctypes overhead; **ctypes** (*Foreign Function Interface* in general) **is not embedding** but you have chances to see that this is **suitable for you with little or no modification**
> 3 votes

---
Tags: python, c
---


title: scanline filling a trapezoid

text:
# Question
Title: scanline filling a trapezoid
I have computed the four corners of the viewable bit of 2d map in my 3d view. So I know the trapezoid that is visible, and I want to 'visit' these tiles in my map.

So my algorithm is basically a convex polygon scanline fill, specifically with four points.

However, I have trouble finding simple sample code to borrow; all want to cope with the complexities of concave and complex polygons and apply winding and such, which is unnecessary in my case and cluttering.

I've contemplated sitting down and writing my own simple trapezoid scanline fill implementation from first principles but was wondering if anyone had a tried and tested version to share that I could copy instead?

Or maybe I've just been googling for the wrong terms and there are some on the net to point me at?

# Answer
So I implemented my own; here's the python prototype:

```
class Pt:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "(%s,%s)"%(self.x,self.y)

class TrapeziumIterator:
    def __init__(self,map,width,height,a,b,c,d):
        # create an iterator over the cells in the map that are in the trapezium described by a,b,c,d corners
        # a,b,c,d describes the CLOCKWISE perimeter of the trapezium, e.g. tl,tr,br,bl from screenspace
        self.map = map
        self.width = width
        self.height = height
        # we re-orientate the trapezium so the lowest y is topmost
        t = [a,b,c,d]
        start_y = min(pt.y for pt in t)
        while t[0].y != start_y:
            t.append(t[0])
            del t[0]
        self.t = t
        # work out starting position
        self.y = int(max(0,start_y)) # init y before x!
        self.x = self._start_x(self.y)-1 # x is iterated in the first call to next()
        # work out stopping positions
        self.stop_x = self._stop_x(self.y)
        self.stop_y = int(min(height,max(pt.y for pt in t)+1))
    def next(self):
        "return True if there is a square to be visited; then the x and y variables member are set; else return False"
        self.x += 1
        while self.x >= self.stop_x:
            self.y += 1
            if self.y >= self.stop_y:
                return False # reached the end
            self.x = self._start_x(self.y)
            self.stop_x = self._stop_x(self.y)
        assert self.x >= 0 and self.x < self.width, self.x
        assert self.y >= 0 and self.y < self.height, self.y
        return True # you can read the x and y member variables
    def _start_x(self,y):
        # go down the left side
        return max(0,self._side(y,0,3))
    def _stop_x(self,y):
        # go down the right side
        return min(self.width,self._side(y,3,0)+1)
    def _side(self,y,start,stop):
        inc = -1 if start < stop else 1
        while self.t[stop].y < y:
            start = stop
            stop += inc
        f = (y - self.t[start].y)
        f /= (self.t[stop].y - self.t[start].y)
        return int(self.t[start].x + (self.t[stop].x - self.t[start].x) * f)

def test(image,col,a,b,c,d):
    w,h = image.size
    it = TrapeziumIterator(image,w,h,a,b,c,d)
    while it.next():
        image.putpixel((it.x,it.y),col)

# test it
import Image
w,h = 100,100
image = Image.new("RGB",(w,h),(255,255,255))
test(image,(0,255,0),Pt(-60.3,-10.4),Pt(20.2,25.3),Pt(70,90.2),Pt(60,110))
test(image,(255,0,0),Pt(30.3,40.4),Pt(60.2,25.3),Pt(70,50.2),Pt(33,47.7))
# debug show it a bit larger
image = image.resize((w*6,h*6))
image.show()

```

The quad is described by its four corners in clockwise order. The algorithm finds the top-most corner, and then walks down the left and right sides.
> 0 votes

# Answer
Since a trapezoid is made of two triangles you could just split it up and use some triangle drawing code, which I'm sure you can find plenty of examples of.

If you want to implement it yourself, all you need to do is iterate down the left and right sides of the trapezoid drawing horizontal lines between those points. Use a standard line drawing algorithm like Breshenam's for following the sides. You'll probably also need to clip off screen pixels.
> 1 votes

# Answer
If you draw horizontal scanlines, convex polygons (including quads) divide vertically into sections as follows...

1. Possibly a triangle on the top, with a horizontal base.
2. A (possibly empty) sequence of quadrilaterals with horizontal edges top and bottom.
3. Possibly a triangle on the bottom, with a horizontal top edge.

The triangles can be viewed as quads where one of those horizontal edges just happens to have a zero length, so all you really need to worry about are quads with horizontal edges top and bottom.

There isn't a lot of simplification of this for the quads case - you'll have at most 3 parts to draw (each of the four corners on a different scanline), but that doesn't help much.

Anyway, as you scan from top to bottom, you always have a next-significant-scanline at which you'll change the left edge, the right edge, or both. Following these edges can be done with a variant of Bresenhams. Be aware, though, that it's valid for the edge to move over multiple pixels per scanline - it's not quite the standard Bresenhams algorithm you need for those edges.

You may need to clip off the top and bottom chunks with each scan-line, but the easiest way to clip stuff that's horizontally out of range is to individually clip the scanlines before drawing - without affecting the two (left and right edge) Bresenhams-algorithm states.

Often, the vertices of a polygon are stored in clockwise or counter-clockwise order to support visibility calculations. If that's the case here, it can also help with this "rendering". View the list of vertices as a circular array". Find the highest vertex/vertices and the lowest vertex/vertices. The left-edges vertices are in one span of that circular array, and the right-edges vertices in the another. One of those spans is in the correct order for rendering, the other is in the reverse order. It may be easier to make those lists of left-edge and right-edge vertices before you start, rather than work within the circular array, but it shouldn't be that difficult either way.

This kind of thing was explained well in 3D graphics books for the 16-bit era, but got more neglected when 3D graphics cards became the norm, for obvious reasons.
> 1 votes

---
Tags: c++, c, geometry
---


title: What should I use to handle input?

text:
# Question
Title: What should I use to handle input?
What should I use to handle input? I am wanting to use OpenGL so that my games are cross platform. DirectX provides input libraries, and OpenGL does not. Because my games need to be cross platform, I cannot use DirectX's libraries. What should I do, or what is the common solution to this type of problem?

# Answer
SDL and SFML are cross-platform and widely used.
> 4 votes

# Answer
DirectInput is quite deprecated, as far as I know, and very rarely used. If you're using OGL directly and not through any abstraction, then you will have to go to the operating system API to collect input, or use an abstracting library that has already done this work like SDL, SFML and more.
> 3 votes

# Answer
OIS is a good input library but it doesn't support mac very well.
> 1 votes

---
Tags: opengl, directx, input, cross-platform
---


# Question
Title: Need advice for 3D BSP based graphics engine
I have coded myself a OpenGL BSP viewer for an old game format. It is very similar to the Quake 3 file format. Because my interest is developing graphics engines, I want to be developing while looking at using current technology. So I turn to you, the experts on the subject for direction of what to focus on. I would like this to be as fast as possible and considering the old file formats are very simple and have few polygons, I think it should be doable. Here are my questions:

1. Lighting a. Does it make sense for me to learn vertex lighting or should I just implement per pixel lighting instead? b .I know OpenGL has an 8 light limit. Should I realistically only use one of those for ambient light and the rest computer through shaders? If not, what should I do?
2. Sorting/Culling a. What is the fastest most common used algorithm for sorting surfaces to render. Complexity is not really an issue. I want to learn what is currently being used and ways to really only render the things I can see. I have seen a number of algorithms described like the painter's algorithm and am wondering what makes the most sense for BSP based geometry. b. If I have textures with alpha masks, I was told that sorting has some sort of involvement with this process. How do I allow them to render correctly in 3d space?
3. Graphics Pipeline a. Should I be sending my geometry data via VBOs? Is this the standard used today? b. If I have a number of "regions", possibly 200-300, should I find a better way to send them to the GPU without sending 200-300 chunks. Should I combine them into one and keep a reference associated with each.

Any other tips for BSP based rendering and things of that nature?

Also, if I said something that was incorrect, please correct me. I'm that person who would rather be corrected and slightly embarrassed than ignorant and unaware.

Thank you for your time. I really do appreciate it.

# Answer
If you're - as you say - interested in *current* technology :

1) Lighting : Per-pixel lighting, definitely. If you want to look at current-gen rendering, you'll be looking at writing vertex- and pixelshaders. Simple as that. They offer almost unlimited flexibility and are not much harder to use than the fixed-function pipeline, if you start to learn them properly. OpenGL's 8 light limit is only applicable for old-fashioned fixed-function pipeline setups. Don't go that route, learn OpenGL Core and forget about all the dated glBegin/glEnd stuff.

2) Sorting / Culling : To start out : only sort if you need to for transparency. Only cull objects that are outside the view-frustum.

3) If you're using OpenGL, use VBO's and VAO's.

-

Unasked : if you're making a viewer for an old-fashioned BSP format (I suspect something from an ould Valve / ID engine ?) you should be able to get away with drawing the entire level without any sort of optimization (culling / bsp) at all and still get full framerate on modern hardware ;)

OpenGL Tip: Get the OpenGL Superbible 5th edition. This will teach you how to do modern OpenGL and will not cloud your mind with stuff you'll later find out is outdated.
> 1 votes

# Answer
1.a Per-vertex lighting is easier then per-pixel lighting (per-vertex lighting is built-in into OpenGL, perpixel lighting requires a custom shader).

1.b If you have eight lights, use them! You'll have to calculate which lights are visible, though.

3.a Use VBOS. Never use glBegin/glEnd (unless you use display lists, but in your situation VBOs are the better solution)

3.b You should not worry about performance while the program is still in development. Especially with todays hardware. So, send out your 200-300 chunks.

I don't know BSP maps well enough to help you with your other questions.
> -3 votes

---
Tags: opengl, binary-space-partitioning
---


# Question
Title: How should the actual game interface with the menu system
I'm using the Game State Management (GSM) concept in my prototype and I like it very much. One of the screen has a "Game" embeded in it, where all the "good stuff" happens. The menu launching the game works fine, but **I'm not sure how I should allow the game to request a screen from the ScreenManager.** I'm not talking about a menu screen, but about something contextual to the game.

For clarity's sake, let's say that when I click on a game element (a rendered model for example) I want a screen that asks me what color I want that model to be drawn next. Right now, my game knows that model is "targeted" with the mouse (I use a Ray picking approach).

I looked at the Role-Playing sample to see how they did this, but when their GameScreen handles the keys, to open the inventory for example, it's never contextual to what's actually happening in the GameScreen.

Ideas welcomed!

**Edit:** The game must also be able to get a feedback or something from the "contextual screen" to get the new model color, for example.

# Answer
> 5 votes
The problem here is that you are trying to get a controlled object (screen you're in) to direct it's controlling object (ScreenManager). Two approaches come to mind:

1. Adapt the code of the library so that the ScreenManager listens for and acts on custom events fired from the screens it manages. You could send events that carry an instance of class `object` that you can fill with data every time, and respond accordingly in the ScreenManager.
2. Define an object with static data members, which you can then reference from any other class. When you want to change state with context, push the context into this central class; fire the request to change; when the change is about to occur, check the central class and act accordingly. I find this approach hackish as I hate relying on statics to hold globally accessible info this way.

When I developed a gamestate system for Disjunction, I got around this by method 1: I explicitly designed the state subsystem to carry data on every transition, informing the new state as to the old state's intent. Whether you do this via events or direct references is up to you. The state pattern is a really easy one to get to grips with -- maybe you should roll your own.

# Answer
> 3 votes
A good architecture is keeping the GameState and ScreenManager objects separate so they don't directly know about each other and only indirectly communicate though an EventDispatcher object; ScreenManager registers with EventDispatcher as listening for messages about models being picked, and GameState sends a message to EventDispatcher about a model being picked (along with a parameter for which model was picked).

Going in the other direction is as simple as having ScreenManager dispatch events about buttons being clicked, and GameState listens for messages about buttons being clicked.

Now you can change either the GameState object or the ScreenManager at will and, as long as you don't change the messages each is dispatching/listening to, changing one will never affect the other.

I believe this is the Observer pattern, although frankly my knowledge of design patterns is kinda ad hoc.

EDIT: I misunderstood the question slightly, but I'm not changing my answer because it's still how I would do it. The relationship between the Game object and the ScreenManager in GSM is different from what I originally thought you were talking about, but using an EventDispatcher like this is still how I would pass messages around.

# Answer
> 2 votes
A simple solution would be to create an `InputBoxScreen`, `ColourPickerScreen` etc. all deriving from GameScreen. These would have in the constructor some context object (e.g. your model / object that was clicked on).

It would also have a delegate to run.

When the user made their selection it should run the delegate passing in the context, and the selection, then remove its self from the screen manager.

An example usage below (using generics to strongly type the context object):

```
//User clicked the model
var colourPickerScreen =
    new ColourPickerScreen<Model>(modelSelected, (context, colourSelected) =>
        {
            context.Colour = colourSelected;
        });

screenManager.AddScreen(colourPickerScreen);

```

The tricky part is often ensuring that the context/action is still valid when the user makes the selection. e.g. the model still exists.

---
Tags: xna, c#, state, screen
---


# Question
Title: How should I pay people who work on my game development project?
What is the proper way to pay your team for a game development project? For example, how would you pay to a graphics artists or a musician for their work, especially in the context of today's app marketplaces like the Apple App Store or the Android Market?

It is better to pay in advance, or to share the incomes proportionally as an app becomes successful?

# Answer
> 6 votes
Each project will be different, and you may also find that your potential employees have a variety of expectations.

For example, many folks may prefer a salary because they have a practical personal need to pay rent/mortgage and put food on their table. Especially if there is a need to hire them for a lot of hours (e.g., 40 hours per week for 6 months), your employees will probably be more comfortable with regular paycheques.

If the jobs are really small (e.g., less than a week's work), then paying on a per-project basis may work better. They may wish to get partial payment up front, with the remainder after the project is completed (and with larger projects there could also be a number of payments in between as the work progresses).

There may also some employees who are willing to agree to a "hybrid" of these two ideas, such as in the form of a base salary plus a percentage of the profits after the game is released ("profit sharing" which is similar to paying royalties, except that you'll probably want to be the owner of the work they've done for you). The risk is, of course, that the game never turns a profit and they don't get to realize the potential benefits of profit sharing (you'll want to make sure this is explained clearly in the contract -- the "Advice from professionals" section below recommends getting legal advice).

The positive side of this "profit sharing" approach is that it can provide a subtle long-term marketing advantage because those who get a share of the profits \[as long as, or whenever, the game is profitable\] will likely feel motivated to do "word of mouth marketing" for you by telling people "I contributed to *that* game; you should try it!"

**Advice from professionals**

Hire an **accountant** (a CGA designation is highly recommended) to make sure you get all the payroll and taxation aspects of your employment arrangements set up correctly.

Hire a **lawyer** (one with experience in both contract law and employment standards is preferred) to make sure your employment and/or profit sharing contracts are set up correctly.

For the profit sharing arrangements, you will probably need to have one short meeting with both your lawyer and your accountant at the same time.

# Answer
> 1 votes
I'd think you have two approaches: you can hire them as contractors, or as partners.

As contractors, you are paying them one time for what they do - e.g., "I will pay you X for a total of 4 music tracks" You own what they make outright, and it's yours to do with as you please.

As partners, they may (or may not) be paid for their work on the project, but at the same time they also are given some kind of royalty or income based on the sales of your game.

My personal opinion is that if the artists are not deeply involved in your game's design, hire them as contractors. Pay them once, and never worry about it again. If they an integral part of the design process, then bring them in as partners so they feel a greater sense of pride (and ownership) in what they do.

---
Tags: project-management, payment
---


# Question
Title: Investigation stage before starting a game
I was thinking about *how* to organize the stage about getting informed about whatever game is needed to develop, what would others do.

For example, if I wanted to develop a game about car racing, I should figure out all the factors during the race, from the car factor to the pilots, etc., environmental factors like weather, circuit conditions, etc.

How does one manage this stage?

Thanks.

# Answer
1. Use your imagination on the general topic if you haven't already.
2. Do some research online and in libraries / museums too if you're keen.
3. Play a few similar games, or at least watch youtube vids / read reviews of them. Know your competition.
4. Rinse, repeat steps 1-3. Slowly your imagination will feed off the ongoing research you are doing, and your game idea will become more defined / refined.
5. (Optional) Take notes as your major ideas take shape, if you don't have an amazingly good memory.

And before you do any of the above: Get a google account if you don't already have one, and set it up for tagging so you can use it as an all purpose database. Gmail, google docs and google bookmarks all use tagging as you probably know, to cross reference information by topic. What if you have two categories, "fuel" and "circuit conditions", and a single article matches both? -- So, tag to keep track of the cool stuff you'll find. You can search gmail more easily by typing eg. `label:"circuit conditions" label:"crashes"` into the gmail searchbar to find an article you know you saw somewhere on both these topics...

And as Phil has stated -- using a cyclical approach like this will show you quickly enough if your idea is not something you wish to pursue.

EDIT: And as Randolf has suggested, even if you only scribble notes that you will never look at again, scribbling notes and sketches has the impact of solidifying concepts in your mind.
> 6 votes

# Answer
There are many different approaches you can use. Since the 1980s, I've been designing an MMORPG and using a hierarchial point-form layout in simple ASCII text files (which are also organized hierarchially)...

Initially, I started out with a vision of having a system with a bank of modems, which was inspired by a real-time multi-user game called *Infinity Complex* on a multi-line BBS which was apparently running the Galacticom BBS software. Then in the 1990s the internet swept the public by storm, and I *upgraded* (or *scaled up*) my vision to accommodate a much larger multi-player base.

To organize the data, I have a set of directories like this:

* Project\_name

+ Concepts

    - Cartography (maps of the planet, continents, cities, dungeons, etc.)
        - Creatures (monsters that are computer-controlled)
        - Environment (plants, buildings, terrain, etc.)
        - Foods (some real, some fantasy)
        - Items (things the players can pick up and use like tools, art, etc.)
        - Magic (spells, potions, equipment like wands, etc.)
        - Quests
        - Shops
        - Species (the player-controlled characters, most species have multiple races)
    + Documents

    - Background (detailed histories that are not fully explained in the story)
        - Dictionary (almost exclusively for made-up words)
        - Encyclopedia (almost exclusively for made-up things and places)
        - Story (mine is currently larger than 65 MBs of pure ASCII text, divided up into numbered book sub-directories each containing separate files like "chapter8.txt")
    + Miscellaneous

    - Marketing ideas
        - Screen shots from other games
    + Source

    - Database
        - Prototypes
        - Production (this one is currently empty as I'm currently developing prototypes)
    + Specifications

    - Interface
        - Protocol (for client-server communications)
        - Size of elements (or tiles, etc.)

Within many of these directories, I have a variety of text files named simply and logically, and then in many cases I also have accompanying "Research" directories where I store more files that are the result of research that I've done over the years...

For the Orc species I have a file called "Concepts/Species/Orc.txt" which contains specifications, the various races, abilities, natural intelligence levels, and other information about Orcs. I also have a "Concepts/Species/Research/Orc/" directory which contains pictures and other information about Orcs which I have researched over the years. If I create art for Orcs some day, then I will store it in the "Concepts/Species/Art/Orc/" directory (and make any subdirectories there for the different races, or whatever, if necessary).

For other species, just change "Orc" to whatever the name of that species is. For a species I created where there is no pre-existing data anywhere to be found, if there is something similar to it then I store a copy of it in the relevant "Research" directory for that species. If I need to add a note to a .PDF file, for example, then I'll create a .txt file with the same base filename and save my notes in there.

Another example would be "Shops" which works in pretty much the same way. For the Weapons shop (which is sometimes combined with the Armoury and/or Archery shops in some towns), I have a text file called "Concepts/Shops/Weaponry.txt" which contains a list of various weapons that these shops can carry. There's also another sub-heading for "specialized weapons" in this same text file that lists certain specific weapons that are only available in a few shops throughout the world, along with a little bit of background about why (e.g., the merchant has a specialized skill that is needed to create this particular type of weapon, and there are only three characters throughout the world that have this skill). For shops that are sometimes combined with other shops, I have a special sub-heading in my text file for this too, with references to the filenames for those shops (and then I make sure those shops reference back as well). For pictures of weapons and documentation about how various weapons work (from researching the internet, scanning pages from library books, etc.), I store these files in the "Concepts/Shops/Research/Weaponry/" directory.

The key with using a hierarchy like this effectively though is to try to keep the structure deep instead of flat. In other words, don't fill up your higher (closer to the "root" or "top") in your structure with too many categories -- sub-categorize instead. (If you're so inclined, use a database to store your information; my personal preference just happens to be a deep directory structure instead, and it works quite well for my needs.) If you go flat-and-wide instead of deep, it will become a challenge to navigate and manage, and over time it will feel "disorganized" and be more of a pain to work with.

Under "Project\_name" I do keep a few text files, which are:

* credits.txt (a list of people who have contributed a few ideas, support, etc.)
* description.txt (a generalized description of the project, will be useful in marketing)
* names.txt (literally thousands of names I've been dreaming up all these years)
* vision.txt (general purpose of this project, key features, benefits to users, etc.)

Under the other directories I often have a "resources.txt" file that includes links to web sites (and the dates I found them just in case I need to use a service like "archive.org" to view them in the future) with a note about why the link is relevant. These are the types of resources that I don't absolutely have to have, but would be useful in expanding on further research should I need to at some point (searching for stuff in Google is very helpful, but pre-determined resources like this can still save a lot of time).

I hope this is helpful to you, or, at the very least, interesting enough to get you started.
> 10 votes

# Answer
I tend to work more iteratively, and break the idea I have down into smaller problems that can be solved more easily. By doing this it helps me see my progress more clearly with concrete results rather than spending weeks researching something that might never make it into the final game.
> 2 votes

---
Tags: game-design, planning
---


# Question
Title: How can I handle a 2d game with tens of thousands of sprites rendering at the same time?
We are trying to make a small 2d game which requires an excessive amount of sprites spawning and moving around the screen at the same time. We did try doing this in python but it started choking at around the 500 mark. Are there any good ways to handle this in python?

# Answer
If you have a very large number of sprites, it might be time to let hardware handle it and move your sprite rendering into VBOs via pygl or the like. Realistically though, massive numbers of sprites can usually be turned on it's head as a "find the sprite under this pixel" problem instead. Maybe not so easy in python, but you might find a library already written for "particles" that handles this situation better. Collecting your sprites by wich frame they are on for example.

A good answer to this question would require a bit more knowledge about the type, speed, clumping, or even how regular the sprites might be. Do you have thousands of sprites because there are that many entities? or is it moving land-pieces? do they move in groups? Each assumption we can make about the sprites can offer a better / faster rendering solution.

As usual, what is your input data, and what do you want out.
> 8 votes

# Answer
Late to the party, but I think the simple answer is, "Learn what code profiling is and how to apply it". Because you cannot make any assumptions as to what is causing your performance drop until you do.
> 4 votes

---
Tags: 2d, sprites, python
---


# Question
Title: Identifying mesh format from initial bytes
I have a file containing mesh data whose blocks seem to start with DWORDS like:

0x1 0x1 0x3100026f 0x1 0x30000112

or

0x1 0x1 0x310007b2 0x1 0x30000112

or

0x10000006 0x3 0x310001f6 0x310001f6 0x310001f6

They don't look like .x binaries. Any other ideas?

**UPDATE:**

Here's more: 00000001 00000001 3100026F 00000001 30000112 000000C7 BD869270 3F0372D4 00000000 BD41F15F 3F11A611 3F522E05 3E40EF5A 3E17CDF8 3E40993C BF504FBD 3F0CCC2A BF78001B BE654B6A 3DDA7965 BD80EB99 3F003679 3C0BDAE1 BD3DD880 3F112A76 3F528732 3E8EFD04 3E185DD8 3E3984B8 BF48A923 3F180DA9 BF7854DC BE6599AE 3DBF7319 BCD7235C 3F041CCC 00000000 BF52314E 3F12223D 00000000 3F727B04 3C22FD80 3E29BCD1 3F7C0367 3D6FCD12 3E70A826 BCE91707 BF78B921 BCD7235C 3F008C87 3C28E0F6 BF6B36D8 3BD28E32 3ECA109F 3F4AEA89 3D894EC0 BE18A98D 3F7CC7A8 3D57AE4B 3E48D2F6 B46C577B 3F7B0753 BE3DBAC2 3EF41E67

It looks like some of these are almost certainly floats and others are almost certainly not. And it appears (not shown here) that after a long list of valid floats, there is a long list of DWORDS that aren't valid floats. A list of vertices followed by some table of indices?

# Answer
At least part of it looks like a variabe-length list of the format: (number of entities) \[(entity ID) times the number\]:

```
00000001 3100026f 00000001 30000112

```

-\> two lists of 1 entity each

```
00000003 310001f6 310001f6 310001f6

```

-\> one list of 3 entities

What those might *mean*, though? No idea. It doesn't look like a floating-point number (at least not an IEEE-754 one). It would be some unpractically (for a 3D artist) small numbers, on the order of 1E-9. It's more likely something like a bunch of flags and/or IDs. EDIT: Or byte offsets into the file, for that matter.

---

EDIT: So far, the format looks like follows (guessing some info):

```
[amount of sub-models]:uint_32
[amount of data for first (unknown) block]:uint_32
[unknown data]:array of uint_32
[amount of data in the second (unknown) block]:uint_32
[unknown data]:array of uint_32
[amount of vertices]:uint_32
[vertex data]:array of vertex_data

```

vertex\_data looks like follows:

```
[position]:vector3 of float
[normal]:vector3 of float, normalised
[UV_mapping]:vector2 of float, in the range [0.0f ... 1.0f]
[first unknown normal]:vector3 of float, normalised
[second unknown normal]:vector3 of float, normalised

```
> 4 votes

# Answer
If you have a system running Linux (or Cygwin) you can try the 'file' command on it, if its relatively common it should show up.
> 2 votes

# Answer
You say you found a long list of valid vertices? Draw them in point form; if they resemble a model, then chances are your correct.

From that you could then count how many vertices there are, and then from that count, search the binary for anywhere that count might pop up. This could allow you to find the header which then describes said vertices (ID, count etc).

From this information you could then extrapolate other headers and find similar patterns, and maybe distinguish some more valid data.

Food for thought.
> 1 votes

# Answer
If you think it's a standard file format, then I suggest you just quickly rename the file to different mesh formats and double-click until you get one right. This is assuming you have a 3D editor installed, of course. You might just go down the Wikipedia List of 3D graphics file formats; start with the common ones like blend, max, 3ds, ma, mb, ac, wings, md2, md3...

Also please don't forget to mention what the answer is when you find it, in case by chance someone else has the same question!

But really, either you try all the different formats, or we have to create sample files in each format and open them with a hex editor and look at their headers. I certainly can't find a place that lists all of the 3D format headers. The only one I know off the top of my head is that a Milkshape 3D file starts with the characters "MS3D000000", so yours is not a MS3D file.
> 0 votes

# Answer
It's very possible that this is just a custom format that is not standard. Since most games strip out a lot of unimportant information in their content pipelines, it's entirely possible that the game in question is just rigged to read these files directly with no need of watermarks in the headers.

If that is the case, one way to detect the file format is to reverse engineer the format, process it as the game would and validate that you get sane results during the processing.

```
00000001 00000001 3100026f 00000001 30000112
or
00000001 00000001 310007b2 00000001 30000112
or
10000006 00000003 310001f6 310001f6 310001f6

```

If you'd like to reverse engineer this format, you'll need more than just the first 5 dwords. I myself can already see some possible patterns in here, but there is no way to tell whether my conclusions are correct without more data from the file or fiddling with the bytes and trying to load it in the game to see what happens.
> 0 votes

---
Tags: 3d-meshes
---


# Question
Title: Making walls in tile-based games: what am I missing?
After spending time today to jot down some notes regarding the implementation of walls into my tile-based game, I've suddenly realized it's not going to be as simple as I imagined before. While the current stage of my work is not even close to actually making the wall-related code, I've come up with three different ways to do it. Right now I'm unsure which one of my ideas will work best, and whether I missed something or not.

Important: a character **CAN** stand on a tile that has walls, regardless of their form.

The common thing for all the three variants: the tilemap will be "kept" in an single-dimension std::vector (or similar) based container. The reasons for that are (awesomely) explained in answers to a different question.

Container classes in tile-based games.

Back to walls.

**A) The simple approach.**

Nothing fancy here. Each tile-container can hold not only characters, but one or several Wall objects, which are attached to the edge **inside** the tile.

Pros: easy to implement, nothing to change in the engine. Cons: Two things. One - it might be just in my head, but some combinations just look ugly. Second - this approach allows to make a double-wall from two adjacent tiles. Building will be an important part of the game, and double-walls allow the builders to possibly forego upgrading the material of the walls through game means, and just achieve increased durability with doubling the existing wall. That's not desirable. Sure, I could include a procedure that forbids double-walling, but it will have a bad feel to it.

**B)The smart(?) approach.**

Instead of letting the players double-wall the whole map, I'm going to beat them to it. Every wall has two halves that are attached to the edge of the tile from inside. So, to make a single "Wall unit" I'll have to create two Half-Wall objects in two adjacent tiles.

Pros: It's symmetrical!!! Also, no significant change of current engine specs is needed. Cons: More hassle, more objects, and, of course, the "caps". As you can see in the picture, a corner will basically cry for a "cap" object. I'm actually cool with it, it's not so hard to add. Hey, I already have a plan for thin columns made out of four connected caps. Sweet. Still, I have some worries regarding possible Field of View and Line of Sight issues.

**C) The total overhaul variant.**

Or, I could just create borders and corners as separate containers for game objects. Just like that.

Pros: Not even sure. Well, it's straightforward. Definitely. Cons: It will require an overhaul. Not of code, thankfully, but of the current game mechanic mentality - that's for sure. The benefits are not so obvious. Also, this aprroach requires **much** more containers than the two previous ones. The indexing math will also be a bit of pain.

So here we have it - three distinct ways of making walls between tiles. If there are any alternatives out there - I'll be happy to check them out. If there are any benefits/downfalls to any of the approaches that I didn't see - please point them out.

# Answer
I'd use your method 'B'.

To avoid needing 'caps', just extend each wall "1/2 wall thickness" in both directions. This will create overlapping walls where they meet, but your diagrams already suggests this is not a problem.

So, in Method 'B', Pic #3, the horizontal wall would extend to the left a bit, and the vertical wall would extend up a bit.

\[I'm new here, just registered. Am I missing something, as I can't see an 'Add Comment' button to your original post. Is that a privilege of people with higher reputations? Or am I overlooking the obvious? Sorry for adding this as an 'answer'.\]
> 14 votes

# Answer
You noted that a character can stand on a tile containing a wall but have you considered treating each tile as wall itself? Even half a tile as a wall in a horizontal or Vertical fashion?

Pros: Calculations and placements are trivial, collision is trivial where all calculations and collisions are just based on the coordinates of the walls placement.

Cons: It could impact your entire implementation, code and graphics. You don't want to totally abandon your method either, you still want special cases where only part of a tile is wall (Link to the Past with cliffs).

This is how I would I have based my implementation, going forward, knowing that I can always reference a tile and perform a calculation on it depending on my characters location and what kind of tile it is.

A castle wall I could just perform a calculation from the center drawing a box that I could not pass through or if its a round rock I could do the same calculation from the center but as a circle so my character can move around in like it was rounded.
> 2 votes

# Answer
Sorry to say but the third way is really the way to think, well, you already have the ability to do that so lets move on and think about the other two!

The thing is that a wall is a zero width, two dimentional (height\*length, in a 3D world) square partitioning two Boxes. You should consider them as such but you might use a simpler solution as when to build your dungeon (especially if other people might build parts).

It seems it is a Top-Down 2D game where walls have "a width" so they need that corner (your 'cap' object). This is exclusively 'graphics' though so I'd go with some sort of:

A 2D map with the tiles (ie. type of tile and such).

A 2D map with 2 walls, ex. bottom and right (the left wall will be the 'right wall' in the tile left from this one).

\+ a Logic that draws all the walls and 'caps' etc.

Thus separating logic and graphics. You might do an "interface" taking care of things like SetWall(ThisTile, LEFT, NOWALL) -\> setting the right wall of the tile left of ThisTile to "NOWALL"...

Maybe this seems blurry but the thing is that you should always try to have at one side the logic (the actual data, without redundancy) and on the other side the 'drawing of the data' which calculates if there is need for a 'cap' etc.

++
> 1 votes

---
Tags: c++, tiles, level-design
---


# Question
Title: pathfinding with obstacles in a Warcraft 3 like game
Consider A\* searching on a tile based map. A straight forward code would be: If there is an unit inside that cell, then it is unreachable, this is ok.

But there is map resolution issue. When I look into Warcraft 3, there monsters and structures does have different radius, and you can walk very close, which is more like vector based, how this was implemented?

Also, what is the standard solution to incorporate moving obstacles collision detection with path finding algorithm, like Warcraft 3?

# Answer
> 7 votes
I can't say for sure what kind of approach was used by WC3 developers, but it looks pretty much like Hierarchical Annotated A\*. Unit radius defined in the WC3Editor was used as-is for 3d model scaling, but actual unit size for pathfinding was discrete, maybe something like unitSize = (int)(unitRadius / 10). It wasn't vector-based, that's for sure.

Let's say there are a lot of path nodes making high-resolution node grid. Simple unit like a ghoul has a size of 2, so in order to place it somewhere in a grid we need 4 free path nodes near each other. A death knight hero is slightly larger with a size of 3, taking 9 path nodes total. Now we place 2 ziggurats together leaving a 2 node-wide space in-between, and send a ghoul and a death knight on the other side. Ghoul will be able to pass between two ziggurats, while death knight will have to move around. How can it be determined?

In order to see whether a node can accommodate a unit of specific size, let's assign a special clearance value to each node defining a maximum allowed unit size. Basically, it means that several bounding checks were made for a node, and the largest possible bounds were remembered as node's clearance. So when we want to place a death knight on some node, it becomes as simple as comparing node's clearance with death knight’s size. Of course, things are going to become much more complex when there are several units hopping around competing for nodes, but that’s another story.

For further detail you may want to check out this article:

http://harablog.wordpress.com/2009/01/29/clearance-based-pathfinding/

# Answer
> 4 votes
It would use tessellation to create pathing regions AKA navigation meshes. This article explains the concept with full diagrams.

You can still maintain A\* as your pathfinding approach, however your network is no longer a grid (4-connected graph), but a graph representing the arbitrary connectivity between your polygonal regions. So you will have to adapt your algorithm to suit.

---
Tags: collision-detection, path-finding, collision-avoidance
---


# Question
Title: How to avoid singleton pattern for Event Scheduler?
I want to make an Event scheduler for my Game, I basically want to be able to schedule the triggering of a Game Event. This can be a one time trigger, or a periodic trigger (trigger event "E\_BIG\_EXPLOSION" on a 5 seconds basis...).

It is tempting to think that this may be a good place to use a Singleton, but singletons can be quite evil and they tend to spread like a disease... so I try to avoid them at all cost.

What design would you propose to avoid the singleton usage in this case?

# Answer
You should have a very well-defined set of interfaces that are allowed to transmit or receive messages -- giving them a reference to a EventScheduler should be trivial. If it isn't, or if you feel like that would involve passing the event scheduler to "too many" distinct types, then you might have a larger design problem on your hands (a promiscuous dependency, which singletons tend to exacerbate, not solve).

Remember that while the technique of passing the scheduler to the interfaces that need it is a form of "dependency injection," you aren't in this case injecting a *new* dependency. This is a dependency you already have in the system, but you are now making it an explicit one (versus a singleton's implicit dependency). As a rule of thumb, explicit dependencies are more preferable as they are more self-documenting.

You also afford yourself more flexibility by decoupling the consumers of the event scheduling from each other (since they are not all necessarily tied to the same scheduler), which can be useful for testing or simulating local client/server setups or a number of other options -- you may not need these other options, but you have not expended effort to artificially restrict yourself from them, which is a plus.

EDIT: All I mean when I talk about passing the scheduler around is this: if you have some game component that is responsible for responding to collision, it's probably created via some collision responder factory that is part of your physics layer. If you construct the factory with a scheduler instance, it can then pass that instance to any responders it creates, which can then make use of it to raise events (or perhaps subscribe to other events).

```
class CollisionResponderFactory {
  public CollisionResponderFactory (EventScheduler scheduler) {
     this.scheduler = scheduler;
  }

  CollisionResponder CreateResponder() {
    return new CollisionResponder(scheduler);
  }

  EventScheduler scheduler;
}

class CollisionResponder {
  public CollisionResponder (EventScheduler scheduler) {
    this.scheduler = scheduler;
  }

  public void OnCollision(GameObject a, GameObject b) {
    if(a.IsBullet) {
      scheduler.RaiseEvent(E_BIG_EXPLOSION);
    }
  }

  EventScheduler scheduler;
}

```

This is obviously a terribly contrived and simplified example since I don't know what your game object model is; it does however illustrate making the dependency on the event scheduler explicit and shows some potential for further encapsulation (you wouldn't necessarily need to pass the responders the scheduler if they communicated through to a higher level collision response system at the same conceptual level as the factory that dealt with the nuts and bolts of raising events via the scheduler. This would isolate each individual responder implementation from the implementation details of the event dispatch system, such as which specific event to raise on collision, which may be ideal for your system -- or not).
> 12 votes

# Answer
An event dispatcher is one of those cases where a singleton isn't the *worst* idea in the world, but I applaud you for trying to avoid it. You might find some ideas here.
> 7 votes

# Answer
I tend to avoid singletons too but there are a few objects that make the most sense as singletons and a central messaging system is one of them. Despite the rants I've heard, singletons are certainly much better than global variables/functions because you always have to deliberately address it (versus global values just magically appearing out of thin air).

In the end every message sender and receiver must have *some* common point of intersection, and it is much better to keep your objects decoupled by having a common singleton shared by everything rather than have each of your message senders directly know about the message receivers.

While I'm sure some other architecture could be devised for your event system, to me it seems like a waste of effort to over-think it, especially when using an event system is already a big win over not using one.

EDIT: As for your specific example of an explosion event dispatched on a periodic trigger, I would probably have the events dispatched in some other object (like the turret gun or whatever causing those explosions) and not in the central event system. However those events would still be dispatched *to* the central event system.
> 3 votes

---
Tags: architecture, design-patterns, events
---


# Question
Title: How important is understanding Software Project Management for an indie?
I ask this because I'm curious to know from people who actually support themselves by making games, if their project management skills contribute to determining the success of a project?

I also have this feeling for some reason that having too much project management can strangle the creative process. Maybe there is a way to prevent that from happening. I don't know.

Thanks to all that reply.

# Answer
Sometimes "strangling the creative process is necessary", if the creative process is so out of control that it's preventing you from shipping a game.

PM (project management) is one of those things that, if things are going smoothly, you hardly notice that it's there. It's primary goal is to keep the team focused on what the real goal is.

Some things in the PM toolbox can actually help the creative process. The idea of short sprints to a "shippable product" can put you in the quick iteration mindset. Daily standups are useful as a communication tool. But it's all about how you apply it and where.

The relative importance of PM depends on the project and the team. Sometimes it doesn't add anything. Sometimes it's the difference between success and failure.
> 7 votes

# Answer
Caveat and summary - I'm basing my answer on the idea that you have a good team to start with. A good team doesn't need a project manager, but can work together towards a common goal as a team. "Bad" teams (or really complex projects) need a project manager.

There's an old joke in the modding world of the guy who posts on some forum that he has an awesome game idea, and he just needs a coder, a modeller, a skinner, a sound guy and a level designer. And what's he going to do? He's the "leader" or the "idea guy". The point being, the poster doesn't have much to offer, and really needs to be part of the development team.

Don't let your desire to add project management to a game turn your project into one of these. Indie implies small team, and small team implies very flat organizational structure. And that implies that your team can work independently towards a common goal that they all share and understand.

Some teams need no management and are self managing - a team of equals who's synergistic efforts combine into something good. This is true when the developers are working towards a common shared vision and goal.

If that vision is *not* shared, then there needs to be something that guides everyone towards the same goal. That can be a project manager, but it just as easily can be a good design document that everyone follows.
> 5 votes

# Answer
It is pretty important, just like a cooking oil: its presence seems inessential, but its absence becomes noticeable with passing of time :) Well, game project's activity can be divided into two categories: enjoyable and painful. Consider this:

* Writing a complex artificial life simulation or complex particle system feels good and rewarding.
* Analysis of competitors, accountancy and various evaluations feels like abominable waste of time.
* Its only natural for one to strive for a pleasant while avoiding unpleasant.
* Success comes naturally to those who diligently challenge painful tasks instead of just happily coding away from them.

It is easy to spot a problem here, without proper project management you may fail to adequately deal with accumulating problems, arising challenges and various other things which come up in project's lifetime.

So project management is not here to strangle creativity, it is to aid you by providing a systematic way of solving both pleasant and unpleasant tasks.
> 1 votes

# Answer
I think the first question you have to ask (perhaps clarify in your question) is: Are you managing only yourself? Or are you managing others?

Because if you're only managing yourself, I would frame it as "self-discipline" and "effective time management" as opposed to what PM generally refers to, which is managing a group who are on the floor, getting the actual nitty gritty done.

From my experience, being an "individual indie" means having a solid grip on where to dedicate your time to what, eg. production, support, networking, promotion, etc. And once you can effectively manage yourself, that's when you have something to offer (your indie business) as a manager of others.

I guess what I'm saying is, everything comes with time. If you're not at the point where you have to worry about traditional PM skills yet, then don't. Focus on improving your ability as a creative, a developer, and a businessman.
> 1 votes

---
Tags: project-management
---


title: 3D Camera control in DCC

text:
# Question
Title: 3D Camera control in DCC
I'm trying to build a simple world editor and I would like to implement a camera similar to what's used in 3ds Max, Maya or even Unity.

From what I can figure out from Unity, the panning behavior seems to be relatively simple : the camera is moving on the plane defined by the camera position and direction. However, rotation is more complex. Most of the time, the camera is looking at a fixed point on the xz plane and rotating around it. I'm not entirely sure how this point is determined and this is what I'm trying to find out. Also, I've noticed that, after a certain height, the camera fall back to a rotation-only control.

Does anybody implemented something similar to this?

# Answer
It seems to me that how the point is determined is really up to you. You could set the initial point to be the centre of your world and then set your camera up with an appropriate angle and distance looking at that point.

* Panning would move the camera AND the point.
* Rotating, as you said, would rotate the camera around it.
* Zooming would move the camera closer to the point along the "target" vector of the camera to the point.

Doing it this way allows you to focus and rotate around a specific object within the world.

Some other options:

* Display the point so the user knows what they're rotating around/looking at
* Tether it to the ground of the world (if applicable/possible)

You seem to understand how the other tools work with the exception of figuring out the point. So, I would say just implement the point in a way that makes sense and works for your world editor.
> 1 votes

---
Tags: camera, map-editor
---


# Question
Title: Random seed function for map generation?
I am looking for a function to generate a random tile-based map as the visual boundaries of the map change (by going through the map). I want the map to be infinitely large, and have maze-like structure.

However, if the world is infinite, going back to where a player has already been before raises a problem. The game must remember how everything back there actually looked like.

So, I was thinking - "How does Minecraft solve this issue?" and I thought to myself that they must be using some kind of random-number function with a seed, that can both go forward but also backwards, and in that way, re-generate old tiles exactly as they were, but in new instances.

What are your thoughts on this?

# Answer
> 21 votes
What you've noticed is the difference between a random number generator and a noise function. A random number generator spits out a different number each time you call it. A noise function takes some arguments - say, a map x and y - and spits out numbers with *random-like statistical properties*, but *the same value for the same arguments every time*, i.e. it is a proper mathematical function.

The two are very closely related. A noise function can simulate a random number generator, by passing in a different value each time - e.g. `noise(1)`, `noise(2)`, and so on. And a random number generator, dumped into a giant table, can act as a noise function. In both cases though, you're using the wrong tool for the job.

Minecraft in particular uses Perlin noise, a type of noise which is cheap to compute, and has a desirable property of being *continuous* in as many dimensions as you need - if you graph `f(x)` to `f(x + 1)`, there won't be any sudden jumps. This makes it very useful for many things like texture modulation, volumetric clouds and gases, and terrain generation.

If you are looking for an implementation to start playing with, Ken Perlin's improved Perlin noise generator is one of the simplest implementations.

# Answer
> 3 votes
The way Minecraft controls its generation is by creating a level seed which is used to seed all the random number generation for the game. If a chunk doesn't exist on disk when it is requested, it will be generated using Notch's generation function based on the level's seed; it's then saved to disk for later.

It sounds like you're looking to achieve similar behaviour, so that's a safe way to go.

# Answer
> 2 votes
As Joe pointed out, you're looking for a hash function. Generally, random functions are just hash functions seeded with the last returned number. So if `Random()` returned `Hash(seed)=1234`, a second call `Random()` would return `Hash(1234)`, at so on.

If you're looking for a simple hashing function for pseudo random numbers, check out MurMurHash. I've implemented it in C# and can post it somewhere if you're interested. More detailed information of Perlin Noise, which uses such a hash function, can be found at here, and an implementation of it in C# is here.

All of this information came from a question I asked a year ago here on Stack Overflow. What you're looking into is called procedural content generation, so if you need more information, do a search for that. Happy terrain-generating!

---
Tags: tiles, random, minecraft-modding, tilemap
---


# Question
Title: Common mistakes when developing a game with Socket.io and Node.js
I am not a game developer by trade but am working on a card game (that is real time, not turn based). I was wondering what the common mistakes are that people make when new to this sort of development so that I can avoid them!

# Answer
There is a Google Techtalk featuring Rob Hawkes, creator of Rawkets, who talks about the problems he ran into while creating his game with Websockets and Node.js. He also comes up with some pretty slick solutions for the problems that he faced.
> 8 votes

# Answer
The biggest mistake, is simply playing the games on the client side, and allowing them to communicate their information as they see it. Have the clients simply communicate their input, and render a model sent from the server at discrete intervals. (Store these models in an array with a server-timestamp, then interpolate between two known timestamps to render all actors everyframe)

I have created a framework specifically for creating HTML5 realtime multiplayer games, based on the Client/Server model. In this model, players send only input to the server (keys being pressed) - and the game occurs on the server.

The server sends timed world-snapshots to all clients, and clients render themselves say 75 ms back in time from the current time, by finding two known world updates their rendertime falls between.

Repository (contains 3 demos) https://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs

Video Box2D demo in action: http://vimeo.com/24149718

Slides from JSConf 2011: http://www.slideshare.net/MarioGonzalez15/realtime-html5-multiplayergameswithnodejs-7868336

It's based on Quakeworld and Valve's Source engine whitepapers: http://fabiensanglard.net/quakeSource/index.php http://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking
> 8 votes

---
Tags: node.js
---


# Question
Title: How to coordinate sprites, player's position and collisions in a Bomberman-like 2D game?
I'm programming a Bomberman in Java (my first game) and I'm having problems with the player's sprites and position in the map. I'm using a 2D integer array to represent:

* Unbreakable blocks
* Explodable brick walls
* Free spaces
* Player itself (not sure if this is correct)

By now I could correctly place every background tile (40\*40 each) iterating the array. Bomberman's sprites are MAX 40\*40 (sometimes a little smaller). My question is, how can I correctly handle the collisions with walls? I already tried to do it, but that solution was very horribly buggy.

Thanks in advance.

# Answer
> 2 votes
I'd store the positions of items as integers as you are doing now in a array. Testing for a collision with a wall could be as simple as testing the map array for the wall piece, for example:

```
if(map[player_x+1][player_y]!=WALL)
{
  // player can move right
}

```

If you need certain sprites to move between tiles smoothly such as bomberman himself or sliding bombs you could store an additional offset as a float.

# Answer
> 2 votes
I made an attempt to answer your question on your original post, on Stack Overflow:

If you are simply using the array to represent a game grid (so that the player can not be inbetween blocks other than for animation purposes), then it would be extremely efficient to simply check the space the player wants to move to (can only be 4 spaces, up, left, right, or down), see if they are passable terrain, and then allow the player to move there.

This is how I am imagining your board to look, please let me know if this is incorrect:

```
W W W
O P O
W O W

```

(A 3 by 3 visualization of the array; `W` represents a wall, `O` represents open space, and `P` represents the player)

for this example I'm going to assume that the top-left corner is represented by `locationArray[0][0]` and the bottom-right is `locationArray[2][2]`. `X` is the first array parameter, `Y` is the second.

The player is at `locationArray[1][1]`

In the above case, if the player opted to move left, you would check the array location to his left, `locationArray[2][1]`, find it open, and allow the player to move.

If the player opted to move up, `locationArray[1][0]`, the check would not allow the player to move, as it is impassable terrain (a wall).

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


# Question
Title: Objective-C to Java conversion for porting iPhone apps to Android?
can anybody help me to convert this objective-c code to android java.

```
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (_mouseJoint != NULL) return;

    UITouch *myTouch = [touches anyObject];

    CGPoint location = [myTouch locationInView:[myTouch view]];

    location = [[CCDirector sharedDirector] convertToGL:location];

    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

    if (_paddleFixture->TestPoint(locationWorld)) {

        b2MouseJointDef md;
        md.bodyA = _groundBody;
        md.bodyB = _paddleBody;
        md.target = locationWorld;
        md.collideConnected = true;
        md.maxForce = 1000.0f * _paddleBody->GetMass();

        _mouseJoint = (b2MouseJoint *)_world->CreateJoint(&md);
        _paddleBody->SetAwake(true);
    }

}

```

I tried below is my code but getting exception. java.lang.nullpointer . Is anything wrong ?

```
public boolean ccTouchesBegan(MotionEvent event) {

         if (_mouseJoint != null){
             return true;

        }
         else{

         CGPoint convertedLocation = CCDirector.sharedDirector().convertToGL(CGPoint.make(event.getX(), event.getY()));
         Vector2 locationWorld = new Vector2(convertedLocation.x/PTM_RATIO, convertedLocation.y/PTM_RATIO);

         // return CCTouchDispatcher.kEventHandled;
           //_mouseJoint.setTarget(locationWorld);

        if(_paddleFixture.testPoint(locationWorld)){

             MouseJointDef md = new MouseJointDef();
             md.bodyA = _body;
             md.bodyB = _paddleBody;
             md.target.set(locationWorld);
             md.collideConnected = true;
             md.maxForce = (float)(1000.0f * _paddleBody.getMass());
             _mouseJoint =  (MouseJoint) _world.createJoint(md);
             _paddleBody.setAwake(true);
         }
        }
     //return CCTouchDispatcher.kEventHandled;

        return true;
    }

```

# Answer
The key difference between obj-c and pretty much any other language is that you don't have to check for `null` (or `nil` in obj-c). Basically you need to see what line your exception is occurring on, and wrap that with a null check.
> 0 votes

---
Tags: android, cocos2d
---


# Question
Title: OpenGL Vertex Attributes - Normalisation
Alas, I have searched, and have found no definitive answer.

When would you normalize the vertex data in OpenGL using the following command:

```
glVertexAttribPointer(index, size, type, normalize, stride, pointer);

```

I.e when would `normalize == GL_TRUE`; what situations, and why would you choose to let the GPU do the calculations instead of preprocessing it? All examples I have ever seen, have this set to GL\_FALSE; and I cannot personally see a use for it. But Khronos aren't stupid, so it must be there for something useful (and probably common).

# Answer
The "normalized" parameter affects the use of fixed point values.

This doc says the parameter "Specifies whether fixed-point data values should be normalized (GL\_TRUE) or converted directly as fixed-point values (GL\_FALSE) when they are accessed."

Further, this one states "For glVertexAttribPointer, if normalized is set to GL\_TRUE, it indicates that values stored in an integer format are to be mapped to the range \[-1,1\] (for signed values) or \[0,1\] (for unsigned values) when they are accessed and converted to floating point. Otherwise, values will be converted to floats directly without normalization."

In summary, if you're not using fixed point values, you don't need to care. If you do, this flag controls whether (for example) byte value 128 should be 0.5 or 128.0.
> 9 votes

# Answer
This is an old question, but the current answer doesn't really explain what you would use them for.

It's all about saving space. And with vertex attributes, less space can mean higher performance (if you're vertex transfer bound).

Colors typically don't need much more than 8-bits per component. Sometimes you need 16-bits, if it's a HDR light value or something. But for surface characteristics (which is what most vertex attributes are), 8 bits is fine. So unsigned normalized bytes are a good vertex format.

Texture coordinates do not need 32-bits of floating-point precision. A 16-bit value from \[0, 1\] is sufficient. So normalized unsigned shorts are a reasonable vertex format.

Normals *never* need 32-bits of precision. They're directions. 8-bit signed normalized bytes tend to be a bit small, but 10-bit normalized values are good enough most of the time. OpenGL (3.3+) even allows you to use 10-bit normals via a 10/10/10/2 bit packed format, stored in a single 32-bit unsigned integer.

You can even play games with vertex positions, if you find yourself in grave need of more memory.

Without normalization, you would have to waste precious cycles in your shader dividing byte attributes by 255.0. Why do this, when the hardware can do it *for free?*
> 12 votes

# Answer
Imagine you have a mesh with high-precision normals and another mesh with low. With attribute normalization you can use the same shader but pack the second mesh's normals in bytes.
> 0 votes

---
Tags: opengl, c, vertex
---


# Question
Title: How do I make a resolution independent system?
I'm blanking on this one. I can anchor stuff on edges of course, that would make my UI resolution independent...until it changes so much that the graphics are too small. How do I scale appropriately whenever needed? How do I keep my graphics at the right proportion while scaling? I don't want them stretched if the resolution has a different proportion like 16:10 as opposed to whatever else.

Is there a true and tested approach to this? Video players show black borders because of this problem, is this not properly solvable?

# Answer
> 5 votes
First keep in mind that with rasterization there technically is no such thing as true resolution independence. With high enough magnification individual texels will start to become visible. The only solution to this is to write a vector graphics system.

That being said there are a few steps to creating a robust raster based resolution independent system: sizing, coordinate systems, and layout.

For sizing and positioning we need to use some set of units that maintain a ratio to the actual application resolution. In this case lets use inches because I'm American and you can scale elements with DPI (dots per inch). For example lets say your application is running at 800x600. Default Windows DPI is 96 so that means the application has a resolution of (800 / 96) x (600 / 96) inches or 8.33x6.25 inches.

Since you need to be able to work with, at the very least, both 4:3 and 16:9 aspect ratios how you handle your screen coordinate system gets a little bit tricky. What I recommend doing is putting (0,0) in the center of the display area (as well as windows and controls). This works well because if you put (0,0) in a corner then as that corner moves around based on resolution and aspect ratio it's going to translate all of your sprites whereas the center of the screen will always be the center of the screen no matter the device. Continuing our example with 800x600 this would result in a coordinate system that is (left to right) -4.165in to 4.165in and (top to bottom) 3.125in to -3.125in.

So at the moment you have DPI independent UI system with items that will always be at the same spot relative to the center of the screen - not quite resolution independent. Fortunately what DPI independence allows you to do is scale the UI by scaling DPI based on some heuristic. For example we can scale DPI using vertical resolution as our heuristic. If 800x600 is 96 DPI then we'll use 123 DPI for 1024x768 or 115 DPI for 1280x720.

Lastly you will need to build a layout system that handles both absolute positioning as well as relative positioning. Excellent examples of this are WPF and the web. You can specify that controls/boxes fill some % of the parent element while docking it to an edge along with many other useful automatic layout options. All of this together will result in a UI system capable of looking nearly identical across many different resolutions and aspect ratios.

To summarize I highly recommend you study WPF as it does nearly all of this except it maintains an origin at the top-left corner coordinate system and doesn't automatically scale DPI based on vertical resolution.

# Answer
> -1 votes
Generally what you'd want to do depends on the game.

One option is to have black borders if the aspect ratio (proportion) is different (probably easiest, just render to texture, then render that to screen, resizing as appropriate).

Another option is to have different render paths for different aspect ratios. You could have one for widescreen, one for 'normal'.

Yet another option is to scale things separately, e.g. make a UI message box larger or smaller depending on resolution. Whenever you need to work out where to draw to, instead of using exact pixels, do things like 0.2 down, 0.8 across, width 0.1, height 0.3. Ovbiously in this case you'd get stretching of things, although depending on how you're drawing things that could be fine (i.e. stretch a UI background, but not the text).

In terms of 3D, as long as you set the viewport up correctly you should end up with widescreen players being able to see slightly more than non-widescreen setups. (alternatively draw black borders / or stretch the view).

---
Tags: xna, resolution
---


title: XNA - multiple VertexBuffers?

text:
# Question
Title: XNA - multiple VertexBuffers?
I'm trying to learn how to use VertexBuffers in XNA 4.0. I can render wireframe shapes and I can render textured shapes. However, I'm having some trouble rendering them both at once. I'm initializing the buffers like this:

```
vertexBuffer1 = new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationWireframe, numPointsWireframe, BufferUsage.None);
vertexBuffer1.SetData<VertexPositionColor>(pointList1);

vertexBuffer3 = new VertexBuffer(graphics.GraphicsDevice, vertexDeclarationTexture, numPointsTexture, BufferUsage.None);
vertexBuffer3.SetData<VertexPositionTexture>(pointList3);

```

The above code fails during Draw() because the vertex buffers are using two different types of vertexDeclarations, one for wireframe (VertexPositionColor) and one for textures (VertexPositionTexture). I tried moving the call to VertexBuffer.SetData() to just before the relevant geometry is drawn but that didn't work.

I've also tried setting my Effect object TextureEnabled = false when wireframe is being rendered and resetting it when the textured geometry is rendering, but that didn't work either. The effect seems to be expecting a TextureCoordinate regardless.

What's the proper way to do this?

# Answer
> 1 votes
All you need to do is set a new RasterizerState object on your GraphicsDevice that specifies wireframe (or not). Specifically to accomplish what you're trying to do here are the steps:

1. Draw your vertex buffer with depth & depth write enabled and filled shading
2. On your GraphicsDevice object set a new RasterizerState that specifies wireframe and a new DepthStencilState that disables both depth testing and depth writing
3. Draw the same vertex buffer again but use a different effect. For example when you draw the wireframe mesh only output a constant color or maybe just vertex colors. If you don't change the Effect being used then the wireframe mesh won't show up because it'll be the same color as the original.

This is all accomplished with only 1 vertex buffer.

---
Tags: xna, shaders, vertex, effect
---


# Question
Title: C# XNA Framework Paddle Collision Problems
I am trying to make a pong game that uses a burger as a ball and a plate as its paddle. I have everything right except that the burger goes right through the plate. Can anyone help me?

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Burger_Attack_Mitch_McCauley
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GameSprite myGameSprite;
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D imageBurger;
        Texture2D imagePlate;
        Texture2D imageStart;
        Texture2D imageEnd;

        KeyboardState keyState_01;
        KeyboardState keyState_01_Old;

        GamePadState pad_01;
        GamePadState pad_01_Old;

        int intGameState;

        GameSprite spriteStartScreen_01;
        GameSprite spriteEndScreen_01;
        GameSprite spritePlate;
        GameSprite spriteBurger;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {

            // TODO: Add your initialization logic here

            myGameSprite = new GameSprite();

            spriteStartScreen_01 = new GameSprite();
            spriteEndScreen_01 = new GameSprite();
            spritePlate = new GameSprite(300, 425, 150, 50);
            spriteBurger = new GameSprite(300, 300, 150, 100, 1, -1);

            intGameState = 5;

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            imageBurger = Content.Load<Texture2D>("Images\\DeathBurger");
            imagePlate = Content.Load<Texture2D>("Images\\Plate");
            imageStart = Content.Load<Texture2D>("Images\\StartScreen_01");
            imageEnd = Content.Load<Texture2D>("Images\\EndScreen_01");

            spriteStartScreen_01.spriteTexture = imageStart;
            spriteEndScreen_01.spriteTexture = imageEnd;
            spriteBurger.spriteTexture = imageBurger;
            spritePlate.spriteTexture = imagePlate;

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            GetUserInput();
            ChangeGameState();

            switch (intGameState)
            {
                case 5:
                    break;

                case 86:
                    break;
                default:
                    MoveUserControlledSprites();
                    MoveSprites();
                    TestForCollisions();
                    break;
            }

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            switch (intGameState)
            {
                case 5:
                    spriteBatch.Draw(spriteStartScreen_01.spriteTexture,
                        spriteStartScreen_01.spritePos, Color.White);
                    break;

                case 86:
                    spriteBatch.Draw(spriteEndScreen_01.spriteTexture,
                        spriteEndScreen_01.spritePos, Color.White);
                    break;
                default:

                    spriteBatch.Draw(spriteBurger.spriteTexture,
                        spriteBurger.spritePos, Color.White);
                    spriteBatch.Draw(spritePlate.spriteTexture,
                        spritePlate.spritePos, Color.White);
                    break;
            }
            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
        private void GetUserInput()
        {
            keyState_01_Old = keyState_01;
            pad_01_Old = pad_01;

            keyState_01 = Keyboard.GetState();
            pad_01 = GamePad.GetState(PlayerIndex.One);
        }

            private void ChangeGameState()
            {if (intGameState == 5 &&
                pad_01.Buttons.B == ButtonState.Pressed &&
                pad_01_Old.Buttons.B == ButtonState.Released)
            {
                intGameState = 10;
            }
                if (intGameState == 5 &&
                    keyState_01.IsKeyDown (Keys.Space) &&
                    keyState_01_Old.IsKeyUp(Keys.Space))
                {
                    intGameState = 10;
                }

                if (intGameState == 86 &&
                    pad_01.Buttons.B == ButtonState. Pressed &&
                        pad_01_Old.Buttons.B == ButtonState.Released)
                {
                    intGameState = 5;
                    spriteBurger.spritePos.X = 300;
                    spriteBurger.spritePos.Y = 0;
                }

                if (intGameState == 86 &&
                    keyState_01.IsKeyDown(Keys.Space) &&
                    keyState_01_Old.IsKeyUp(Keys.Space))
                {
                    intGameState = 5;
                    spriteBurger.spritePos.X = 300;
                    spriteBurger.spritePos.Y = 0;
                }
            }
                private void MoveSprites()
                {
                    if (spriteBurger.spritePos.X <= 0)
                    {
                        spriteBurger.spriteSpeed.X = 2;
                    }
                    if (spriteBurger.spriteSpeed.Y <= 0)
                    {
                        spriteBurger.spriteSpeed.Y = 2;
                    }
                    if (spriteBurger.spritePos.X +
                        spriteBurger.spriteDims.X >=
                        Window.ClientBounds.Width)
                    {
                        spriteBurger.spriteSpeed.X = -2;
                    }
                    if (spriteBurger.spritePos.Y +
                        spriteBurger.spriteDims.Y >+
                        Window.ClientBounds.Height)
                    {
                        intGameState = 86;
                    }
                    spriteBurger.spritePos.X += spriteBurger.spriteSpeed.X;
                    spriteBurger.spritePos.Y += spriteBurger.spriteSpeed.Y;
                }
        private void MoveUserControlledSprites()
        {
            if (keyState_01.IsKeyDown(Keys.Left))
            {
                spritePlate.spritePos.X -= 3;
            }
            if (keyState_01.IsKeyDown(Keys.Right))
            {
                spritePlate.spritePos.X += 3;
            }

            spritePlate.spritePos.X += pad_01.ThumbSticks.Right.X * 5;

            if (spritePlate.spritePos.X < 0)
            {
                spritePlate.spritePos.X = 0;
            }

            if (Window.ClientBounds.Width < (spritePlate.spritePos.X + spritePlate.spriteDims.X))
            {
                spritePlate.spritePos.X = (Window.ClientBounds.Width - spritePlate.spriteDims.X);
            }
        }

        private void TestForCollisions()
        {
            Rectangle plateRect = new Rectangle(
                (int)spritePlate.spritePos.X,
                (int)spritePlate.spritePos.Y,
                (int)spritePlate.spriteDims.X,
                (int)spritePlate.spriteDims.Y);

            Rectangle burgerRect = new Rectangle(
                (int)spriteBurger.spritePos.X,
                (int)spriteBurger.spritePos.Y,
                (int)spriteBurger.spriteDims.X,
                (int)spriteBurger.spriteDims.Y);

            if (plateRect.Intersects(burgerRect))
            {
                spriteBurger.spriteSpeed.Y = -1 *
                    Math.Abs(spriteBurger.spriteSpeed.Y);
            }
        }

            }

    }

```

# Answer
> 4 votes
Mitch, you're going to run into a lot of similar problems on your way to the finished game. It's often pointless to ask others to debug your code, especially when it's not so hard to do it yourself. Like they say, “Teach a man to fish; and you will not have to listen to his questions about debugging basics”, so lets do a debugging 101:

You say that a ball goes right trough a paddle. A simple assumption can be made that either collision check via rectangle bounds or reaction to the ball after collision is wrong. Lets see if its one of these cases:

1. Place a breakpoint in the body of condition `if (plateRect.Intersects(burgerRect)) {...}` and see if it hits.
2. If it does hit, collision is working and your modification of ball's coordinates does not work.
3. If it doesn't hit, collision is not working. Place a breakpoint after creation of your two bounding rectangles and check their properties, especially this spriteDims thingies.
4. If everything is seemingly fine, look at your sources again, check every coordinate assignment, breakpoint every line if you have to, and sooner or later you will catch a bug :)

Further down the development process you will probably want to increase difficulty over time by increasing your ball's speed, and at one point it may start going through paddle again :)

When collisions are done with a naive collision check and assignments like `spritePos.Y += spriteSpeed.Y`, your ball can go right through paddle even if everything is seemingly right; e.g. if a ball's position is increased by a number which is larger than a paddle's bounding rectangle dimension. You may want to google "collision detection", there are a lot of good things to read.

# Answer
> 1 votes
When your spriteBurger.spriteSpeed is set to -2 (when it's moving upwards I'm guessing) the following line of code you have won't have any effect:

```
spriteBurger.spriteSpeed.Y = -1 * Math.Abs(spriteBurger.spriteSpeed.Y);

```

This is because you're essentially saying -1 * 2 which equals -2, which is where you started.

You can simply use the following code to reverse the direction your spriteBurger is going:

```
spriteBurger.spriteSpeed.Y = -spriteBurger.spriteSpeed.Y;

```

Based on looking at the code above though, I don't think spriteBurger.spriteSpeed.Y is ever set to -2 so I'm not sure what the change above will do for you.

---
Tags: xna, c#, collision-detection
---


title: Batch blit vs separate blit

text:
# Question
Title: Batch blit vs separate blit
A tutorial that I have followed had me collect and blit all of my sprites with the following lines:

```
allsprites = pygame.sprite.RenderPlain((l_sprites))
allsprites.draw()

```

At the moment, this is fine for me, as all of my sprites make use of the same base image. However, I find myself in need of having various sprites animated, some changing, and some going to a basic colored rectangle.

My question is if this batch drawing method is still viable when all of my sprites are in flux. My previous experience has been in straight C with SDL, and normally I would simply roll my own update loop.

# Answer
The `Group` class (for which `RenderPlain` has been a deprecated alias for many years) is more a logical tool than a performance tool. It provides no speed benefit over looping over the sprites yourself. If you are constructing it every frame, it's definitely a net negative.

What you should do instead is replace your `l_sprites` list of sprites with a group directly. Rather than appending sprites to the list, add them to the group. This lets you use Group.update to update the sprites rather than rolling your own update loop. It also lets sprites remove themselves from the group using Sprite.kill, which is often a more convenient way to remove them.

If you want a performance gain out of using sprite groups, you should turn to RenderUpdates, which returns a list of rectangles appropriate for passing to pygame.display.update.

(If you want good performance, you should give up Pygame's sprite library and turn to OpenGL or one of its Python wrappers instead.)
> 3 votes

---
Tags: python, pygame
---


# Question
Title: 2D physics library that supports curved surfaces and inverse or boolean shapes?
I've been using box2D for a few months, but I now badly need a physics library which can use boolean shapes (ie; cutting a circle out of a square) and/or curved surfaces. Does anyone have any suggestions?

Edit: Language is c++

# Answer
> 4 votes
Have you considered combining standard box2d shapes/fixtures and convex polygon attaching them to same body?

If you want you can even implement concave decomposition algorithms like the ones provided by this .NET(C#) Box2d port (at the bottom, it also supports some boolean operations):

https://github.com/Genbox/VelcroPhysics

PS: there should be some performance/complexity reason(s) for not supporting concave polygons as is.

# Answer
> 1 votes
I'm not sure there's such a thing as what you're describing. Everything is/can be made out of convex shapes, especially in graphics/physics math (this makes operating on bodies much easier)

It's more about finding, making, and implementing algorithms that break complex shapes down into as few simple shapes as possible. This is called **Polygon Partitioning**, and to do this i would suggest this simple, nearly includable library:

Physics math can much more accurately work with curved items such as circles though, as there are very quick equations when shapes have a common radius. I would suggest simply putting **circles (or only a section of a cirlce) and polygons** together to form whatever curved, pointy, or other crazy shapes you want to make. *And again there are most likely algorithms for this out there even now.*

you can also put "holes" into shapes by adding a "hole" shape to a body, and then test at run time whether a colliding shape is inside the whole or not. Then don't do any collision if it is.

also if you didn't know; **sine and cos waves** are very helpful for making curved hills and such.

# Answer
> 1 votes
> I now badly need a physics library which can use boolean shapes (ie; cutting a circle out of a square) and/or curved surfaces

The term you are looking for is

* (2D) CPG -- constructive planar geometry
* (3D) CSG -- constructive solid geometry

If you can live without curves (at least in your cut-out areas), go for the approach @Den suggests.

If you need to be able to slice polygons along curves, you are pretty much going to have to find a CSG library such as GPC. And you are going to have to be able to find one that supports splines in its intersections. And then you are going to have to transport that spline data into Box2D. And be warned -- good CPG libraries cost several hundred to several thousand dollars. There are free ones out there but they are by no means as full featured or as well optimised (in general, though they are not intended for real time use).

One thing I will warn you on -- if you don't have *at minimum* a graduate level background in mathematics, do not attempt a custom solution to the polygon intersection problem at home. There is a reason they charge big bucks for these solutions.

---
Tags: c++, physics
---


title: Red5 or zendZMF or BlazeDS or Cirrus?

text:
# Question
Title: Red5 or zendZMF or BlazeDS or Cirrus?
I've been trying to develop a multiplayer turn based game which is mostly free to play - I just want to see if the game idea is appreciated - hence I want to do it with minimal cost and I'm confused which one of these to use: red5, zendamf, BlazeDS or Cirrus.

Red5 seemed the best option for me initially but getting a media server to host seems to be quite expensive. Same reason why I couldn't use Electroserver - cost. Both are very attractive options though.

ZendAMF then looked a feasible option since it supported remoting. But how do I let the other players get updates on actions of one player through zendAMF, which as far as I know does not do data push. I'll have to do it by polling - asking server constantly for updates - which wont look very real time.

Then I heard about BlazeDS which does support data push. Now I have to learn java if I want to use that and get a new web host because my existing host does not have tomcat.

Then I heard about cirrus which is still in 'codename cirrus' stage. It looks like a very feasible option since its peer to peer with miniamal server support needed. Is it good for a mutiplayer game?

Well if anyone has experience developing multiplayer flash games I'd like to know if a turn based multiplayer game with more than two players participating can be implemented using zendamf. ZendAMF because I know PHP and AS3.

# Answer
I've implemented the game using cirrus. Its free, atleast for now. No need to change my hosting server - its a simple php-mysql web server. I also use zendAMF in the backend - so the solution is a combination of zendAMF + Cirrus. With Red5 and BlazeDS I'd need to find a new hosting service which is a needless expense.
> 0 votes

# Answer
Try NodeJs, it may fit your realtime needs, because you already know AS3 which shares many similarities with Javascript since they're both ECMAScript languages.
> 1 votes

# Answer
I have some experience with Red5. It is similar to BlazeDS in that it uses a Tomcat server. It has a built-in Tomcat server but I've heard some people got it to run on a stand-alone Tomcat (7) server. That would be an option if you find a host that provides Tomcat.

You can probably keep the Java code to a minimum by having Red5 provide no more than a gateway to pass (remote procedure call or state update) messages. I think there are standard classes that already do something like that, but I have no experience with them.
> 1 votes

# Answer
I have no experience of any of the above solutions but I would like to suggest a solution that fits your need.

Take a look at http://www.gamooga.com/. Its a hosted communication framework for realtime apps and multiplayer games. You will need to just upload your server side code to Gamooga website, no infrastructure or hosting required.

It provides you with Flash API that you can use to connect from your frontend to Gamooga backend. On the server side, you have to implement your logic in Lua, and there are good demos that you can look at for help.
> 0 votes

---
Tags: flash, multiplayer, server, hosting
---


title: Points in d3d11

text:
# Question
Title: Points in d3d11
D3D10/D3D11 drops support for point primitives. I'm trying to render a set of points for quick and dirty debug, any suggestions/quick hacks for getting large size points to show up in D3D11?

# Answer
Ok, hold on, there's still D3D11\_PRIMITIVE\_TOPOLOGY\_POINTLIST, not sure why I was under the impression D3D11 didn't support point primitives.
> 1 votes

---
Tags: directx11, point-cloud
---


title: An ellipse outside two points?

text:
# Question
Title: An ellipse outside two points?
I am trying to generate an ellipse outside two points (two-dimensional vectors).

Is there a formular for that, or a cool way of doing that in C# XNA?

What I am trying to do is have a particle circle around one player and another.

# Answer
> 2 votes
One approach would be to consider the coordinates of the two entities (the player and the opponent) to be somewhere on the major axis of the ellipse, preferably placed such that their visual extents do not intersect with the intended ellipse. From that you should be able to compute the extents of the major axis. The minor axis is then derivable from the major axis by multiplying the extent of the major axis by some aspect ratio.

Once you have the equation for a parametric ellipse, you can sample along it to compute coordinates suitable for particle placement - if you combine this with some perturbation of the equation you can probably get some nice artistic control over the effect.

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