# Question
Title: Where can I find a free dictionary of words?
Hi I'm writing a game where the player has to connect a group of letters to form words. Something like bookworm but it will be very different I hope.

The point of the question is that I need to build a dictionary of words.

I made a simple java program that crawls the web and extracts words, but a lot of trash is mixed with the good words and it's impossible to clean it. I'm talking about 100,000 words.

Is there any dictionary available that can be freely used or anybody has an idea of how to build one?

Thanks!

# Answer
This website has a list of 58,112 (British) English words available in uppercase or lowercase formats.

This other website has a variety of word lists available, but I'd recommend checking out the "Official 12Dicts Package", which can be downloaded from here, as it has been rigorously checked for errors and provides better documentation than most lists out there. The lists in this package contain approximately 40,000 words.

In terms of minimal effort on your part, I believe the resources above are probably your best solution
> 9 votes

# Answer
The following site is attempting to accumulate links to different open dictionary projects. If I understand what they're doing correctly, they are offering dictionary packages that you could potentially download and read with your application. Hopefully this leads you in a helpful direction.

Open Dictionary Databases
> 7 votes

# Answer
The Moby project is the biggest one I know of. It's also the source for Fedora's "words" package for example, at least in English.
> 6 votes

# Answer
This one seems pretty nice, though I don't know about compared to others.

Seems to be in an easily parsable and readable format too.
> 3 votes

# Answer
I performed something recently where i ripped every word out of war and peace whilst it does not contain every single word in the dictionary it does have the added benefit of being able to tally word usage to get an idea of usage distribution you will also find slang words and names however, although these can be filtered rather simply
> 0 votes

---
Tags: assets
---


title: Spreadsheets in Game Design?

text:
# Question
Title: Spreadsheets in Game Design?
There have been two instances from the past two weeks that I've heard from well known successful game developers that they use spreadsheets when designing games.

The first being David Whatley in this GDCVault video: From Zero to Time Magazine: App Success

The second being the guys that do Walled Garden Weekly.

David said he models everything out and uses excel models to see how everything plays out. What on earth is he talking about? Is it seeing how the game mechanics react to each other?

Is there somewhere where I can learn more about how to do this?

# Answer
> 27 votes
To give an example where spreadsheets make sense for game balancing: I am currently developing an RPG. I wanted to design a formula for the experience needed to reach each character level. My goal was that each level takes a bit longer to reach than the previous one, even though the character is stronger with each level and thus makes more exp per minute.

So I created a spreadsheet with a row for each level and the columns "EXP to next" and "expected EXP per minute" which were a function of the level. The third row "minutes per level" was calculated from the previous two. That way I could easily see how much time the player will spend on each level with my exp per level formula.

My first formula used to calculate "EXP to next" in fact resulted in a **decrease** of the time spent on later levels, because I underestimated how much more exp high level characters will make. So I changed the formula from quadratic to exponential. That fixed it, but now the lower levels only took seconds. Adding a multiplication factor got nice numbers for the lower levels, but levels above 60 took several years to reach, which was rather overshooting my goal.

After a lot more fiddling around, I finally got a pretty nice formula which did what I wanted. Simulating all those formulas in a spreadsheet surely saved me weeks of playtesting.

Some random examples from other genres where using spreadsheets could makes sense:

* **Side-scrolling shoot-em-up**: Average lifetime of each enemy ship when the player concentrates its firepower on it. Important to see how many new enemies per second are still manageable.
* **Real-time strategy**: Simulating combat of each unit against every other one to see which one wins with how much health left. Check these results against the unit costs to get a hint which ones might be over- or underpriced.
* **4X**: Model economical growth over time and research progress over time to find a fair cost for each new unit/facility which becomes available.

# Answer
> 4 votes
The spreadsheet is employed to simulate the game internal economy and maybe other closely related stuff.

If you need a more visual tool to do that, check Joris Dormans framework called Machinations. You can even do part of the mechanics in there.

http://www.jorisdormans.nl/machinations/

# Answer
> 2 votes
I use excel in many ways to balance the game economy etc...

We also use it in level design, we list out all the mechanics on the columns, and all the levels on the rows and X off where we should plan to use the feature in the levels. This way they are appropriately scaled; this way its easy to tell if you have too many mechanics, or if there is a mechanic that is getting too much/not enough use.

# Answer
> 1 votes
I once used Excel to help a designer give me a list of simple football plays for a football mini-game.

Basically the requirements were for 8-10 destination sets for 6 linesmen on the field. The game itself (engine and all) was still under heavy development.

I took an image of a football field and aligned it so that the coordinates were the same as in game, then made a point graph overlay to represent the positions of the linesmen. The designer, then simply needed to type in the coordinates that he wanted by trial and error.

Of course instead of using this tool, he played around with photoshop leading to yet more iteration, but that's beside the point. The point is that Excel is extremely general purpose and can be used for almost anything.

# Answer
> 1 votes
This is an economy balance spreadsheet by Net Jacobsson.

https://docs.google.com/spreadsheet/ccc?key=0Aj7KDHJLUaEJdDhPTmJQS2tPMjNnSVhpV1VLOENKTHc&hl=en#gid=0

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


# Question
Title: Checking game objective status in efficient way on each update call
I am creating a 2d mobile game where there are three levels. Each level has 20 objectives. This can increase in the future.

Examples:

```
Level 1
Current Objective: 2/20
Objective : Collect 1000 coins
Rewards: 100  coins.

Level 1
Current Objective: 20/20
Objective : Kill 100 aliens
Rewards: Shotgun

```

The question is, when a user is playing a game, how do you check if he has already completed his current objective in efficient way? This is not involving any third party listener like GameCenter, Scoreloop, etc.

I do not want to have a method with zillions of switch/if-else/or any other conditional blocks to be checked in every update call since this will affect the FPS. Some frameworks are not thread-safe. So having a separate thread is not an option either since I am going to port it to some other platforms using some other frameworks.

How do I go about it?

# Answer
**Premature optimization and design paralysis are evil. Don't fall into the trap of worrying about a simple check. If you're concerned, implement and profile.**

I think you're under-estimating how powerful hardware can be - even the low-end hardware. An if statement comparing a simple boolean is pretty cheap and should be the least of your concerns in a game. I agree that checking for the condition every frame isn't ideal - but there a lot of difference ways you can circumvent this if you're that concerned. The check is extremely cheap and many others have went over this - but I'll try to give yet another detailed explanation. You've tagged this under Java and C++ and mentioned Android 1.5 in a comment - so presumably that is your target.

**Check only when necessary.** If you have an objective that is obtain a score of 10, 000 points; add a check on your setter for score or add a callback to the achievement manager, preferably to verify this. The objective manager would just be a simple hash map of enums and booleans; (I picked hash map for the fast lookup times) the callback makes a quick lookup into this table and sets it to unlocked if needed.

**Optimize for the game objectives.** If your game objective is "kill 5 ships", keep a counter of the alive ships left; don't query the game state directly. Evaluate the state deltas as they are completed so you don't have to do an expensive computation all at once. This is handy if your objective requires a lot of spatial probing that might be expensive. Does every yellow box need to be touching a green box? On collision, set a flag to determine this and then unset it when the object moves off. Keep the state easy to access and query.

**Defer the check.** If your check is more expensive than a single lookup and a few comparisons (expensive property getters, functions or lots of checks) and you really think you can't optimize the checks, then you can always defer your check. Your game likely has states that are idle or the player is not doing a whole lot. It's tough to say without knowing your game - but let me give a general gist.

We'll use *Angry Birds* as a quick example here to illustrate the purpose. Angry Birds probably has a lot of states in its state machine - but for simplification reasons we're going to assume just two.

The first state is when the birds are resting on the slingshot; they're idle and not doing anything and just waiting for user input. Not a lot of stuff is going and small FPS drops would go unnoticed the minute this state is transitioned to.

The second state is of course when the bird is flying through the air. After this state finishes (the bird has finished flight), the game transits back to the slingshot (state 1) and checks to see if all the pigs have seen defeat.

The idea of deferring the objective checks works exactly like Angry Birds does - you can queue up plausible objective checks that could have happened during that state and then you verify later when the load is acceptable and the end user won't notice any obvious frame drops.
> 5 votes

# Answer
You should create an achievement system for observing the rules and performing the necessary checks

How can I set up a flexible framework for handling achievements?
> 1 votes

# Answer
Keep a list of achievements per level. Iterate through the list each cycle. If an achievement is done just delete it from the list (to put it another way, check is accomplished).

Don't be affraid to "if" each option. Your gameboy would be able to iterate a 1000 member list with 60 fps (hypothetically). You won't feel an FPS drop.

There are ways to go without ifs using some simple mathematical formulas but it's 2013. We don't need hacks like that. It will make your code more obscure.
> 0 votes

# Answer
Just check at every event instead of every frame call. For example, if you have an objective of gathering 200 coins, check this one only when you get a coin. If you have a score achievement, check it only when the score changes.
Checking those things only when relevant will keep your overhead mininum.

To avoid the big if/switch structure you can make a specialized class to manage those achievements/objectives and have an exclusive function for each single achievement.
> 0 votes

---
Tags: c++, java, algorithm, mobile
---


title: Generic Class Name for RTS

text:
# Question
Title: Generic Class Name for RTS
Hopefully this will be a nice easy question :-

I am building an RTS as a way of learning OOP techniques.

Currently the code has the following classes

```
Class MustInherit GameUnit

Class MustInherit Building
  Inherits GameUnit

Class MustInherit Vehicle
  Inherits GameUnit

Class MustInherit ??????
  Inherits GameUnit

Class Jeep
  Inherits Vehicle

Class WeaponsFactory
  Inherits Building

Class Grenadier
  Inherits ??????

```

I am looking for the generic name for people to replace the ?????, ideally a word that describes people of any race or culture - humanoid or otherwise. As this is a learning exercise I would like to get it right - using the ...Is A... idea of class inheritance.

For Example: Jeep IS A Vehicle, Vehicle IS A GameUnit.

Thanks

# Answer
> -1 votes
When a Jeep is a Vehicle, then a Grenadier seems to differs from it by the fact that it moves on foot. So I would recommend to name the base-class for these units Infantry.

Infantry comes from the latin word infans which describes a child which has learned to walk on its own. It was used to describe a soldier who walks into battle instead of using a horse or charriot.

---
Tags: game-loop, rts, oop
---


# Question
Title: How do I stop overlapping shapes when collision detected in AndEngine?
I am making a very simple demo in AndEngine in which I have three rectangles: rect1, rect2 and rect3 in an ArrayList.

I register onAreaTouch as follows:

```
 @Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX,
        final float pTouchAreaLocalY) {

    switch (pSceneTouchEvent.getAction()) {

    case TouchEvent.ACTION_DOWN:
        // this.setScale(1.0f);
        this.mGrabbed = true;
        break;
    case TouchEvent.ACTION_MOVE:
        if (this.mGrabbed) {
            for (int i = 0; i < rectangles.size(); i++) {

                int index = rectangles.indexOf(this);

                if (i != index) {

                    if (this.collidesWith(rectangles.get(i))) {
                        // should not overlap
                    } else {
                        this.setPosition(pSceneTouchEvent.getX() - 90, pSceneTouchEvent.getY() - 90);
                    }
                }
            }
        }
        break;
    case TouchEvent.ACTION_UP:
        if (this.mGrabbed) {
            this.mGrabbed = false;
        }
        break;
    }
    return true;
}

```

Rectangles are now overlapping with one another. I don't want this behavior, instead I'd like it if rect1 collides with rect2 then rect1 should not move further, but can move in any other direction.

\[Cross-Posted here\]

# Answer
> 1 votes
In order to solve this you need to implement something between the touch position and the position of the object.

Instead of setting the position directly to the new touch position you'll want to first test to see if the touch position is valid. If the new position is free from overlap, then you're done and you can move the rectangle there. However, if the rectangle being there would cause overlap you need to find out how far from the shape's current position it can go before causing overlap (math's your friend here) and only move it that far. If it's already against a shape and you drag into it, it will keep trying to move in, realizing it can only move 0 in that direction and give up. This method also has the added benefit of allowing you to slide the rectangle against an object it can't pass through with no further code.

A warning however, if you are working on a drag and move around model and not just a "place in a valid location" one, only focusing on where the shape will end up will allow you to "jump" other objects by moving all the way to the other side of them. If you want to avoid this you'll need to do some form of sweep collision detection where you check to see if the shape carved out by the rectangle's movement would collide with any of the shapes, and then stop/modify it's destination based on the point of first collision.

# Answer
> 0 votes
Save the last position of the rectangles before moving them as a variable. When collision is detected, determine the reverse direction of movement of each rectangle. Then move them back in that direction the amount of the overlap. The rectangles will be touching, but not overlapping.

Very fast moving shapes will require a different method. Hopefully you dpn't need to use very fast shapes.

---
Tags: android, andengine, collision-avoidance
---


# Question
Title: How do I map a 2D grid to my game object coordinates?
I'm using Gameplay3d as a game engine to develop a simple board game, PEG Solitaire.

I've come to the part where I've created a 2D grid for all the movable object, empty locations and also where it's not movable. I'm now trying to somehow map that 2D grid to my actual game coordinates, translations of my pieces. Using Gameplay I can select my objects. What I'm trying to figure out is how to solve this actual problem to map my grid to the actual movement of the game pieces?

I was maybe thinking of using an `std::map<char*, int>` where "`char*`" is the NodeID and "`int`" is the index in the 2D grid list so that I can identify each Node and where they are in my 2D grid. The problem I'm having now is how can I solve the problem if the user select places on my board that doesn't have moveable piece. Let's say the user clicks on an empty hole on the PEG Solitaire board. How can I map that location to my 2D Grid?

I've created my board model and Sphere using Blender. I can using Gameplay use raypicking and select the differente Sphere Nodes and the whole Board Node. The problem is that I can't pick the individual holes on the Board as Nodes. I know the center position of each hole on the board. So my solution was to somehow first figure out the Spheres world size maybe translate it to the screen size. When the user then clicks on the screen I can check if the position of x and y is inside the selection area of that hole so to say. I'm probably just wondering away in my own thought. But any detailed help here would be appreciated.

Get object world size and translate to screen size of possible.

The 2D grid looks like this:

```
0022200
0022200
2222222
2221222
2222222
0022200
0022200

```

# Answer
If you're trying to convert a position in 2D to the position in 3D, then it degenerates to a maths problem. Basically, you have to produce a transformation matrix which then translates, rotates, and scales the 3D point (presume Z = 0) to a new one. If you know how you want it to be orientated and placed, then this suddenly becomes a trivial problem. Wikipedia explains it *relatively well* here, although I suggest that you Google for more information.

**Edit:**

Based on your comments, you seem to be trying to solve to separate problems. The first is converting your selection in 3D to 2D, and the second is selecting what is in that area. To convert 3D into 2D, you need to ray cast to obtain the point on the surface. Then, *as I said above*, you need to transform the points into 2D space. If you already have the other matrix, then you can calculate the inverse of it and use that.

Once you have your transformed point in 2D (note - this means discard the hypothetical Z = 0 from before), you then need to get the objects in it. My personal advice would be to iterate through all of your objects, and then check to see if their centre intersects with the polygon. I've linked the ray-casting algorithm as it relates back to the ray casting before. If the centre of the object intersects, then it's in the chosen area, and you can add it to another list (or a pointer of it, etc.)

**Edit 2:**

From the information I now have, it seems that you're trying to work out if you have a valid area to place your sphere / peg. At this point, presuming you have the transformed point in 2D (from above, if you don't already have it), you merely need to work out if the point lies in an empty position. This is a bit more maths, which goes as follows:

* Take the point `Vector2 x`, which is our point in 2D.
* Transform `x` by some other vector `Vector2 y` to get the point relative to your board ( `x + y` ).
* Now scale the expression by a scalar `float a` to get the point with unit x-values and y-values corresponding to the grid of the board ( `a(x + y)` ).
* Finally, cast the individual parts of the resultant vector to integers so that they can be used directly as array indexes.

The final code would be (in C++, sorry if it's the wrong language):

```
Vector2 getArrayIndices(Vector2 initalVector)
{
    Vector2 translationVector(x_value, y_value); // Pre-determined
    Vector2 translatedVector = initialVector + translationVector;

    int scalar = scale_value; // Also pre-determined
    Vector2 scaledVector = scalar * translatedVector;

    Vector2 integerVector((int)scaledVector.getX(), (int)scaledVector.getY());
    return integerVector;
}

```

I'll presume that from here you can check the x and y values of the vector against your array / grid (as shown in the question) to see if the value is a 1 (or whatever an empty square is represented as), and thereby check if the location is valid.
> 1 votes

---
Tags: algorithm, input, gameplay3d-engine
---


# Question
Title: 'No Platforms Found' error in Unity Android
I am having a problem with Unity Android - every time I try to "build", a 'No Platforms Found' error pops up.

Thing is that I already have Android SDK in my computer (copied it into my G drive from the official .zip download). JDK is installed too.

I use Unity 4.0.0f7 Pro version, and have SDK Platforms 2.1 (API 7), 2.2 (API 8), 2.3.3 (API 10), 3.0 (API 11), 3.1 (API 12), 3.2 (API 13), 4.0 (API 14), 4.0.3 (API 15) and 4.2.2 (API 17).

How can I remove this error and build successfully?

P.S. I have already had a look at some of the threads in Unity website regarding this matter. None of the suggested answers has worked for me.

# Answer
> 1 votes
Okay, here's how I managed to get it right - (assuming C drive to be your system drive)

1a. Install both 32 & 64-bit versions of Java in your C drive. 1b. Install Android SDK in any drive other than C. Download and use the .exe file - not the .zip file. 2. Install Unity in C drive. 3. Proceed to creating your Unity scenes and publishing them for Android.

Good luck! :-)

---
Tags: android, unity
---


# Question
Title: 2D animation example in pyglet (python) looping through 2 images/sprites every x seconds
Suppose you have two images: `step1.png` and `step2.png` .

Can anyone show me a very simple example in pyglet how to loop through those 2 images say every 0.5 seconds?

The character doesn't have to move, just a simple black screen with a fixed region wherein the two images continually change every 0.5 secs.

I know how to make a character move, shoot projectiles etc. but I just can't figure out how to control the looping speed of the images.

# Answer
> 4 votes
I use my own sprite class, which has an timer variable which accumulates the dtime in the update\_frames() message. By this you have an exact timestamp and can easily change the image based on certain timings.I do not have a source available but I will add this later, if needed

Update: Here is a small piece of code: It loads two frames and displays flip flop it after a second. This will be done in **update\_frames(dt)** (counter is a float between \[0-2\[, you can also multiply dt to have different timings )

Note that the print in **on\_draw** will print on each frame, but count changes only 10 times a second, configured in **pyglet.clock.schedule\_interval(update\_frames,1/10.0)** (play with this value, you will see the duration of the animation will not change)

```
#!usr/bin/python
import pyglet
window = pyglet.window.Window()
counter=.0

def load_anim():
    arrImages=[]
    for i in range(2):
        tmpImg=pyglet.resource.image("step"+str(i)+".png")
        arrImages.append(tmpImg)
    return arrImages

def update_frames(dt):
    global counter
    counter=(counter+dt)%2

@window.event
def on_draw():
    print counter
    pyglet.gl.glClearColor(0,0,0,0)
    window.clear()
    frames[int(counter)].blit(320,200,0,
                              frames[int(counter)].width,
                              frames[int(counter)].height)

frames = load_anim()
pyglet.clock.schedule_interval(update_frames,1/10.0)
pyglet.app.run()

```

# Answer
> 8 votes
Like this:

```
import pyglet

# Create and open a window
window = pyglet.window.Window(200, 200)

# Load sprites
s0 = pyglet.resource.image('01.jpg')
s1 = pyglet.resource.image('02.jpg')
sprites = [s0, s1]

# Animation
anim = pyglet.image.Animation.from_image_sequence(sprites, 0.5, True)
sprite = pyglet.sprite.Sprite(anim)

@window.event
def on_draw():
  window.clear()
  sprite.draw()

if __name__ == '__main__':
  pyglet.app.run()

```

But you probably want to use a texture atlas instead of that, like this:

```
import pyglet

# Create and open a window
window = pyglet.window.Window(200, 200)

# Cut our cat up into a 5x5 grid of images to move through (sprite sheet)
raw = pyglet.image.load('cat.jpg')
raw_seq = pyglet.image.ImageGrid(raw, 5, 5)
anim = pyglet.image.Animation.from_image_sequence(raw_seq, 0.5, True)
sprite2 = pyglet.sprite.Sprite(anim)

@window.event
def on_draw():
  window.clear()
  sprite2.draw()

if __name__ == '__main__':
  pyglet.app.run()

```

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


# Question
Title: Displaying (3D) objects' name above them
The Elder Scrolls: Morrowind has a rather interesting way to display each focused objects' name. It's all a bit fuzzy in my memory right now, but the most important part I remember perfectly: the object's name is always displayed in the proximity of the object (most of the time on top of it).

My question is: given a 3D mesh, how should I proceed to calculate the name's position on the screen? I'd like to always position it on top of the given mesh for now. Like in this screenshot of Morrowind:

I'm working under Unity, if it helps. The first thing that comes to my mind is to somehow use the distance between the player and each object, then take the object's actual height in consideration, and determine a line in 2D space (the screen) that just "touches" (intersects) the top of the 2D representation of the mesh (what we're actually able to view on the screen). Something like this:

But this feels a bit complicated and clunky, and might not work for characters that are not standing tall for example.

The 2nd thing that comes to my mind: would there be a way to achieve this using matrix multiplication, in the same way 2D representations of 3D objects are obtained?

Thanks!

# Answer
> 2 votes
If you are using GameObjects you could easily:

```
float SomeYOffset = 1.1f;

// Set position of GUI element
nameBar.position = new Vector3(player.position.x, player.position.y * SomeYOffset, player.position.z);

```

If you're not using GameObjects, you can take the vertex with the highest Y value and offset the nameBar mesh from there.

```
for(int i = 0; i < nameBar.verts.Length; i++)
{
    nameBar.verts[i] += new Vector3(vert.x, vert.y += SomeYOffset, player.z);
}

```

# Answer
> 2 votes
Some things to consider here are that the object might not be rotated towards the camera, and that the position in 3d world space of the object is not always linear. So, objects farther away from the camera would need the font size reduced in relation to their depth in the view.

Here is some sample code that transforms relative to the camera:

```
   objectname = GameObject.Instantiate(Resources.Load("HoverText")) as GameObject;
   GUIText name = objectname.GetComponent<GUIText>();

   name.text = "Test Name"; // Change Me

   objectname.transform.position = Camera.mainCamera.WorldToViewportPoint(transform.position) + new Vector3(0f, 0.05f, 0f); // Change the 0.05f value to some other value for desired height

```

"HoverText" should be in the Resources directory in the project. The gameobject itself should have a GUIText component added to it.

---
Tags: 3d, unity, 3d-meshes, geometry
---


title: Changing game controls using .txt file

text:
# Question
Title: Changing game controls using .txt file
I'm using XNA to create a simple block breaker game. At the moment I have controls set in the standard way:

```
if (keystate.IsKeyDown(Keys.s))

```

I've figured out the file handling problems involved and have taken in a string from a text box, for examples sake I'll have that string as "NumPad2". Now I need the game to take that string and somehow use "NumPad2" as the new control, instead of "s".

# Answer
Just use Enum.Parse, something like this:

```
var key = (Keys) Enum.Parse(typeof(Keys), keyString);

```

where keyString = "NumPad2", as you declared previously
> 7 votes

# Answer
Create an `IXmlSerializable` class that handles saving / loading of the key settings. For example:

```
public class ControlSettings : IXmlSerializable
{
   public Keys MoveUp;
   public Keys MoveDown;
   public Keys Shoot;

   public ControlSettings() {}
   //...
}

```

When you start the game, create a new instance of `ControlSettings` by deserializing an XML that defines the assigned keyboard controls (let's call this instance `myControlSettings`). Then in your game code:

```
if (keystate.IsKeyDown(myControlSettings.MoveUp))
{
   //...
}

```
> 5 votes

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


# Question
Title: multi user web game with scheduled processing?
I have an idea for a game which I am in the process of designing, but I am struggling to establish if the way I plan to implement it is possible.

The game is a text based sports management simulation. This will require players to take certain actions through a web browser which will interact with a database - adding/updating and selecting. Most of the code required to be executed at this point will be fairly straightforward.

The main processing will take place by applications which are scheduled to run on the server at certain times. These apps will process transactions added by the players and also perform some automatic processing based on the game date.

My plan was to use an SQL server database (at last count I require about 20 tables) and VB.net for all the coding (coming from a mainframe programming background this language is the simplist for me to get to grips with). I will also need a scheduling tool on the server.

Can anyone tell me if what I am planning is feasible before I dive into the actual coding stage of my project?

# Answer
> 1 votes
Non-distributed systems as you mention, rely on processing within a local environment. They are not designed to scale. Therefore, your approach is based heavily on the use of local processing, in that you aren't considering distributed approaches.

Distributed systems, rely on processing spread out both locally and remotely. In order to achieve a communication method between these systems, a messaging architecture is added in. Information and data is exchanged by this messaging system. These approaches scale well, but require a modified design approach from the start.

It's hard to tell if your planning is feasible for the long term, but definitely feasible for the short term, where scaling isnt an immediate concern.

# Answer
> 0 votes
I think that this kind of approach is reasonable in the first phase of such a project, but in the future it must give way to a more advanced approach.

Normally the web activity consists in altering the state of the system: for each request to a particular set of web pages, you get a side effect in addition to just the content you requested (html, json, images, etc).

In your case, the user is not the only source of status updating, there is also a process that runs at a certain interval: obviously you can not exhaust the matter of the state transition just through the action of the user (using a strategy like "I will compute the partial outcome of your actions now, but I will not tell you until the deadline").

The use of a (centralized) process, implies that the system should not accept operations when that process is running. How long does it take to finish? I imagine that it will need of a time proportional to the number of players, or at most quadratic.

Here is the crux of the matter: this approach does not scale, in the general case, and the process can not last more than a certain amount of time, even with millions of players. At some time you will need to understand how to distribute the upgrading process; probably by precomputing everything you can at the stage where players can operate, and/or dividing update operations in independent blocks give to a process pool.

My opinion is that you have to keep in mind this now; now that you can define the parameters of the project, but probably you can continue as you said for now, since your first goal is to make a limited number of people very happy (at the earliest)

---
Tags: game-design, web, .net, sql
---


# Question
Title: Dependency setup between libGDX projects in Eclipse IDE
For my game I'd like to create another project that extends the functionality of libGDX and since it will be an independent project it could be easily reusable. How can I achieve this in Eclipse IDE? Do I have to use any building tools like Ant or Maven? I'd prefer not using them but I also don't want that the libgdx.jar file to get in the final jar twice. Do I have to create a full libGDX project (with gdx-setup-ui) for the extension project or is it enough to create a simpe Java Project and add the libGDX library?

# Answer
I found the answer in Aurelien Ribbon's forum: http://www.aurelienribon.com/forum/viewtopic.php?f=7&t=2

> This is easy to do:
>
> 1. Create a project for your library (we'll refer to it as the "mylib" project),
> 2. Add gdx.jar and tween-engine-api.jar to its build path (put these files in its "libs" folder, which you have to create),
> 3. Add your source files to its "src" folder,
> 4. Generate the 4 test projects with the ProjectSetup tool (tick the "Universal tween Engine" library),
> 5. Add your "mylib" project to the build path of the main test project (check its checkbox to export it \[1\])
>
> Now you should be able to work on your library in the mylib project, and to directly test it in the desktop/android/html projects.
>
> \[1\] it is required for the android test project to work since the Android SDK rev17
> 1 votes

---
Tags: java, libgdx, eclipse, deployment
---


# Question
Title: Good technological solutions to build an ascii map and moving characters in a browser (like dwarf fortress)?
I'd like to build a webapp for my game website that involves using text characters to represent animals and people, and have them move around on map squares with independent (server driven) AI.

So essentially, a dwarf-fortress map in the browser: With moving creatures, mobs, npcs and pcs. Though not that I'm not looking to acheive this scale, I'd probably start of showing a quarter of this content or so at any time.

Probably some of the background/immobile tiles could be loaded statically. But for creatures/animals and things that can move, I'm not sure what technology solutions would be most effective.

I'm aware of `<canvas>` though I don't know whether its capabilities fit this use case. Certainly some amount of javascript is going to be necessary.

Are there javascript libraries or canvas libraries out there that fit this use case? Another technology that I am not aware of? Anyone know of any examples of websites that have done anything similar to this, so that I can crib ideas from them?

# Answer
I have actually made a character display library for the web, Unicodetiles.js, which I have not only spent some time optimizing, but it also explores different ways of presenting the text; it has three renderers:

1. DOM, which uses a matrix of `<div>` elements to render each glyph with a customizable foreground and background colors.
2. Canvas, which draws the characters using the `<canvas>` element. This is much faster, and there are performance tests to back that up: http://tapiov.net/unicodetiles.js/tests/
3. WebGL, which uses a canvas-element to create a font texture and then renders using WebGL, which is even faster and very scalable to big viewport sizes, but not as well supported in browsers.

Note that the linked performance tests can be pretty extreme, changing every character every frame. In practice, even the DOM renderer is fast enough for most purposes.

If you decide to make your own library, I'd still recommend using canvas because it seems to perform better, allowing bigger scenes. Using only WebGL will limit user base and it is complex to implement (Unicodetiles has an automatic fallback mechanism).

---

Another library, which I've heard suggested a lot recently is rot.js. It is specifically geared towards roguelikes as it comes with e.g. FOV system and dungeon generators. If you want a complete package, this might the way to go.
> 5 votes

# Answer
I think the most effective way would be just to fake it. Rendering to some target element using your own built in sprite font as if you're rendering a normal 2D screen. This approach makes sure no strange stuff happens when people are missing fonts, or are using a very different language (Chinese, Russian).

Fonts and texts are one of the most difficult thing to get pixel perfect in all locales on all browsers. Even when embedding a font and using some CSS magic browser and usability settings can still override and alter it. For normal websites pixel-perfect text isn't an issue but in games like Dwarf Fortress a few pixels can lead to an extremely incoherent view. Even when not using a browser but a normal application there are issues with text rendering. So even Dwarf Fortress itself uses the approach I described.

http://en.wikipedia.org/wiki/Dwarf\_Fortress

> On-screen displays use slightly modified code page 437 characters in 16 different colors implemented as bitmaps, rendered with OpenGL

*Edit: because I got some comments I extended the answer a bit*
> 6 votes

# Answer
To find out the number of lines and columns you need to output, you should check the window width and height and change it accordingly. Remember to listen to onResize events and modify the width and height accordingly.

**When you want to do this the textual way**, you could do this using text with a monospaced font and a table where each cell contains one character.

To address individual characters you could create a `<table>` with the correct number of rows and columns, where each `<td>` has an ID consisting of its x- and y- coordinates. That way you can address individual cells by ID and change their innerHTML to change the letter and change their css class to change their color.

**Using a canvas**, however, might be faster because you don't have to manipulate a large DOM tree for each character you have to replace. Dwarf Fortress is doing a similar thing, by the way. The characters which are used to represent objects are actually bitmaps, not true text output, and they are drawn using 2d graphic APIs. The HTML5 canvas is well-equipped for this. It has the context.fillText method which allows you to draw text on the canvas. This can be used to draw individual characters. You can change the size and font face by manipulating the variables context.font and the color of each letter by calling context.fillStyle.

Note that calling fillText hundreds of times per frame could be slow, because rasterizing fonts is expensive and no browser I know of uses caching. That means that when you render the same letter with the same settings a hundred times, it will be re-rasterized a hundred times. To increase the performance you could cache the rasterized appearance of each letter with each color on a hidden canvas and then draw these hidden canvases using context.drawImage. Copying from one canvas to another is usually a lot faster than font rasterization.

I am currently developing a 2d game using canvas, and noticed that the largest FPS eater was the font drawing. When I added a cache for rasterized text, it improved performance a lot.
> 3 votes

# Answer
OK this is just a stab in the dark and I don't know how that renders.

Basically you use the same trick consoles (aka terminal) did in the olden days. First you start with a monospace font. You have M lines with N characters. So you simply dump the text into a div that is wide enough (width: N em?) and put every N characters a line break; in this case a `<br/>` instead of a `\n`.

The trick is to replace the buffer, either char by char or the entire contents at once with java script.

If you want to get really specific you can use the @font-face to ensure you have the same monospace font everywhere.
> 0 votes

# Answer
Think in terms of glyphs. Decouple the display of the text from the meaning behind it. For example:

(pseudo code)

```
if (display.hitGlyph)
    glyph = Glyph.Asterisk;

display(glyph);

```

And then in your underlying code for defining the glyph atlas, simply do something as:

```
Glyph.Asterisk = "*";

```

The glyph atlas can in fact be a lookup into a ascii table with various encodings. The point here is merely to separate when to display, with what is to be displayed. I would recommend making a framework from scratch. It would give you more freedom.
> 0 votes

---
Tags: javascript, html-canvas, browser-based-games, web, webapp
---


title: Pong collision detection

text:
# Question
Title: Pong collision detection
I am making Pong... again. Anyway, the collision detection. In the past, I had gotten it working, but it used a bunch of globals, and other nasty things. This time, I am trying it where I have a Paddle, Ball, and CollisionManager class. Basically, the the paddle and ball have move functions, which moves as they would normally, including potentially invalid places.Then, the CollisionManager's sole function would check for and resolve and collisions. I hope to keep this structure.

That works fine for ball-\>top/bottom collisions, and in keeping the paddles in bounds. However, the ball-\>paddle collision, or its inverse, I am having trouble with it. This is because there are three situations that can happen, which I have badly illustrated in Paint:

The ball can hit the paddle as normal, it can hit the top or bottom of the paddles, and finally, the paddle can move into the ball. My question is, how to handle all these cases correctly. Note that this would be, more or less, how to determine when each case happens - how they are handled is not part of my question.

I had thought of a potential solution - essentially retracing, pixel by pixel, the steps of the ball, untill it no longer collides with a paddle. Then, determine the case and do things. However, this seems a bit buggy, with corner cases and such, and additionally, failed in determining when the paddle runs into the ball.

Any ideas how to do this correctly?

# Answer
If I understand correctly, your game has discrete movement steps, but you need to calculate when and where two moving objects could collide?

Just simplify the problem by finding the **relative motion of the ball to the paddle**. Then it's just a matter of figuring out which set of static edges (the paddle edges) collide with the moving ball. I assume you know how to handle corner (literally) cases?

For example, if the ball's motion vector is `[ball_i, ball_j]` and the paddle's motion vector is `[paddle_i, paddle_j]`, get the relative motion vector (with respect to the paddle) by **subtracting the paddle's motion vector from all other motion vectors**. So given this:

Subtracting the paddle's motion vector from all motion vectors, you get this:

*Note: subtracting the paddle's motion vector from itself makes the paddle stationary!*

Then it's simply a problem of whether the motion of the ball, starting from its initial position and moving in the direction of `[ball_i - paddle_i, ball_j - paddle_j]`, collides with which sides of the paddle.
> 2 votes

# Answer
Are you doing this in C++? I made a "break out" style game in java and had to solve this problem. I don't know if C++ has this (I'm sure it does) but there is a Rectangle class in the basic geometry library that has an "intersects" method. You pass a rectangle argument to it and it checks if the two rectangles intersect. Your collision check would look something like: if(paddle1.intersects(ball)) {collide();}

If you can't find a method like that, it's pretty easy to make your own. I ended up making my paddle out of four rectangles, one for each side of the paddle so I could easily determine which side of the paddle was struck, and therefore, how to deflect the ball.

If this sounds at all helpful, I can elaborate more.
> 0 votes

# Answer
first you can simplify the collision check by imagining the ball as a single point (its center) moving about
and the rectangle as a larger rounded rectangle (with the radius of the corners equal to the radius of the ball and the center points of the corners the corners of the original rectangle),

then you can use CongXu's answer and just check the intersections of a line (the path of the ball) with another (axis-aligned) line or a circle segment and depending on which segment collides you know where the collision point is and change the behavior

on the off chance that you have 2 collisions just take the one closer to the start point
> 0 votes

---
Tags: c++, collision-detection
---


# Question
Title: How do I pass textures into a fragment shader in Slick?
I've written a shader that uses three different textures, tex0, tex1, and tex2. I can load it into Slick and successfully display it, but I can't figure out how to set the three different textures. Whichever texture I last load or set is the one used for all three.

My code:

```
if (sp == null) {
    try {
        sp = ShaderProgram.loadProgram("passthrough.vert", "planet.frag");
        planet = TextureLoader.getTexture("png", new FileInputStream("earth.png"));
        clouds = TextureLoader.getTexture("png", new FileInputStream("clouds.png"));
        lights = TextureLoader.getTexture("png", new FileInputStream("lights.png"));
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

sp.bind();

// Attempt to set tex0-tex2. This fails and just sets everything to tex2.
glUniform1i(sp.getUniform1i("tex0"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, planet.getTextureID());

glUniform1i(sp.getUniform1i("tex1"), 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, clouds.getTextureID());

glUniform1i(sp.getUniform1i("tex2"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, lights.getTextureID());

sp.setUniform1f("time", tick * 0.03f);
sp.setUniform2f("resolution", 400f, 400f);

// Render a quad. This works, except that the textures are all the same.
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(0, 400);
glVertex2i(400, 400);
glVertex2i(400, 0);
glEnd();

```

# Answer
OK, it turns out that instead of

```
glUniform1i(sp.getUniform1i("tex0"), 0);

```

I should be using eg

```
sp.setUniform1i("tex0", 0);

```
> 1 votes

---
Tags: opengl, java, glsl, lwjgl, slick
---


# Question
Title: How to get pixels affected by a light in deferred shading?
I implemented deferred rendering in my little engine using framebuffers but there is no dynamic lighting for now. The g-buffer contains positions and normals in view space and albedo.

To implement real time lighting, I guess that I need to perform one pass for each light. Given the position and shape of a light, how can find all pixels affected by the light? I want to support point lights, spot lights and directional lights.

# Answer
In deferred shading, one usually just draws some geometry that bounds the light's area of effect in world space, such as a polygonal sphere or cone that encloses the point or spot light's mathematical sphere or cone.

The simplest thing to do is draw the back faces of this geometry (front face culling) with the depth test reversed (greater-than instead of less-equal). Then any pixels that are between the camera and the back faces of the light geometry will get shaded.

This also shades pixels between the camera and the front faces of the light geometry, which are outside the light and therefore don't need to be shaded. There are various optimizations that can be done to remove these pixels, such as a depth bounds test or stencil masking.

For a directional light, you do a full-screen pass.
> 1 votes

---
Tags: lighting, culling, deferred-shading
---


# Question
Title: Generated Perlin noise is not coherent (sharp edges)
I'm having a bit of trouble implementing Perlin Noise, I've included an example the problem below. I've tried debugging but everything *appears* to be working correctly, and I can't figure out what's causing the sharp edges in the output.

Below is a snippet of the code that I'm using to generate the noise (sorry about lack of comments, most should be self-explanatory though).

```
inline int ffloor(float i)
{
    return (i >= 0 ? (int)i : (int)i-1);
}

inline float dot(float x, float y, Vector grad)
{
    return (x * grad.x + y * grad.y);
}

inline float lerp(float t, float a, float b)
{
    return a + t * (b - a);
}

inline float scurve(float t)
{
    return (t*t*t*(t*(6*t -15) + 10));
}

inline Vector getVec(int x, int y)
{
    unsigned char a = permutations[x & 255];
    unsigned char b = permutations[y & 255];
    unsigned char val = permutations[(a + b) & 255];
    return gradients[val];
}

float noise2(float xPos, float yPos)
{
    float x0 = ffloor(xPos);
    float x1 = x0 + 1.0f;
    float y0 = ffloor(yPos);
    float y1 = y0 + 1.0f;

    float fracX = xPos - x0;
    float fracY = yPos - y0;

    float n00 = dot(fracX, fracY, getVec(x0, y0));
    float n01 = dot(fracX, fracY - 1.0f, getVec(x0, y1));
    float n10 = dot(fracX - 1.0f, fracY, getVec(x1, y0));
    float n11 = dot(fracX - 1.0f, fracY - 1.0f, getVec(x1, y1));

    float sx = scurve(fracX);
    float sy = scurve(fracY);

    float avgX0 = lerp(sx, n00, n11);
    float avgX1 = lerp(sx, n01, n11);

    return lerp(sy, avgX0, avgX1);
}

void init(void)
{
    int i, j, k;
    float step = 6.24f / 256;
    float val = 0.0f;

    for (i = 0; i < 255; i++)
    {
        permutations[i] = rand() & 255;

        gradients[i].x = (float)sin(val);
        gradients[i].y = (float)cos(val);
        val += step;
    }

}

```

To generate the noise map I'm calling `init` and then iteratively calling the `noise2` function with coordinates that have been scaled to the size of the map I want (so `xPos` and `yPos` are always between 0 and 1).

# Answer
> 2 votes
There's a typo in your interpolation code:

```
float avgX0 = lerp(sx, n00, n11);  // <-- should be n10, not n11
float avgX1 = lerp(sx, n01, n11);

```

---
Tags: c++, perlin-noise
---


# Question
Title: Releasing a game without really having an officially registered company
I'm thinking of releasing my iOS game *without* formally registering a company at all. I'm not sure I even want to create a company.

ITunes wants to know the copyright holder of my title. I have 2 questions regarding this:

1) Can I use my (already decided upon if will exist) company name and just register it later (if the need arises)?

2) Or should I just use my NAME as the copyright holder, regardless if I plan to formally register the company later or not?

# Answer
Do I have to say that I'm not a lawyer? I'm not a lawyer.

In some/most countries, you can use a pseudonym of your choosing called a Trade Name. You just can't use "Incorporated", "Limited" or any other legal label in the name though. This type of business is called a Sole Proprietorship, and I would highly recommend it because it's easy to create (you already have), dissolve (any time), and do any taxes for (It's just personal taxes, nothing special). At any time, you can Incorporate a business by paying a bunch of money to the government and paying someone to handle the complicated taxes, but unless you're making a lot of money or have multiple employees, I'd stick with the Sole Proprietorship.

I'm a sole proprietor in Canada and work under the legal name "John McDonald Consulting". Since I charge my customers GST, I have to have a GST number registered with the government where I pay them the GST that I collect each quarter. Your country of residence may be different, check their website.
> 13 votes

# Answer
Not a lawyer, here's my personal interpretation.

I'd think that using the name of a company that doesn't exist could be considered fraud. The copyright holder should be you for now. This covers the contingency where you don't form that company, or you don't form it soon. A copyright is property that you can transfer to your company later if you wish.
> 8 votes

# Answer
I am not a lawyer either... :)

TBH, it really depends on what the laws are. I know here in United States, the city has its own laws, the state has its own laws, and the country has its own laws for doing business. You have to abide by them all. Certain permits you need from state, certain permits from city, and certain permits from country.

My recommendation would be to do a Sole Proprietorship. It is fairly inexpensive, easy to setup, and will have you covered from the legal perspective. There are some permits you'll also have to get.

Good news is: You probably won't have to worry about many permits/other paperwork. Unless you get an office or start hiring people.

There's a reason why United States isn't so small-business friendly. The laws make is quite hard for someone to setup a business.

Also, don't forget to file earnings from your game when you file taxes. :)

**P.S**: Don't get discouraged from this whole legal thing! Trust me, it'll be all worth it once you start getting good reviews, and when the $ starts coming in. This legal stuff is just so you can be covered.
> 2 votes

---
Tags: legal, copyright
---


# Question
Title: How is game development different from other software development?
For a solid general purpose software developer, what specifically is different about game development, either fundamentally or just differences in degree?

I've done toy games like Tic-tac-toe, Tetris, and a brute-force sudoku solver (with UI) and I'm now embarking on a mid-sized project (mid-sized for being a single developer and not having done many games) and one thing I've found with this particular project is that separation of concerns is a lot harder since everything affects state, and every object can interact with every other object in a myriad of ways.

So far I've managed to keep the code reasonably clean for my satisfaction but I find that keeping clean code in non-trivial games is a lot harder than it is for my day job.

The game I'm working on is turn-based and the graphics are going to be fairly simple (web-based, mostly through DOM manipulation) so real time and 3d work aren't really applicable to me, but I'd still be interested in answers regarding those if they're interesting. Mostly interested in general game logic though.

P.S. Feel free to retag this, I'm not really sure what tags are applicable.

# Answer
> 23 votes
There is one major difference. In my opinion, it's the only difference that really matters.

We can go over the technical details of why it's different, sure. 3D engines, particle physics, lots of different things come into play.

But lots of different forms of software have strings attached. Modeling software has to do a lot of the same things. Every piece of significant software has some specialized library it has to use.

So what makes GAMES different?

Here it is: Software is designed to fill a business need. You want an inventory system? You can define what types of items you ahve to handle. You can define what you want for your production scheduling. You can do all that. Or if you want banking software, you can define what you want to do with it.

**With games, your business need is "fun". Try writing a technical specification for "fun".**

That, in my humble opinion as a developer, is what makes games different than regular software. You simply can't say "Great! This software is now feature complete as per the client's requests!" because all they want to do is have fun.

That being said, you don't need 3d graphics and extravagant physics for something to be fun. Why do people still play Tetris? Its physics consist of "move block down" "don't let block go out of bounds" and "stop block when it hits something", and while over the years there have been numerous versions, some with fancier graphics than others, but the bottom line is -- **it's fun!!**

So if you want to be a great game developer, do not throw out what you've learned as a regular software developer. It's still very useful stuff. And @Sion is right about separating your components, just like you would in a regular piece of software. But the single most important feature you can add to your game is fun. Fun fun fun fun fun. That's why game development exists, that's what you need to make your game successful. And trust me on this **however fun it is to play, it's at least 10x as fun to make!!**

Good luck with your game-dev'ing!! :D

# Answer
> 21 votes
I'm primarily a game developer and not a traditional software developer, but I think there are several key differences.

These are obviously several **generalizations** and not comprehensive:
Bigger teams. More varied backgrounds (artists, programmers, producers, with each there is even more variation). Longer development cycles. Higher standards of performance. Larger scale of projects. Bigger and more expensive risk of failure. More stressful environment.

As for object interactions and laying out your architecture, you can still properly decouple systems. Your gameplay objects and behavior, will clearly have dependencies on each other and on these systems. That is the nature of the game though (pun intended), it combines all of these systems into a single, cohesive unit, and there's nothing wrong with that. It might seem so because the scale of it all is larger than you're accustomed to.

Some easily identified and segregated systems?

* Collision Detection
* Collision Response
* Physics
* Animation
* Graphics (2D and 3D)
* Artificial Intelligence
* User Input
* File Input/Output
* Networking

# Answer
> 2 votes
I don't think game programming is any different than other application domains from the standpoint of it being harder to pick the right separation of concerns. Anytime you take your skills to a different type of application domain you are going to find that the transition isn't as smooth as you may have hoped because there's always differences. What worked in your database application has many patterns/idioms that don't work so well in your embedded app, which has many patterns/idioms that don't work so well in that real-time system which also has many patterns/idioms that don't work in game programming. However, the game programmers have the same problems when they leave their game programming domain. It's all just a matter of what you are used to.

With that said, I think game programming seems harder for many people because it requires you to work with parts of the computer that most programmers never have to deal with at their real job (low-level graphics and sounds) and more applied math than many people are comfortable with and not because of separation of concerns. While there's always difficulties determining the right choice for separation of concerns, I think the difficulty with separation of concerns you are experiencing is simply moving to a new problem domain. Once you build a few applications then it'll be like anything else, you'll learn what you like and not use what you don't.

# Answer
> 0 votes
> and one thing I've found with this particular project is that separation of concerns is a lot harder since everything affects state, and every object can interact with every other object in a myriad of ways.

I think you have an answer there, there are a lots of interactions. I made a few games with XNA (C#), now im doing a mid-size game as you say, a strategy-simulation game, been working on it for almost 2 months now, and im do it alone with no help, so i must keep my code simple. One huge difference i think, is to understand and design some classes for functionality, and other for drawing, this helps and makes your program cleaner. Of course, if you are doing a game you need to have more resources, like images (2d or 3d) and music (or sounds). So there are differences, i think its harder, but its very funny.

# Answer
> 0 votes
I think Game Programming is more fun. You can constantly test your game, you implement different physics, which results in different behavior.

From my experience, game programming is actually a lot more fun compared to software development. In software development you have certain business rules to abide by, it gets little boring. You're creating a software, its not fun. Using software is great, helpful, useful, but not fun.

Games are fun. Maybe its just me, but I find game development much more intriguing and exciting than traditional software development, regardless of the tools use.

PS: I use the latest tools for software development, HTML5, Asp.Net, C#, etc. I still find DirectX, UDK, XNA, Unity more fun to code.

---
Tags: game-design
---


# Question
Title: Rule of thumb for enemy art design in 2D platformer
I'm at the early stages of developing a 2D side scrolling open ended platformer (think Metroidvania) and am having a bit of difficulty at enemy design inspiration for something of a scifi, nature, fantasy setting that isn't overly familar or obvious. I haven't seen too many articles, blogs or books that talk about the subject at great length. Is there a fair rule of thumb when coming up with enemy art with respect to keeping your player engaged?

# Answer
You should look at your design document. It should contain background information about the world your game plays in. You do have a design doc, do you?

If not, start by thinking about the setting...

Medival european fantasy? Arabian nights fantasy? Cyberpunk megacity with a hint of magitech?

What kind of places would you find in such a world?

Who would live in such a place?

Rats and mutants in abandoned sewers?

Why are they living in the sewers? Poverty? Social Stigma? Choice?

Asking questions about the world your game is set in can guide you towards certain design decisions, or might even imply certain art choices, e.g. sewers - dim & gritty, metropolis - clean and shiny.

Where does the enemy come from might allude to what they look like. E.g. soldiers from kingdom X might wear wooden armor because they don't know smelting.

The design might also be influenced by the needs of the story, e.g. you might want easy enemies for the start of the game, so you might want to limit enemies in the first stages to grunts, while in the later stages, you can go wild with ubergrunts and elite troops with shields and katanas and rolleskates (or jetpacks, or wings) or something.

For more on creating worlds, see http://en.wikipedia.org/wiki/Worldbuilding

There are a lot of recurring 'tropes' you could use, too: http://tvtropes.org/pmwiki/pmwiki.php/Main/Trope e.g. http://tvtropes.org/pmwiki/pmwiki.php/Main/UniqueEnemy

WARNING: Browsing tvtropes.org can lead to excessive wikiwalking!

Finally, you could get inspiration from other games. I watched some speedruns of the contra series on youtube lately... lots of different enemies in small 30 minute packages.
> 2 votes

# Answer
I found this to be a good source, in an attempt to address similar challenges that I faced.

Hope this helps.
> -1 votes

---
Tags: game-design, art
---


# Question
Title: Unity3d iOS: unable to find iPhone_GlesSupport.h
i've an old unity project and i've tried it just today (with unity 4.1) and xcode 4.6. Xcode is unable to build it for the error: "iPhone\_GlesSupport.h" file not found.

Im pretty a noob under xcode and objective-c in general so i've searched in internet about this problem, but without any luck.

Anyone know more or have experienced this problem?

Thanks

# Answer
It seems that Unity 4.1 changed the trampoline project pretty significantly. There must be a plugin or something that your older project is using that is referencing that old file and needs to be updated to Unity 4.1.
> 1 votes

---
Tags: unity, xcode
---


# Question
Title: How to know the boundaries of an isometric tile?
In a 4x4 square tile, it's easy to know which pixels are inside the tile's boundaries. I know immediately that the 4th vertical pixel is supposed to be drawn but the 5th isn't.

However, on a rhombus' shaped tile, those boundaries aren't that obvious since the picture that contains it is a rectangle. This means that, within that rectangle, there will be pixels that are supposed to be seen and pixels which aren't.

If I'm drawing an isometric tile, how would you suggest I get to know which pixels are within its boundaries and which aren't?

I thought about drawing border lines so that I can draw the texture inside but since the texture should be a power-of-two size, there's no middle pixel on each axis, so it won't be just a matter of connecting 4 dots. So I decided to connect each of the 2 middle pixels in each edge, with the closest pixel on the closest edge (1st picture on top). However, if I draw inside of them, the texture won't reach the edge, which I imagine will create gaps. If this is the case, should I draw the lines one pixel beyond those two middle pixels in each side to get the outside boundaries (2nd image on top)? Are these lines a reliable indicator of which pixels should be seen?

# Answer
> 1 votes
To answer your second question first, I believe you should draw inside the lines of your second image. This will mean the tiles are all identical, and will pack tightly.

The first question, how to best determine what is inside the tile has at least two solutions.

The first is straightforward: use transparency. If you can put it in the tile itself, you are done. If you for some reason can't or don't want to, you can use one extra tile as a mask, and then just do a check, like this:

```
 foreach pixel x and y
    if(mask(x, y) == White)
      drawPixel(x, y, myTile(x, y))

```

Well of course you need modifications to handle pixels falling of the screen and choosing the correct tile and offsetting the pixels, but those are the same as for rect tile (whatever code you have, you can just dump in the mask code there).

The second solution is to use the lines you have already calculated. We can take a few shortcuts, and use the absolute value function to simplify the situation a bit.

```
foreach pixel x and y
   x1 = x - width / 2 + 0.5 //calculate relative to tile centre
   y1 = y - height / 2 + 0.5

   if (abs(x1 + 2*y1) <= width/2 + 1) && (abs(x1 - 2*y1) <= width/2 + 1)
      drawPixel(x, y, myTile(x, y))

```

As before, you will need to calculate offsets and handle screen borders.

Of these, the first is much better, since it is much easier to modify if you decide to change your tiles. (Deriving the equations are in principle easy, but I find in practice I waste a lot of time tracing rounding, off-by-one, and other errors).

---
Tags: tiles, isometric
---


title: Efficient types of 2D animation

text:
# Question
Title: Efficient types of 2D animation
I currently am doing art for a game being made (by me...) and started to think of multiple different ways of animating.

The two I am currently debating, with myself, is single layered animation and multiple layered animation.

Single: The entire character is done on one layer, with all of the required frames.

Multiple: Different body parts on their own separate layer (i.e. arm on one, leg on another, and so on)

I would like help figuring out the pros and cons of these so then I could decide, preferably from someone who has done one or the other...or both, but anyone that could offer assistance would be greatly appreciated.

# Answer
> 1 votes
Single Cons:

* restricted effects - the same animation will play over and over, and you cannot randomize any of your characters movements.

Single Pros:

* less files - this is really just a pro beacause I hate to see my res-folder flooded with .png-files. If you use multiple bitmaps, the same animation might demand 5+ different bitmaps (and if you are programming with limited memory, like a phone, save valuable memory).
* easier animation - Loop through the frames, done!

Multiple Cons:

* More files - (see Single Pros)

+ Harder animation - This might not be an issue if you're experienced with animations, but if not, positioning all the bitmaps (like arms and legs on a body) and making them move realistically might be a real pain when using multiple bitmaps.

Multiple Pros:

* More freedom with effects - I have a friend who is building his own 2d version of Dead Space right now, and he is using multiple bitmaps for arms, legs head and body, so that when he shoots his enemies, different limbs fly off, and when they die its a gory mess of limbs and blood, if this was done using a single bitmap the pool of blood and limbs would look the same every time, but using multiple bitmaps, he can randomize the death-animation which gives the game a nice depth.

The above is for sprites only, since I program for android, I don't animate backgrounds, that would kill my heap. Feel free to edit to add your own Pro/Con experiences with this.

# Answer
> 0 votes
Backgrounds: I find it easier to make these with one element per frame. It makes a very nice (and easy) effect if you want the sky to move at a different pace than the ground or something like that!

Characters: I personally like to have the whole character on one frame rather than body parts in multiple frames, I find that it is just easier for me!

Sources: I made a 2d sonic the hedgehog platformer for my Computer Science class.

---
Tags: 2d, animation
---


title: Delta Time in Videos

text:
# Question
Title: Delta Time in Videos
When playing a Video in my OpenGL Game (e.g. startup video), I want to sync it with my delta time. What is the delta time and how to use here.

Do I need to sync with the delta time (and how?) or is there another way to sync my video? I'm using my own video file reader.

# Answer
The Delta Time is simply a standarized "clock time", which should be always be 1Hz or 1tick/1second. Some clocks can be to fast or too slow so a precise Rolex watch will show the exact delta time while a cheap one will lie a bit...

The CPU's are referred to as clocks (for eg. the overclocking). Depending on their "clock rate" some can even be over 5Ghz, so they can generate 5,000,000,000 "clock beats" per second. If you do not use the delta time in your video player, your computers clock will frames of the video 5Bil x faster then it should. So it needs to be downscaled to a human-friendly time measurement unit. Would You use miles to measure the height of an ant - You can, but why would you?

Older games for Windows 95, didn't use the delta time but were scaled for the cpu's at that time. If you load a 25 year old game into a new computer wont be able to play it, as it was meant to be used on an Intel 80386 or something similar which had the clockrate of 40Mhz. So the game would play 125x faster on the new PC with 5GHz clock.

Read about the deltatime and the clock rate on Wikipedia, and before you script anything which has a time constant keep in mind that if it is meant for different CPU's you always have to use the Delta Time. :)

http://en.wikipedia.org/wiki/clock\_rate

http://en.wikipedia.org/wiki/Delta\_timing
> 1 votes

---
Tags: c++, opengl, video
---


title: FFMPEG Opengl video rendering

text:
# Question
Title: FFMPEG Opengl video rendering
I'm searching any way to render with ffmpeg, an opengl texture that contains the video frame.

Actually, I am not good with ffmpeg... Is there any library/documentation or something? How can I render a video with ffmpeg to opengl?

Thanks

# Answer
> 2 votes
Example implementation with basic demos: http://code.google.com/p/openmedialibrary (opengl/openal frontend to an ffmpeg backend)

---
Tags: c++, opengl, video
---


# Question
Title: What's the best way to draw lots of trees
I'm writing an app which renders a random island planted with trees. The trees are currently two quads, criss-crossed and drawn with textures. I plan to have more complex meshes that form different plant types, e.g. a palm tree, oak, grasses etc..

The problem I face is that because the textures are transparent I must draw them from back to front. Plan-b is to call of using discard in the frag shader, but z-order gives better results:

```
uniform float uTreeAlpha;
uniform sampler2D uTexture;

varying vec2 vTexCoordOut;

void main (void)
{
  vec4 colour = texture2D(uTexture, vTexCoordOut);
  if (colour.a < 0.1) {
    discard;
  }
  gl_FragColor = vec4(colour.rgb, colour.a * uTreeAlpha);
}

```

The second problem is because the order changes depending on camera & lookat I do not know an efficient way to draw them in OpenGL in a single call.

At present my rendering code looks like this pseudocode:

```
if cameraChangedFromLastTime() then
  sortTreesBackToFront();
end
for i = 0 to trees.size() -1
  drawTree()
end

```

Where every drawTree() sets some uniforms, sets the texture, and then calls glDrawArrays(). I have some optimisations to skip setting a texture or updating texture coords if the last tree and the current are the same, and setting some common uniforms outside the loop, and of skipping trees which are too far away but basically if I have 3000 trees I go 3000 times around the loop.

Drawing each tree individually is the performance killer. If I could draw them in a single call, or batches (while preserving Z-order) I'd probably so in 1/10th the time.

So how would I do that. Bear in mind that my trees are placeholders and eventually I would have:

* Different meshes for different trees
* Different scales and angles for trees to give some more variety
* Different textures for different trees, potentially multiple textures applied to a mesh (e.g. leaves one texture, trunk another)
* Trees are all mixed together so no simple way to draw one kind and then another
* Some form of simple cyclical animation (branches bobbing in the wind)
* All textures would reside in a single atlas

So what's best approach here? Is it feasible to render in a single pass? If I used glDrawElements, rebuilding the indices but not the vertices, could I achieve this?

# Answer
What you want is hardware instancing. Note: I've done this in XNA (i.e. DirectX), but I don't know much about OpenGL. I'm positive there is a comparable feature, though. Basically what it amounts to is binding together the vertexes of your tree model with another vertex stream that carries world coordinates for each instance.
> 3 votes

# Answer
The transparency only needs to be ordered if it uses non-additive blending. For a ton of distant billboards, the blending is unnecessary (you can't really see it). Render at least the further ones with cutout transparency (alpha of only 1 or 0) and you don't need to sort them.

You can use a sprite sheet of sorts to render different types of trees, with baked animations. Draw meshes for closer trees which you can animate with more fidelity based on winds or whatever you want.
> 2 votes

---
Tags: java, android, opengl-es2
---


# Question
Title: Hex tile systems and the efficient use of classes
So I've built myself a system of classes for what I think is an efficient way to describe an entity that would live in my game.

Is this an effective approach or am I creating entities that are too large in size? I want the game to be able to run well even with an inane amount of tiles.

I read the post (Map with 20 million tiles makes game run out of memory, how do I avoid it?) about having one million tiles and memory problems and I'm worried that my tile system I've created using the entity system will not be able to handle such large sized maps as there is so much information to be processed.

To give you an idea about what each component of a Hex Entity holds, the sprite comp maintains the following variables: the texture, position, rotation, height and width; while the hex comp of the hex entity maintains: the position, the coordinates on the board, the orientation, and what hex's are adjacent to it. Should i simplify the date types

# Answer
It is hard to say what exactly will suit your situation. Your setup is very memory inefficient, if you want millions of hexes as much data as possible should be implicit, that means you should store hexes in an array where each array entry maps to a specific position.

But do you need millions of hexes? If you have only got a few thousand hexes your current system may be fine.
> 3 votes

# Answer
Here's an example of a large number of block entities per frame:

http://www.youtube.com/watch?v=YMRTOozLufI (spool to position 1:07)

The way I had 100,000+ blocks per frame, single threaded was to limit the data that defined those blocks, ie:

```
public struct Block
{
    public BlockType Type;
    public byte Sun;
    public byte R, G, B;

    public Block(BlockType blockType)
    {
        Type=blockType;
        Sun = 0;
        R = 0; G = 0; B = 0;
    }
}

```

The block then, is quite compact, but not defined for extremely low memory here. To do that, I needed to look even further, for example:

```
public struct LowMemBlock
{
        private byte store ;

        public BlockType Type
        {
            get { return (BlockType)(store >> (byte)4); }
            set {store = (byte)(((byte)value << (byte)4) | (store & 0x0F)); }
        }

        ...
}

```

This isnt the full lowmemblock, but just a snippet. It highlights the point of efficiently using the high and low nibbles, to further reduce the size of the block in memory.

One other interesting point to consider, is Garbage Collection. If you are able to sacrifice a potential stutter at specific frames, make use of the gc in .NET to clear up deallocated memory.

Two more techniques that I found to work well are:

**1. Sparse matrices:** http://www.blackbeltcoder.com/Articles/algorithms/creating-a-sparse-matrix-in-net

Quote:

> A sparse matrix is a data structure that works like a two-dimensional array but uses far less memory. It is ideally suited for situations where you need to represent a grid, but most cells in the grid will be empty.
>
> For example, consider a spreadsheet with 1,000,000 rows and 1,000,000 columns. To represent the data for such a spreadsheet using a two-dimensional array, the array would need to store 1,000,000,000,000 elements! When you consider that most spreadsheets use only a tiny fraction of the available cells, this represents a huge waste of memory. A two-dimensional array uses memory for all cells, whether they are used or not.

The sparse matrix is ideal: It allows you to specify a position, and store the data at that position. The positions in the sparse matrix that have no data, are not initially allocated. So, in reality, the matrix is a defined array, but only that doesnt use memory for any cell that has no data. It is much more memory efficient that a usual array. But, I found that it can be slow to traverse when dynamically reallocating, as I was doing with procedural voxel terrain. It might work perfect for you in your game though.

**2. Weak references:** http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

Quote:

> Usually, when an object goes out of scope, or is set to null, it is no longer accessible to us, even if the garbage collector will only delete the object much later. A weak reference object will keep a reference to an object that went out of scope or was set to null, until it is actually deleted by the garbage collector. But until that happens, we can get the object back!

So, we are able to make reuse of the memory allocated on that object, and still allow the gc later on to delete it. In a way, we are informing the gc that it is safe to clean up the memory footprint of that object.

And for clarity, a link to explain them a bit better, with a code example: http://tipsandtricks.runicsoft.com/CSharp/WeakReferences.html
> 1 votes

---
Tags: xna, c#, entity-system
---


title: Making up everything from single pixels

text:
# Question
Title: Making up everything from single pixels
I recently saw a game which looked a bit like minecraft, but it was a RPG. The enemies in this game consist completely of voxels and if they die, they collaps and every single voxels falls down, splattering on the floor.

That looked great and I think it could also look good in a 2D Shooter. But I cannot think about an approach to handle such an amount of pixels. What I want to achieve is: The enemies (and also the player) should consist of pixels, but not in a way that let them look like a pixel mess. They should have certain shapes etc. But everything should be loose. So for example, if there is an endboss with some tentacles or big weapons, it should be possible to destroy these bit by bit. And everytime a bit is destroyed, the single, now loose pixels fly away in all directions.

How is this usually done for voxels? Will this even be possible with pixels (I cannot see why not)? How could be an approach to implement such an idea?

# Answer
In one of my voxel engines, the voxel block explosion was done by creating a defined amount of minature blocks at the explosion point, and applying physical properties to them, eg velocity and gravity. Then, set them at random directions, and draw them. So, the actual voxel model wasnt really being disintegrated, but the voxel particles gave that impression.

That is one approach.

Another approach is to actually break up the voxel model. To achieve that under testing, was to detach the smaller voxels from the model, and apply the same techique for the previously mentioned explosion. No new voxels were created.

In relation to pixels, I would imagine it possible, yes.

An approach might be to look at using a rendertarget for the sprite, and where the texture pixel coords match the explosion points, store those coloured pixels in a dictionary, with position and colour values. Then, the rendertarget would form the source of the sprite without those pixels present. Use finally some type of custom particle manager to explode the pixels from the dictionary, using a technique similar to the explosion of the voxel model that I mention in the second part of this response.

Edit:

As requested in the comment, here is an example of using a rendertarget to regenerate a sprite:

```
    GraphicsDevice _graphicsDevice;
    RenderTarget2D _renderTarget;
    SpriteBatch _spriteBatch;
    Texture2D texture;
    Texture2D _spriteTexture ;
    Rectangle sourceRectangle;

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        _spriteBatch = new SpriteBatch(GraphicsDevice);
        _spriteTexture = this.Content.Load<Texture2D>("SomeTexture");
    }

```

And then, in a new method, something similar to:

```
        _graphicsDevice.Clear(Color.White);
        _renderTarget = new RenderTarget2D(_graphicsDevice, 16, 16, false, _graphicsDevice.DisplayMode.Format, DepthFormat.Depth24);

        _graphicsDevice.SetRenderTarget(_renderTarget);
        _spriteBatch.Begin();
        sourceRectangle = new Rectangle(0, 0, 16, 16);
        _spriteBatch.Draw(_spriteTexture, new Vector2(0, 0), sourceRectangle,
                            Color.White, 0, new Vector2(0, 0), 1f, SpriteEffects.None, 1);
        _spriteBatch.End();
        _graphicsDevice.SetRenderTarget(null);

        texture = _renderTarget;

```

texture becomes the output sprite, as a Texture2D. The code isnt really doing a change here to the spriteTexture. But it illustrates how the spriteTexture is rendered to a new RenderTarget. The actual change would happen just prior to the spriteBatch.Draw method call, where some effect, or modification to the spriteTexture would be done, eg, removing some pixels because of the explosion.
> 3 votes

---
Tags: 2d, architecture, pixel
---


# Question
Title: How do I get smooth edges with OpenGL on Android?
Here is a screenshot that maybe makes clear what my problem is.

I'm only drawing 2D circles with OpenGL.

I already read the following:

and added the blending function. But nothing worked or even made a difference.

This is my renderer:

```
public class GLRendererTamago implements Renderer{

private GLTamago tama;

public GLRendererTamago(){

    tama = new GLTamago();
}

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    gl.glDisable(GL10.GL_DITHER);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
    gl.glClearColor(.8f, 0f, .2f, 1f);
    gl.glClearDepthf(1f);
}

@Override
public void onDrawFrame(GL10 gl) {
    gl.glDisable(GL10.GL_DITHER);
    gl.glDisable(GL10.GL_DEPTH_TEST);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);

    tama.draw(gl);
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    // TODO Automatisch generierter Methodenstub
    gl.glViewport(0, 0, width, height);
    float ratio = (float)width / height;
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glFrustumf(-ratio, ratio, -1, 1, 1, 20);

}

```

and this my object:

```
public class GLTamago{

private int points = 1000;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

public GLTamago(){

    vertices = new float[points * 2];
    for(int i=0; i< points; i+=3)
    {
      double rad = 2*(Math.PI *i) / points;

      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float)Math.sin(rad);
      vertices[i+2]=0;
    }

    ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff=bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);
}

public void draw(GL10 gl){
    body(gl);
    lefteye(gl);
    righteye(gl);
    mouth(gl);
 }

private void body (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(0, 0, 0);
    gl.glScalef(2.0f, 3.0f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
}

private void lefteye (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(1, 1, 0);
    gl.glScalef(0.5f, 0.5f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(1, 1, 0);
    gl.glScalef(0.1f, 0.1f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
}

private void righteye (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(-1, 1, 0);
    gl.glScalef(0.5f, 0.5f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(-1, 1, 0);
    gl.glScalef(0.1f, 0.1f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

}

private void mouth (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(0.0f, -1.0f, 0.0f);
    gl.glScalef(1.8f, 0.5f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
}
}

```

At the edges you can see pixels... and I have no idea how I can fix this.

I often heard to try anti-aliasing and/or shaders... but I don't have any idea how that works etc.

# Answer
I solved the problem with the EGLConfigChooser.

I have no idea what that is doing... but it works very fine.

I just copyed the code from here:

http://code.google.com/p/gdc2011-android-opengl/source/browse/trunk/src/com/example/gdc11/MultisampleConfigChooser.java

in a new class and made as it told me:

> To use this, call myGLSurfaceView.setEGLConfigChooser(new MultisampleConfigChooser()); before calling setRenderer().
> 7 votes

---
Tags: android, opengl-es
---


# Question
Title: 2D Collision in Canvas - Balls Overlapping When Velocity is High
I am doing a simple experiment in canvas using Javascript in which some balls will be thrown on the screen with some initial velocity and then they will bounce on colliding with each other or with the walls.

I managed to do the collision with walls perfectly but now the problem is with the collision with other balls. I am using the following code for it:

```
//Check collision between two bodies
function collides(b1, b2) {
    //Find the distance between their mid-points
    var dx = b1.x - b2.x,
        dy = b1.y - b2.y,
        dist = Math.round(Math.sqrt(dx*dx + dy*dy));

    //Check if it is a collision
    if(dist <= (b1.r + b2.r)) {
        //Calculate the angles
        var angle = Math.atan2(dy, dx),
            sin = Math.sin(angle),
            cos = Math.cos(angle);

        //Calculate the old velocity components
        var v1x = b1.vx * cos,
            v2x = b2.vx * cos,
            v1y = b1.vy * sin,
            v2y = b2.vy * sin;

        //Calculate the new velocity components
        var vel1x = ((b1.m - b2.m) / (b1.m + b2.m)) * v1x + (2 * b2.m / (b1.m + b2.m)) * v2x,
            vel2x = (2 * b1.m / (b1.m + b2.m)) * v1x + ((b2.m - b1.m) / (b2.m + b1.m)) * v2x,
            vel1y = v1y,
            vel2y = v2y;

        //Set the new velocities
        b1.vx = vel1x;
        b2.vx = vel2x;
        b1.vy = vel1y;
        b2.vy = vel2y;
    }
}

```

You can see the experiment here. The problem is, some balls overlap each other and stick together while some of them rebound perfectly. I don't know what is causing this issue. Here's my balls object if that matters:

```
function Ball() {
    //Random Positions
    this.x = 50 + Math.random() * W;
    this.y = 50 + Math.random() * H;

    //Random radii
    this.r = 15 + Math.random() * 30;
    this.m = this.r;

    //Random velocity components
    this.vx = 1 + Math.random() * 4;
    this.vy = 1 + Math.random() * 4;

    //Random shade of grey color
    this.c = Math.round(Math.random() * 200);

    this.draw = function() {
        ctx.beginPath();
        ctx.fillStyle = "rgb(" + this.c + ", " + this.c + ", " + this.c + ")";
        ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
        ctx.fill();
        ctx.closePath();
    }
}

```

# Answer
> 5 votes
I was working on something similar, in which balls will be colliding and rebounding at different angles and velocities. I found the solution in a book for ActionScript animation. Explaining it will take a lot of time and effort and honestly I cant really explain this since I've myself forgotten how most of this works. Please try your best to understand what this code is doing and if you need further assistance, ask me and I'll try my best to explain.

```
function rotate(x, y, sin, cos, reverse) {
    return {
        x: (reverse) ? (x * cos + y * sin) : (x * cos - y * sin),
        y: (reverse) ? (y * cos - x * sin) : (y * cos + x * sin)
    };
}

function checkCollision (ball0, ball1) {
  var dx = ball1.x – ball0.x,
      dy = ball1.y – ball0.y,
      dist = Math.sqrt(dx * dx + dy * dy);

  //collision handling code here
  if (dist < ball0.radius + ball1.radius) {
    //calculate angle, sine, and cosine
    var angle = Math.atan2(dy, dx),
        sin = Math.sin(angle),
        cos = Math.cos(angle),

        //rotate ball0's position
        pos0 = {x: 0, y: 0}, //point

        //rotate ball1's position
        pos1 = rotate(dx, dy, sin, cos, true),

        //rotate ball0's velocity
        vel0 = rotate(ball0.vx, ball0.vy, sin, cos, true),

        //rotate ball1's velocity
        vel1 = rotate(ball1.vx, ball1.vy, sin, cos, true),

        //collision reaction
        vxTotal = vel0.x – vel1.x;
    vel0.x = ((ball0.mass - ball1.mass) * vel0.x + 2 * ball1.mass * vel1.x) /
             (ball0.mass + ball1.mass);
    vel1.x = vxTotal + vel0.x;

    //update position
    pos0.x += vel0.x;
    pos1.x += vel1.x;

    //rotate positions back
    var pos0F = rotate(pos0.x, pos0.y, sin, cos, false),
        pos1F = rotate(pos1.x, pos1.y, sin, cos, false);

    //adjust positions to actual screen positions
    ball1.x = ball0.x + pos1F.x;
    ball1.y = ball0.y + pos1F.y;
    ball0.x = ball0.x + pos0F.x;
    ball0.y = ball0.y + pos0F.y;

    //rotate velocities back
    var vel0F = rotate(vel0.x, vel0.y, sin, cos, false),
        vel1F = rotate(vel1.x, vel1.y, sin, cos, false);
    ball0.vx = vel0F.x;
    ball0.vy = vel0F.y;
    ball1.vx = vel1F.x;
    ball1.vy = vel1F.y;
  }
}

```

# Answer
> 1 votes
I believe your answer is due to the fact your circles are still in contact with each other and that the last line of the first function you post continues to update their positions to positions that are within the boundaries of each other. This will cause the collision routine to continue to keep them stuck where they are. At slower speeds the first function updates their velocity and position away from each other allowing them to move away as their positions no longer overlap.

# Answer
> 0 votes
A simple solution that I have implemented before is when you detect a collision between objects do some simple math to pull the apart from one another before doing the collision calculation. So if two spheres collide, separate them by the sum of their radii and by the angle they collided then do your calculation.

# Answer
> 0 votes
To resolve the colision i made a Vector class with some methods like: 'add()', 'sub()', 'scale()', 'get\_angle()', 'get\_length()', 'set\_angle()', 'set\_length()' and 'norm\_reflect()'.

The last one might be a little tricky so i'll show you how i did it:

```
def norm_reflect(self, vec1):

    if vec1.get_angle() >= 0:    # if angle of vector is positive then add 90 to it

        return self.set_angle(vec1.get_angle() - self.get_angle() + 90)

    else:                        # else, the angle is negative so you subtract 90 from it

        return self.set_angle(vec1.get_angle() - self.get_angle() - 90)

```

To do the collision now its just simple:

1- See if they collide

2- If they do calculate how much you need to move them so they don't collide

```
dist.set_length(- dist.get_length() + total_radius).scale(0.5)

```

3- Then move one circle one way and the other the other way

4- Then make the velocities like this:

```
b1.speed = b2.speed.add(b1.speed.norm_reflect(dist.set_angle(dist.get_angle() + 90)))
b2.speed = b1.speed.add(b2.speed.norm_reflect(dist.set_angle(dist.get_angle() + 90)))

```

PS: You can add things like elasticity to make it more realistic, i didn't put them here because it would get to messy.

---
Tags: collision-detection, physics, algorithm, javascript, html-canvas
---


# Question
Title: Approach on how to split game assets into split archives
With a custom binary file format for archives that is structured similiar to Valve's VPK files I have a `Game.index.gcf` which holds information about all files and where exactly they are stored. I can split up and say, that the `/Assets/Maps` and `/Assets/Scripts` folders should be stored in `Game.000.gcf` while the bigger `/Assets/Music` folder could be split up into `Game.001.gcf` and `Game.002.gcf`. This should boost performance but only if done right. Moreover with updates I could say, just update this particular split archive and not the entire archive (when storing everything in one really huge a file).

As of yet, I don't know how to write such an adaptive algorithm which automatically decides the best way to split all archives and files. What aspects should I keep in mind and what should I be aware of when creating these? Do you have any suggestions?

# Answer
> 0 votes
I wouldn't expect a performance difference between reading a 4KB chunk from a small file or from a big file, assuming both are properly implemented.

For your 1GB "huge" file, you could hold an in-memory index containing available filepaths stored in the VFS (or hashes of them, to store space). Each index entry would just contain the offset in the file - a read is a easy seek, just read the part of the file that you need. If you have compression applied, make sure each file is compressed separately or in series of smaller files, so that you can decompress your chosen file with little effort.

From the operating system point of view, it doesn't really make any difference if the files are 5 or 500 MB. Small files, that is below 10KB or so, actually have a negative impact (because finding the file and opening it also takes time).

I don't see any immediate advantage of using small archives instead of one big one, performance wise. In fact, many AAA games use this method of huge monolithic files.

The "easy patching" argument still applies, but then I guess you don't need any fancy "packer" algorithm.

---
Tags: c++, assets, asset-management, filesystem
---


title: Cost of changing scene in andengine

text:
# Question
Title: Cost of changing scene in andengine
I'm working on a simple 2d puzzle with small textures (in count and quantity). Now after I finished the game logic I'm considering tow options to switch between levels:

* Remove all objects manually and de-attach their spirits from the current scene .
* Drop the whole scene and start the new level on a new scene.

Both options are not much different in code complexity in my case. so the question is what are the drawbacks of the second approach ? specifically is a scene a heavy object?

# Answer
The AndEngine documentation states that a **Scene** is nothing more than a mere container for a specific game state. Logically, if it makes sense for each "level" to be a state - (they are distinicntly different and require some complicated setup or it's just easier), just drop the scene. A scene is a self-contained state - just make sure to be careful that there is no shared state that may require clean up. (Globals are tricky for this... if you keep any global object references that are pertaining to that level, make sure you clean them up.)
> 3 votes

---
Tags: java, android, andengine, puzzle, scene
---