title: Coding Dynamic Events?

text:
# Question
Title: Coding Dynamic Events?
I have no idea what the title of this question should be so bare with me.

My game has turns. On a turn a player does something and this can result in a random number of explosions that occur at different times. I know when the explosions are done. I need to know when **ALL** are done and then do some other action. Also, each explosion is the same amount of time, say 3 seconds..

Right now I'm thinking of using a counter to hold how many explosions are happening. Then once the explosion is finished decrement this counter. Once the counter is zero, do my action. This idea is inspired by objective-c memory management btw. Anyways, does this sound like a good approach or would there be another way.

An alternative might be to figure out the explosion who happened last and let it be responsible for calling this subsequent action.

I'm asking mostly, because I haven't done this before and am trying to figure out if there are bugs that may occur that I'm not foreseeing.

# Answer
You know when each individual explosion is done. You know how many explosions there will be. Just make whatever is in control of your explosions (random event handler?) trigger an event saying the explosions are finished. If you don't have a separate object controlling your explosions, make one.

A global event handler will likely be very useful to you. Any object should be able to push events to the handler. And any object should be able to be extended to handle events.

See these questions for more details:

Best way to manage in-game events?

What role does developing with events have in games?

What should I be considering when designing an Event Manager System?
> 4 votes

# Answer
For situations like this, I prefer what I call the "action lists" approach. It's a generalization of a technique that's been around in various forms for a very long time.

The basic implementation is that you have a queue of Action objects. An Action is something that takes time to complete. Each Action has an Update() method that can be called every iteration of the game state update loop, to perform any portion of the remaining work, and which can mark itself as being finished when the work is complete.

You can then keep this queue of Action objects, and call the Update() method for the Action in the front of the queue each frame. If the Action is marked as finished after it is run, it is removed the queue.

In your case, your ExplosionAction might start the explosion animation the first time its Update() is called. Each subsequence call to Update() would check if the animation is complete (and/or some other timer is complete), and if so, mark itself as finished.

You can then either wait for the action list to be emptied or you can create a SignalEventAction that is pushed onto the back of the queue after all the ExplosionAction objects. The SignalEventAction Update() method would call some callback function (or raise an event, if you have a more complete event system, as Byte56 suggested) and mark itself as finished. The end result will be that the explosions all fire, then the callback gets invoked to signal the game logic that all explosions are done. Nice and simple, and requires no explicit state tracking explosion counters or any special logic for the last explosion; this in turn makes the system a fair bit more robust, in my experience.

It can be helpful to put a small bit of state into the base Action implementation, such as flags whether the Action has already had its Update() method called once or not. You can then let derived implementations override specific callback methods like OnStart(), OnUpdate(), OnFinished(), etc.

There's quite a bit more you can do with an action list with very little extra implementation work. For your needs listed above, you should be fine with the most basic implementation.

If you're interested in more on the technique and how it can be applied to more complicated scheduling scenarios, see the following link to some PDF slides of an informal talk I did over the summer on it (the video is online too if you care to search for it, but it doesn't add anything over the slides): Action! Lists Slides (PDF)
> 0 votes

---
Tags: events
---


# Question
Title: Convert rotation from Right handed System to left handed
I have Euler angles from a right handed system that I am trying to convert to a left handed system. All the information that I have read online says that to convert it simply multiply the axis and the angle in the correct order and it should work. In other words, Z * Y * X. When I do this what I see in Maya, and in engine still do not match up.

This is what I have so far:

```
static Quaternion ConvertToRightHand(Vector3 Euler)
{
    Quaternion x = Quaternion.AngleAxis(-Euler.x, Vector3.right);
    Quaternion y = Quaternion.AngleAxis(Euler.y, Vector3.up);
    Quaternion z = Quaternion.AngleAxis(Euler.z, Vector3.forward);
    return (z * y * x);
}

```

Keeping the -Euler.x helps keep the object pointing up correctly, but when I pass ( 0,0,0) to face in the -z, it faces in the +z. Help :/

# Answer
I didn't have enough rep points to post the answer. But I figured out that doing a simple rotation about the Y was going opposite than what was in Maya. So I figured that adding 180 in the other direction should, and it did:

```
static Quaternion ConvertToRightHand(Vector3 Euler)
{
    Quaternion x = Quaternion.AngleAxis(-Euler.x, Vector3.right);
    Quaternion y = Quaternion.AngleAxis(-Euler.y + 180, Vector3.up);
    Quaternion z = Quaternion.AngleAxis(Euler.z, Vector3.forward);
    return (z * y * x);
}

```
> 3 votes

---
Tags: rotation, coordinates, quaternion, maya
---


# Question
Title: How to collide with a 45degree wall in XNA
I want to make a PAC MAN imitation game to start working on AI, and while my first version will feature rectangles with widths or heights of 1 to makes walls for collision detection, I want to eventually make walls that are at 45 degree angles. I have found no guides out there to do this, only that rectangles can't be rotated apparently.

# Answer
> 1 votes
what your are asking for is analytic geometry. I think there are mainly two scenarios, assuming your wall is only a line:

1. Your Player's bounding volume is a circle: Calculate distance from center of the circle to line, and check whether it is smaller then the radius. Check out this: Distance from point to line in 2D on Wolfram.
2. Your Player's bounding volume is a rectangle: Your have to calculate each intersection of the rectangles four lines and check whether one of the intersection lies in between start and end point of one line. Check out this: Line-line intersection on Wikipedia

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


title: Rotating a sprite to touch

text:
# Question
Title: Rotating a sprite to touch
I know this has been asked before and Ive looked through peoples questions and answers all over the internet and I just cant get it to work. Im sure its down to my inexperience. Ive got an arrow attached to a sprite, this sprite appears when touched but I want the arrow to point where the sprite will launch. I have had the arrow moving but it was very erratic and not pointing as it should. Its not moving at the moment but this is what I have.

```
- (void)update:(ccTime)delta
{
    arrow.rotation = dialRotation;
}

-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent *)event
{
    pt1 = [self convertTouchToNodeSpace:touch];

    CGPoint firstVector = ccpSub(pt, arrow.position);
    CGFloat firstRotateAngle = -ccpToAngle(firstVector);
    CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

    CGPoint vector = ccpSub(pt1, arrow.position);
    CGFloat rotateAngle = -ccpToAngle(vector);
    CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

    dialRotation += currentTouch - previousTouch;
    }

```

I have got pt from ccTouchBegan the same way as pt1

Thanks

# Answer
Ok I figured it with another method.

```
-(void) calcAngleAndRotateObjectStartingAtPoint:(CGPoint)start endingAtPoint:(CGPoint) end
{
    CGPoint diff = ccpSub(end, start);
    float rads = atan2f( diff.y, diff.x);
    float degs = -CC_RADIANS_TO_DEGREES(rads);
    degs += 90.0f; // 0 is pointing right, so offset so our angle is pointing out of the top of the sprite
    [aim setRotation:degs];
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self ccTouchesMoved:touches withEvent:event];
}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if( touch ) {
        CGPoint touchPoint = [touch locationInView: [touch view]];
        touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
        [self calcAngleAndRotateObjectStartingAtPoint:aim.position endingAtPoint:touchPoint];
    }
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{}
@end

```

Thanks for all your answers but this did it for me.
> 0 votes

# Answer
try updating arrow.rotation from ccTouchMoved and not in the update.

```
-(void)update:(ccTime)delta
{
    (empty)
}

-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent *)event
{
    ...

    dialRotation += currentTouch - previousTouch;
    arrow.rotation = dialRotation;
}

```
> 0 votes

---
Tags: cocos2d-iphone
---


# Question
Title: How to get a point to the left/right of a vector
I have a position vector of a point in space and a quaternion for it's rotation. What i'm trying to calculate is a point too the left and a point to the right.

I have the position and rotation(quaternion) of the red dot. What I want is to get the position of the green dots. I have a float value for the distance I want these points to be.

With only the position and rotation is it possible to get a unit direction vector pointing left/right which I can multiply by my float value?

Edit: I also know the original direction vector.

# Answer
Given only a point and a direction there is no defined 'right' or 'left'.

Imagine being a falling raindrop, which direction is right or left for you in that case?

In order to calculate (or even define) a right or left you need two directions, typically forward and up.

You seem to already have a forward direction, so you need to define a up direction.

```
right_dir=forward X up  (cross product)
left_dir=-right

```

As you want unit vectors in these direction, you should of course normalize right & left.
> 12 votes

---
Tags: mathematics, unity, rotation, vector, quaternion
---


# Question
Title: Unity Particle System collision detection problem
I'm using Unity 3.5.5f3 wich has the Shuriken particle system.

I've made a blood particle system based on Unity's demos. (Exploding paint \[Blood\]) The blood is flowing and when it collides with a Plane Transform wich I've created a small pool of blood spawns as a Collision Sub Emitter.

My main problem is that when I want to add another object to collide it just doesn't want to work. When I create a cube, and set it as a collision plane the collision will only occur at the half of the cube.

I want this to happen: When it reaches the cube's surface the sub emmiter activates, and when the surface is horizontal it appears horizontally, and if it's vertical then vertically. Now it just appears horizontally everytime like in the picture.

How could I solve it?

# Answer
After further research I've come to the conclusion that I can't do it with Particle System collision, because it can only collide with planes. To create an effect like I've described, a solution for it is Texture Decals.
> 0 votes

---
Tags: collision-detection, unity, particles
---


title: cocos2d/OpenGL multitexturing problem

text:
# Question
Title: cocos2d/OpenGL multitexturing problem
I've got a simple shader to test multitextureing the problem is both samplers are using same image as their reference.

the shader code is basically just this :

```
vec4 mid = texture2D(u_texture,v_texCoord);
float g = texture2D(u_guide,v_guideCoord);
gl_FragColor = vec4(g , mid.g,0,1);

```

and this is how I'm calling draw function :

```
int last_State;
glGetIntegerv(GL_ACTIVE_TEXTURE, &last_State);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, getTexture()->getName());
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mGuideTexture->getName());

ccGLEnableVertexAttribs( kCCVertexAttribFlag_TexCoords |kCCVertexAttribFlag_Position);

glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, texCoord);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glDisable(GL_TEXTURE_2D);

```

I've already check `mGuideTexture->getName()` and `getTexture()->getName()` are returning correct textures. but looking at the result I can tell, both samplers are reading from `getTexture()->getName()`.

here are some screen shots showing what is happening :

1. The image rendered Using above codes
2. The image rendered when I change textures passed to samples

I'm expecting to see green objects from the first picture with red objects hanging from the top.

after testing lots of things I've figured out glUniform1i is not working as expected, Though I'm not sure what is wrong with it. Here is the code:

```
glUniform1i(textureLocation, GL_TEXTURE0);
glUniform1i(guideLocation, GL_TEXTURE1);

```

# Answer
> 3 votes
This is what you're doing wrong:

```
glUniform1i(textureLocation, GL_TEXTURE0);
glUniform1i(guideLocation, GL_TEXTURE1);

```

Instead of GL\_TEXTURE0 and GL\_TEXTURE1 you need to give them 0 and 1, like so:

```
glUniform1i(textureLocation, 0);
glUniform1i(guideLocation, 1);

```

Also, when using shaders you don't need glEnable (GL\_TEXTURE\_2D), or the corresponding glDisable (GL\_TEXTURE\_2D) - unrelated to your problem but let's get that right too.

---
Tags: opengl-es, cocos2d, opengl-es2
---


# Question
Title: Maya and Game Engines (i.e. Environment Testing)
What does it mean if I'm designing an environment and I want to test it in the game engine, to see what its like to "run" \[or fly\] around my environment? I heard an instructor say that exact thing in a Maya training video and I'd like to know more about "How Game Engines and Maya are related to each other." He stated this would be done to see how things look in "size" (e.g. I assume he meant: 'How big is the cathedral, bridge, wall, building, etc.').

I've tried to research such information but it's too complicated, and detailed. I just want a simplistic response to my query. Thanks to everyone willing to help and not criticize my question.

# Answer
It means that you can export your environment (or Game Level) from Auto-desk Maya to some game engine in order to test it by becoming a player of that environment. Game engine will treat your exported environment as game level and you can run and fly around like a player.
> 1 votes

---
Tags: level-design, maya
---


title: PHP Battle System for RPG game

text:
# Question
Title: PHP Battle System for RPG game
I posted this a while ago on stackoverflow, they thought it would be better place here, I agree.

Essentially I know what I want to accomplish, and I have something to the effect of what I want but I am not satisfied with it. Here's the problem.

Each user has some states: STR (how hard they hit), DEF (dodging/blocking attacks), SPD (when they can strike), and STAMINA (basically their endurance in game, if this runs out they can no longer fight and lose)

What I need is something like this:

> UserA Stats: STR: 1,000 DEF: 2500 SPD: 2000 (HP: 1000/1000)
>
> UserB Stats: STR: 1,500 DEF: 500 SPD: 4000 (HP: 1000/1000)

Because the second user has double the speed, he lands twice the amount of hits on the first user, before he gets hit. Because he has less strength than the first users defence, he will do no, to little damage. This is how the battle would theoretically go:

> UserB strikes UserA for 0 damage
>
> UserB strikes UserA for 0 damage
>
> UserA strikes UserB for 500 damage
>
> UserB strikes UserA for 0 damage
>
> UserB strikes UserA for 0 damage
>
> UserA strikes UserB for 500 damage, and sends him to the hospital!

I was using this code, which is buggy, and not efficient, I just need a better way to do this: http://pastebin.com/15LiQQuJ

Oh, and if anyone has some good ideas on how to improve the concept that would be cool too! It's not that elaborate so I'll be thinking of all sorts of things to make it more dynamic.

Thanks.

# Answer
> 1 votes
If I understand correctly, you're just trying to figure out a better way to figure out who attacks when and how often. Looks like everything is autocalculated, so you don't need to figure out the proper *delay* between attacks or anything. You really just need to figure out how many attacks the fast guy gets before the slow guy gets one. You should be able to do that by adding code similar to this to resolve\_battle:

```
if( $user_a['SPD'] > $user_b['SPD']){
 $a_is_faster = true; // this variable remembers which of the two is faster (true if UserA, false if UserB)
 $speed_ratio = $user_a['SPD'] / $user_b['SPD']; // this var remembers how many attacks the faster player gets before the slower player attacks
}else{
 $a_is_faster = false;
 $speed_ratio = $user_b['SPD'] / $user_a['SPD'];
}
$speed_counter = $speed_ratio; // this keeps track of how many more attacks the faster player is going to get before the slower player gets one
while($in_progress){

 if($speed_counter>=1){
  $speed_counter--;
  if($a_is_faster){
  /* code to make userA attack */
  }else{
  /* code to make userB attack */
  }
 }else{
  $speed_counter += $speed_ratio; // when the slower player gets their attack, we add more attacks to the faster player's counter
  if($a_is_faster){
  /* code to make userB attack */
  }else{
  /* code to make userA attack */
  }
 }

 }
}

```

---
Tags: php
---


# Question
Title: Should I use an SQL database to store data in a desktop game?
### Developing a Game Engine

I am planning a computer game and its engine. There will be a 3 dimensional world with first person view and it will be single player for now. The programming language is C++ and it uses OpenGL.

### Data Centered Design Decision

My design decision is to use a data centered architecture where there is a global **event manager** and a global **data manager**. There are many components like physics, input, sound, renderer, ai, ... Each component can trigger and listen to **events**. Moreover, each component can read, edit, create and remove **data**.

The question is about the data manager.

### Whether to Use a Relational Database

Should I use a SQL Database, e.g. SQLite or MySQL, to store the game data? This contains virtually all game content like items, characters, inventories, ... Except of meshes and textures which are even more performance related, so I will keep them in memory.

Is a SQL database fast enough to use it for realtime reading and writing game informations, like the position of a moving character? I also need to care about cross-platform compatibility. Aside from keeping everything in memory, what alternatives do I have?

### Advantages Would Be

The advantages of using a relational database like MySQL would be the data orientated structure which allows fast computation. I would not need objects for representing entities. I could easily query data of objects near the player needed for rendering. And I don't have to take care about data of objects far away. Moreover there would be no need for savegames since the hole game state is saved in the database. Last but not least, expanding the game to an online game would be relative easy because there already is a place where the hole game state is stored.

# Answer
An SQL database is not nearly fast enough to use for realtime reading and writing game information. Such data is almost always kept in memory, in traditional data structures.

There may be some benefit to using an embedded database such as SQLite for certain types of data, eg. static data that doesn't change during gameplay but does change during development. This could then be deployed as part of the final game where SQLite is only really used when loading up the game for the first time, or when starting a new level, etc.

However there are many downsides too - it is hard to patch individual parts of the data when they're stored in a single database file, it is not ideal for many types of complex data that games need (and which you said you'd store outside - but will have references to and from things inside), it is not very flexible when you need to change the schema, it is not necessarily backwards compatible after you change the schema, etc.

For these reasons, most game developers will just use their own format. Professional developers who are performance conscious sometimes go one step further and save the in-memory data structure directly to disk so that it can be loaded in with a minimum of processing.

And if you really need text-based tabular data that is easily edited, you could use a simple text based format, such as CSV, XML, JSON, YAML, etc.
> 11 votes

# Answer
A database isn't fast, using a database is **a whole lot** slower than traditional memory access. The reason is simple, a database is dynamic, there is a bunch of overhead attached to it, the queries need to be parsed, hashes need to be computed and other stuff.

There are is only one advantage from using a database and that's persistence. You can run one or multiple applications with one database over a long period of time without having to fear data lass. But game clients have absolutely no need for that.

So, you want to get every object which is less than 1000px away?
That would be:

```
List<Entity> retVal;
for(entity in entities)
  if(Distance(entity.pos(), to) < 1000)
     retVal.append(entity);
return retVal;

```

Now what would you think would a database do if you asked it to get every object less than 1000px away?
It would do exactly the same! Just with a bunch of overhead which would make this one extremely simple operation cost about 100 times the processor time (depending on how many entities you have). Databases ain't no magic.

Don't use databases for anything else but server applications.
> 5 votes

---
Tags: architecture, performance, databases
---


# Question
Title: How do I properly center Nifty GUI elements on screen?
I am new to JME3 game engine but I know Android XML GUI layouts pretty good. I have a simple layout here and I cant figure out what is wrong. Here is my XML code:

```
<?xml version="1.0" encoding="UTF-8"?>
<nifty xmlns="http://nifty-gui.sourceforge.net/nifty-1.3.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://nifty-gui.sourceforge.net/nifty-1.3.xsd
                   http://nifty-gui.sourceforge.net/nifty-1.3.xsd">

<useControls filename="nifty-default-controls.xml" />
<useStyles filename="nifty-default-styles.xml" />

<screen id="start" controller="com.jasoncrosby.game.farkle.gui.MenuScreenGui">
    <layer id="layer" backgroundColor="#66CD00" childLayout="center">
        <panel id="panel" align="center" valign="center" childLayout="center" visibleToMouse="true">
            <image filename="Textures/wood_floor.png" height="95%" width="95%"/>

            <panel id="panel" align="center" valign="center" childLayout="center" visibleToMouse="true">
                <text text="test" font="Interface/Fonts/Eraser.fnt"></text>
            </panel>
        </panel>
    </layer>
</screen>

```

Everything works well until I get to displaying the text. I have tried different alignments and tried moving the text into different panels but no matter what I do the text is never in the center of the screen. It's always in the upper left corner, so far I can only see the lower right part of the text. How can I center the text element in the center of the screen?

# Answer
> 5 votes
I believe the problem you're having is that neither your layer, nor your panel are the size of screen. They are both very small in the upper left (which I believe is the default). So centering your image just puts them in the center of a very small rectangle in the upper left.

If you want to center your text on screen, you need to make a panel the size of the screen and then center it in that panel.

---
Tags: jmonkeyengine
---


# Question
Title: Affect movieclip scale from a .as doc to another
I've been working on a game following a tutorial on the internet, the game is an avoider where you have the Avatar, that has to avoid the objects that fall.

The way it is made is: I have a DocumentClass which addChild's the screen you should be seeing and removeChild's the screen that you were.

For example: first it loads the menuScreen, then when you press play unloads menu and loads playscreen. When you die it loads the gameoverScreen and loads the playscreen.

And from the gameOverScreen you can press the SHOP button to go to the shop. From here on I'm on my own and not following any tutorials.

The shop has a button that is supposed to alter the Avatar's X and Y scale to 0.5, but the problem is: how do I make that work?

I tried creating a sharedObject.data.avatarSize, on the store's size button the code would be something like:

```
sharedObject.data.avatarSize *= 0.5;

```

And on the AvoiderGame.as, which is the most of the actual game, on the part where the avatar is created I tried putting this after it's creation:

```
scaleX.avatar = sharedObject.data.avatarSize;
scaleY.avatar = sharedObject.data.avatarSize;

```

This did not work since it gives me the error 1009 saying can't access something that is null. I tried this before "using" the sharedObject:

```
if( sharedObject.data.avatarSize == null )
{
    sharedObject.data.avatarSize = 1;
}

```

But it did not work...

So now I'm not sure on what to do. I know we should reduce global variables as much as we can but how do I do it?

--EDIT--

Also, if it helps, I'm using Flash CS5 and working with AS3.0 and if you don't know about flash, you can also tell me how you would do it on any other language and I would try to convert it to flash.

# Answer
> 0 votes
Solved it!

I had to do a lot of work for it to work though, but it seems to have been mostly a distraction on my part.

Had to create the sharedObject var on the .as files it was used in, which I had already done, but I also had to associate them with the save file where they were, of course!

Then after that the code didn't really give me much trouble, thanks though, I only managed with some tips and tricks from here.

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


# Question
Title: Confusion about Rotation matrices from Euler Angles
I am trying to learn more about Euler Angles so as to help myself in understanding how I can control my camera better in the game.

I came across the following formula that converts Euler Angles to rotation matrices:

In the equation, I could see that the first matrix from the left is the rotation matrix about x-axis, the second is about y-axis and the third is about z-axis.

From my understanding about ordinary matrix transformations, the later transformation is always applied to the right hand side. And if I'm right about this, then the above equation should have a rotation order starting from rotating about z-axis, y-axis, then finally x-axis.

But, from the symbols it seems that the rotation order start rotating about x-axis, then y-axis, then finally z-axis. What should the actual order of the rotation be?

Also, I am confuse about if the input vector, in this case, would be a row vector on the left, or a column vector on the right?

# Answer
It really depends on how you write your vector. DirectX uses row vectors, OpenGL uses column vectors. The matrices need to be transposed accordingly.

If you consider your vector a column vector, it goes to the right: `R_x R_y R_z v`. But if it's a row vector, it needs to go on the left: `v R_x R_y R_z`.

The order also changes depending on this definition, because the matrix "closest" to the vector is applied first. So for a column vector, the order would be z, y, x, but for a row vector it's x, y, z.

And then it also depends on how your Euler angles are defined. Wikipedia gives a bunch of different options with corresponding matrices: http://en.wikipedia.org/wiki/Euler\_angles#Matrix\_orientation
> 3 votes

# Answer
With matrix transformation, it always works right to left. The right most matrix is 'applied' first.

Also, input vector would be column on the right.

Rule of thumb: the matrix closest to the vector goes first.
> 0 votes

---
Tags: mathematics, rotation
---


# Question
Title: How do I implement Unreal-like object serialization?
Recently, I've been working on the core of my engine, and as I'm moving forward I find myself developing throwaway code to read files and simple data into the engine. This got me thinking about how I should implement a file management system.

After a bit of googleing I came across the Unreal Package format, and boy does it look like the perfect one.

I think it's good because the way how it allows you to separate different assets into different packages and allow something like a level to reference the different packages.

I was just wondering, is this possible with C#? Because the built-in serialization API in .NET does not seem to support any form of this, only reading and writing to a single file.

# Answer
Yes it's possible. You don't have to use the built in serialization API. Create your own serialization methods for the objects you want to read/write to disk.

You can make heavy use of the BitConverter method GetBytes, for writing your data. As well as the various `ToType()` methods for reading your binary data.

Writing your own means you're in full control of how the data is written. You can structure it however you want, in whatever directory structure you want.
> 1 votes

---
Tags: c#, serialization
---


# Question
Title: How to implement a 2d collision detection for Android
I am making a 2d space shooter using opengl ES. Can someone please show me how to implement a collision detection between the enemy ship and player ship. The code for the two classes are below:

Player Ship Class:

```
package com.proandroidgames;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;

public class SSGoodGuy {
    public boolean isDestroyed = false;
    private int damage = 0;

    private FloatBuffer vertexBuffer;
    private FloatBuffer textureBuffer;
    private ByteBuffer indexBuffer;
    private float vertices[] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f, 0.0f, };
    private float texture[] = { 0.0f, 0.0f, 0.25f, 0.0f, 0.25f, 0.25f, 0.0f,
            0.25f, };
    private byte indices[] = { 0, 1, 2, 0, 2, 3, };

     public void applyDamage(){
            damage++;
            if (damage == SSEngine.PLAYER_SHIELDS){
                isDestroyed = true;
            }

        }

    public SSGoodGuy() {
        ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
        byteBuf.order(ByteOrder.nativeOrder());
        vertexBuffer = byteBuf.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);
        byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
        byteBuf.order(ByteOrder.nativeOrder());
        textureBuffer = byteBuf.asFloatBuffer();
        textureBuffer.put(texture);
        textureBuffer.position(0);
        indexBuffer = ByteBuffer.allocateDirect(indices.length);
        indexBuffer.put(indices);
        indexBuffer.position(0);
    }

    public void draw(GL10 gl, int[] spriteSheet) {
        gl.glBindTexture(GL10.GL_TEXTURE_2D, spriteSheet[0]);
        gl.glFrontFace(GL10.GL_CCW);
        gl.glEnable(GL10.GL_CULL_FACE);
        gl.glCullFace(GL10.GL_BACK);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
        gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
                GL10.GL_UNSIGNED_BYTE, indexBuffer);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glDisable(GL10.GL_CULL_FACE);
    }
}

```

Enemy Ship Class:

```
package com.proandroidgames;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

public class SSEnemy {

    public float posY = 0f;
    public float posX = 0f;
    public float posT = 0f;
    public float incrementXToTarget = 0f;
    public float incrementYToTarget = 0f;
    public int attackDirection = 0;
    public boolean isDestroyed = false;
    private int damage = 0;

    public int enemyType = 0;

    public boolean isLockedOn = false;
    public float lockOnPosX = 0f;
    public float lockOnPosY = 0f;

    private Random randomPos = new Random();

    private FloatBuffer vertexBuffer;
    private FloatBuffer textureBuffer;
    private ByteBuffer indexBuffer;

    private float vertices[] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f, 0.0f, };

    private float texture[] = { 0.0f, 0.0f, 0.25f, 0.0f, 0.25f, 0.25f, 0.0f,
            0.25f, };

    private byte indices[] = { 0, 1, 2, 0, 2, 3, };

    public void applyDamage() {
        damage++;
        switch (enemyType) {
        case SSEngine.TYPE_INTERCEPTOR:
            if (damage == SSEngine.INTERCEPTOR_SHIELDS) {
                isDestroyed = true;
            }
            break;
        case SSEngine.TYPE_SCOUT:
            if (damage == SSEngine.SCOUT_SHIELDS) {
                isDestroyed = true;
            }
            break;
        case SSEngine.TYPE_WARSHIP:
            if (damage == SSEngine.WARSHIP_SHIELDS) {
                isDestroyed = true;
            }
            break;

        }
    }

    public SSEnemy(int type, int direction) {
        enemyType = type;
        attackDirection = direction;
        posY = (randomPos.nextFloat() * 4) + 4;
        switch (attackDirection) {
        case SSEngine.ATTACK_LEFT:
            posX = 0;
            break;
        case SSEngine.ATTACK_RANDOM:
            posX = randomPos.nextFloat() * 3;
            break;
        case SSEngine.ATTACK_RIGHT:
            posX = 3;
            break;
        }
        posT = SSEngine.SCOUT_SPEED;

        ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
        byteBuf.order(ByteOrder.nativeOrder());
        vertexBuffer = byteBuf.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);

        byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
        byteBuf.order(ByteOrder.nativeOrder());
        textureBuffer = byteBuf.asFloatBuffer();
        textureBuffer.put(texture);
        textureBuffer.position(0);

        indexBuffer = ByteBuffer.allocateDirect(indices.length);
        indexBuffer.put(indices);
        indexBuffer.position(0);
    }

    public float getNextScoutX() {
        if (attackDirection == SSEngine.ATTACK_LEFT) {
            return (float) ((SSEngine.BEZIER_X_4 * (posT * posT * posT))
                    + (SSEngine.BEZIER_X_3 * 3 * (posT * posT) * (1 - posT))
                    + (SSEngine.BEZIER_X_2 * 3 * posT * ((1 - posT) * (1 - posT))) + (SSEngine.BEZIER_X_1 * ((1 - posT)
                    * (1 - posT) * (1 - posT))));
        } else {
            return (float) ((SSEngine.BEZIER_X_1 * (posT * posT * posT))
                    + (SSEngine.BEZIER_X_2 * 3 * (posT * posT) * (1 - posT))
                    + (SSEngine.BEZIER_X_3 * 3 * posT * ((1 - posT) * (1 - posT))) + (SSEngine.BEZIER_X_4 * ((1 - posT)
                    * (1 - posT) * (1 - posT))));
        }

    }

    public float getNextScoutY() {
        return (float) ((SSEngine.BEZIER_Y_1 * (posT * posT * posT))
                + (SSEngine.BEZIER_Y_2 * 3 * (posT * posT) * (1 - posT))
                + (SSEngine.BEZIER_Y_3 * 3 * posT * ((1 - posT) * (1 - posT))) + (SSEngine.BEZIER_Y_4 * ((1 - posT)
                * (1 - posT) * (1 - posT))));
    }

    public void draw(GL10 gl, int[] spriteSheet) {
        gl.glBindTexture(GL10.GL_TEXTURE_2D, spriteSheet[0]);

        gl.glFrontFace(GL10.GL_CCW);
        gl.glEnable(GL10.GL_CULL_FACE);
        gl.glCullFace(GL10.GL_BACK);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

        gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
                GL10.GL_UNSIGNED_BYTE, indexBuffer);

        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glDisable(GL10.GL_CULL_FACE);
    }

}

```

# Answer
> 2 votes
Another option is to implement "Shape" objects, like rectangles, lines, etc... just like the awt package does. You can implement methods like "contains" or "intersect" to know if the shape A is inside or touching shape B.

Doing so, you may assign shapes as an attribute of the game elements, setting the shape type, dimensions, etc... Then in the main loop you could check it out very easy.

# Answer
> 0 votes
You calculate player and enemy ship X and Y values + size to get the amount of pixels they take up.

Then you look if they are touching by comparing all the values, and if they are touching you execute the code.

I can't give a code example because I'm not familiar with the language you use. But the math can look like:

> If SHIP X + SHIP WIDTH is more or equal to ENEMY X and SHIP Y is less or equal to ENEMY Y + ENEMY HEIGHT

This translates to "is the ship's top-right corner touching enemy bottom-left corner?".

I hope this helps.

# Answer
> 0 votes
**hustlerinc**'s answer is fine for most shooter needs, and most games in general; you don't always need pixel perfect collision.

However, if you did want pixel perfect collision, I can't give you actual code since I don't know off the top of my head but the gist is this: you compare every pixel of each image, in their respective locations, until you get to a point on screen where a non-transparent pixel on one image overlaps another non-transparent pixel on the other.

This can get pretty intensive with limited resources, though, so unless you absolutely need it pixel perfect, I'm sure the ol' hitbox method is fine.

# Answer
> 0 votes
maybe use something like this:

```
import static org.junit.Assert.*;
import java.awt.Point; // uses as a line segment
import java.awt.Rectangle;
import org.junit.Test;
enum C { // collision? intersection?
    aOnleft,aAdjacientToB,aOverlapsB,bFlushRight,bInsideA,aFlushLeft,identical,bFlushLeft,bOnleft,bAdjacientToA,bOverlapsA,aFlushRight,aInsideB;
    static C intersect(Point a,Point b) { // a and b are not points, they are line segments
        return intersect(a.x,a.y,b.x,b.y);
    }
    static C intersect(int a1,int a2,int b1,int b2) {
        if(!(a1<a2&&b1<b2))
            throw new RuntimeException("range error!");
        if(a1<b1) {
            if(a2<b1)
                return aOnleft;
            else if(a2==b1)
                return aAdjacientToB;
            else if(a2<b2)
                return aOverlapsB;
            else if(a2==b2)
                return bFlushRight;
            else return bInsideA;
        } else if(a1==b1) {
            if(a2<b2)
                return aFlushLeft;
            else if(a2==b2)
                return identical;
            else return bFlushLeft;
        } else { // b1 < a1
            if(b2<a1)
                return bOnleft;
            else if(b2==a1)
                return bAdjacientToA;
            else if(b2<a2)
                return bOverlapsA;
            else if(b2==a2)
                return aFlushRight;
            else return aInsideB;
        }
    }
    static boolean areDisjoint(Point a,Point b) {
        switch(intersect(a,b)) {
            case aOnleft:
            case bOnleft:
                return true;
            default:
                return false; // are intersecting or adjacient
        }
    }
    static boolean areAdjacient(Point a,Point b) {
        switch(intersect(a,b)) {
            case aAdjacientToB:
            case bAdjacientToA:
                return true;
            default:
                return false; // are disjoint or intersecting at more than one point
        }
    }
    static boolean areIntersecting(Point a,Point b) { // at more than one point
        return !areDisjoint(a,b)&&!areAdjacient(a,b);
    }
    static boolean areDisjoint(Rectangle r1,Rectangle r2) {
        switch(intersect(r1.x,r1.x+r1.width,r2.x,r2.x+r2.width)) {
            case aOnleft:
            case bOnleft:
                switch(intersect(r1.y,r1.y+r1.height,r2.y,r2.y+r2.height)) {
                    case aOnleft:
                    case bOnleft:
                        return true;
                    default:
                        return false; // are intersecting or touching
                }
            default:
                return false; // are intersecting or touching
        }
    }
}
public class CTestCase {
    @Test public void testIntersectPointPointAOnLeft() {
        a.setLocation(1,2);
        b.setLocation(3,4);
        assertEquals(C.aOnleft,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointAAdjacientToB() {
        a.setLocation(1,2);
        b.setLocation(2,4);
        assertEquals(C.aAdjacientToB,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointAOverlapsB() {
        a.setLocation(1,3);
        b.setLocation(2,4);
        assertEquals(C.aOverlapsB,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointBFlushRight() {
        a.setLocation(1,4);
        b.setLocation(2,4);
        assertEquals(C.bFlushRight,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointAInsideB() {
        a.setLocation(1,4);
        b.setLocation(2,3);
        assertEquals(C.bInsideA,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointAFlushLeft() {
        a.setLocation(2,3);
        b.setLocation(2,4);
        assertEquals(C.aFlushLeft,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointIdentical() {
        a.setLocation(1,2);
        b.setLocation(1,2);
        assertEquals(C.identical,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointBFlushLeft() {
        a.setLocation(1,4);
        b.setLocation(1,3);
        assertEquals(C.bFlushLeft,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointBOnLeft() {
        a.setLocation(3,4);
        b.setLocation(1,2);
        assertEquals(C.bOnleft,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointBAdjacientToA() {
        a.setLocation(2,4);
        b.setLocation(1,2);
        assertEquals(C.bAdjacientToA,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointBOverlapsA() {
        a.setLocation(2,4);
        b.setLocation(1,3);
        assertEquals(C.bOverlapsA,C.intersect(a,b));
    }
    @Test public void testIntersectPointPointAFlushRight() {
        a.setLocation(2,4);
        b.setLocation(1,4);
        assertEquals(C.aFlushRight,C.intersect(a,b));
    }
    @Test public void testAreDisjoint() {
        a.setLocation(1,2);
        b.setLocation(3,4);
        assertTrue(C.areDisjoint(a,b));
    }
    @Test public void testAreAdjacient() {
        a.setLocation(1,2);
        b.setLocation(2,4);
        assertTrue(C.areAdjacient(a,b));
    }
    @Test public void testAreIntersecting() {
        a.setLocation(1,3);
        b.setLocation(2,4);
        assertTrue(C.areIntersecting(a,b));
    }
    Point a=new Point(),b=new Point();
}

```

---
Tags: java, android, collision-detection, opengl-es, graphics-programming
---


title: Sony PSM SDK's 2D game engine

text:
# Question
Title: Sony PSM SDK's 2D game engine
I have started with the Sony PSM SDK this week, I'm interested in creating a little 2D game and have been reading through the web about a so called "2D game engine" integrated into the SDK.

Some information I read suggested that it was added on January 2012, but I have been going through the documentation and haven't been able to find any reference to it.

Does anybody know if they finally introduced the 2D game engine for the PSM SDK?

# Answer
Open the documentation and navigate to:
**PlayStation(R)Mobile SDK -\> Related Pages -\> User Guide -\> GameEngine2D**

There are also examples for Physics2D, In-App purchasing, On Screen Controller etc.

---

*You might be in the wrong documents. <br>The documentation installed under this path for me: C:/Users/Public/Documents/PSM/doc/en/index.html*
> 2 votes

---
Tags: 2d, mobile
---


# Question
Title: Specifying force and angle in ApplyImpulse in box2d
I need to apply an impulse on a object with a particular force and at a particular angle in Box2d. If I am right the syntax would be the following:

> body.GetBody().ApplyImpulse(new b2Vec2(direction, power),body.GetBody().GetWorldCenter());

The problem is my direction is in angles. I found a discussion where it was said that the way we can convert an angle into a vector would be as:

> new b2Vec2(Math.cos(angle\*Math.PI/180),Math.sin(angle\*Math.PI/180));

Now I am not sure how to combine these two. In other words, if I wish to apply a force of 30 units at an angle of 30 degrees at the center of the object, how should I do it?

# Answer
The first parameter of applyImpulse is a vector, the direction of the vector indicate the direction the impulse is to be applied and the *length* of the vector indicates the strength of the impulse.

your code;

```
new b2Vec2(Math.cos(30*Math.PI/180),Math.sin(30*Math.PI/180));

```

creates a vector at 30 degrees from the positive x-asis with a length of one. In order to make the vector longer, say 50 units in length(therefore 50 times stronger), just multiply both the x & y components of the vector by 50;

```
new b2Vec2(50*Math.cos(angle*Math.PI/180),50*Math.sin(angle*Math.PI/180));

```

similarity of you want a much weaker impulse, you can multiply by a fraction.

More readably, you could write;

```
 impulse = new b2Vec2(Math.cos(angle*Math.PI/180),Math.sin(angle*Math.PI/180));
 impulse=50*impulse;
 body.GetBody().ApplyImpulse(impulse,body.GetBody().GetWorldCenter());

```

finally you can use b2Rot() to calculate a vector from an angle;

```
impuse=new b2Rot(angle).GetXAxis(); // returns a vector at angle degrees to the x-axis

```
> 3 votes

---
Tags: javascript, box2d
---


# Question
Title: Collision detection on a 2D hexagonal grid
I'm making a casual grid-based 2D iPhone game using Cocos2D. The grid is a "staggered" hex-like grid consisting of uniformly sized and spaced discs. It looks something like this:

I've stored the grid in a 2D array. Also, I have a concept of "surrounding" grid cells. Namely the six grid cells surrounding a particular cell (except those on the boundries which can have less than six).

Anyways, I'm testing some collision detection and it's not working out as well as I had planned. Here's how I currently do collision detection for a moving disc that's approaching the stationary group of discs:

1. Calculate ij-coordinates of grid cell closest to moving cell using moving cell's xy-position
2. Get list of surrounding grid cells using ij-coordinates
3. Examine the surrounding cells. If they're all empty then no collision
4. If we have some non-empty surrounding cells then compare the distance between the disc centers to some minimum distance required for a collision
5. If there's a collision then place the moving disc in grid cell ij

So this works but not too well. I've considered a potentially simpler brute force approach where I just compare the moving disc to all stationary discs at each step of the game loop. This is probably feasible in terms of performance since the stationary disc count is 300 max. If not then some space-partitioning data structure could be used, however that feels too complex.

**What are some common approaches and best practices to collision detection in a game like this?**

**Edit - More info**: This current implementation has a few bugs like discs will sometimes stick over an occupied grid slot. Also it's too difficult to get discs into small spaces. These are all fixable. I asked here just to learn about alternative approaches.

# Answer
You could treat circles (balls) as hexagons, and calculate exact position of a circle mathematically, but I suggest you use a grid, as in these answers:

Making an efficient collision detection system

Fast, accurate 2d collision

Then get balls registered on a cell under mouse cursor and iterate through them to see which is in shortest distance to the cursor.
> 1 votes

# Answer
I don't know what is the actual issue with this algorithm, since you didn't provide any explanation, but assuming you get false negatives for collision, I would suggest running your check not for the nearest grid cell but for all the grid cells that the moving disc collides with.
> 1 votes

---
Tags: 2d, collision-detection, cocos2d-iphone, hexagonal-grid
---


# Question
Title: How to implement explosion in OpenGL with a particle effect?
I'm relatively new to OpenGL and I'm clueless how to implement explosion. So could anyone give me some ideas how to start? Suppose the explosion occurs at location $(x, y, z)$, then I'm thinking of randomly generate a collection of vectors with $(x, y, z)$ as origin, then draw some particle (`glutSolidCube`) which move along this vector for some period of time, says after 1000 updates, it disappear. Is this approach feasible? A minimal example would be greatly appreciated.

# Answer
> 8 votes
You are on the right track.

Typically for particle effects, flat triangles or quads are used for the particles as opposed to something like glutSolidCube. Often the quad are billboarded so that they are always oriented to the camera (so you never see them edge on). Having said that, there is no reason why you can't use cubes for your particles (apart from performance)

The outline for a particle effect is something like this;

1. create a buch of particles, each particle will have its own velocity, position etc (see below)
2. each particle is drawn as a textured quad, usually blended, with transparent edges. The texture and colour of the quad depends on the effect you are trying to achieve.
3. When the particles are spawned at they explosion point,they will be launched out a random velocities, they will be initially very small, but are scaled larger over time. Usually each particle will also have some random angular velocity so the will also rotate as they move away from the spawn point.
4. As a particle grows older, at some point it will be forced to fade away, once it is are completely transparent they will be removed.

There are a lot of properties to control to get the effect you want

* range of initial velocities
* rate of spawning
* response to gravity & wind
* range of angular velocities
* rate of fading
* time to live
* rate of growing
* particle texture(s) \[often same texture is used for all particles\]
* potentially many more

Here is another opengl particle effect tutorial in OpenGL/glut

# Answer
> 1 votes
A direct answer would be pretty long so here is a link to a decent tutorial on such a thing.

http://nehe.gamedev.net/tutorial/particle\_engine\_using\_triangle\_strips/21001/

---
Tags: opengl, physics, particles
---


# Question
Title: MMO market (subscribe model, not play for free)
What mmo games do you know (play) with WoW-like monetization-subscribing (not play 4 free)? And how many active gamers playing them and what cost of each of them?

Thank you!

# Answer
Take a look at http://www.mmorpg.com/gamelist.cfm \- it lists about hundred games with their payment models.

The number of active subscribers is usually hard to find out. The only source is usually the marketing department of each game, which often polishes the number.
> 3 votes

---
Tags: mmo, monetization, statistics
---


# Question
Title: Read only array, deep copy or retrieve copies one by one? (Performance and Memory)
The question is asked regarding an environment with garbage collection.(Java, AS3)

I am writing a level editor using MVC and the view needs to have read only access to the data in the model for rendering purposes. This can be done in AS3 in several ways:

1. With a function that retrieves the contents of each specific object by index.
2. Updating with all the recently modified objects(complicated), this requires keeping the id of the view and the last update date. Keeping the objects sorted by the last change date and then pushing in all the newly changed objects.
3. Returning a copy of the whole array every time.

What is the most effective way to handle a read only array(not implemented in the language)? Does anyone have performance statistics that shows the performance boost gained for using method 2? And when is method 1 severely inferior to method 3.

# Answer
Well typically, garbage collection speed and efficiency depends on the object count and size. Returning a full array deep copy is requires both more memory and and time, and creates more new objects. To me, creating a single object copy is more efficient.

However there are most probably exceptions for some particular situations (accessing same index multiple times for example).
> 3 votes

# Answer
Not a hint on performance but a suggestion for good practice and improvement.

You can have a look at the iterator design pattern which basically only provides an interface to loop over values.
> 0 votes

---
Tags: actionscript-3, performance, data-structure
---


# Question
Title: Can I use a genetic algorithm for balancing character builds?
I'm starting to build a online PVP (duel like, one-on-one) game, where there is leveling, skill points, special attacks and all the common stuff. Since I have never done anything like this, I'm still thinking about the math behind the levels/skills/specials balance.

So I thought a good way of testing the best builds/combos, would be to implement a Genetic Algorithm. It'd be like this:

* Generate a big group of random characters
* Make them fight, level them up accordingly to their victories(more XP)/losses(less XP)
* Mate the winners, crossing their builds, to try and make even better characters
* Add some more random chars, emulating new players
* Repeat the process for some time, or util I find some chars who can beat everyone's butt

I could then play with the math and try to find better balances to make sure that the top x% of chars would be a mix of various build types.

So, is it a good idea, or is there some other, easier method to do the balancing?

**Edit:** Interesting thoughts in all those answers, still waiting to mark just one as resolved. I can see the problem with the AI implementation, but in my specific case, the AI is pretty straightforward. It'll be based directly on the opponent build and chosen parameters for the duel. (The human player will not have access to those info, so can not foresee the enemy stats and strategy). I've read a topic about testing, and I think I'll starting with simple automated tests and in the future evolve it to a genetic algorithm.

# Answer
> 10 votes
The problem with this approach is in this statement -

"Add some more random chars, emulating new players"

The task of randomly generating every permutation of character builds is trivial compared to making the AI that would actually use that build appropriately. It would be extremely difficult to tell the difference between a poor build and a poor AI in this setup - an amazing build in the hands of a dumb AI is still a dumb build.

Since the builds are a finite set, it would be possible to simply map each one out, assign potential damage, etc to each and simply work it out procedurally rather than using a genetic algorithm.

# Answer
> 6 votes
This approach would only work out when your gameplay consists only of character customization and leaves players little or no tactical choices during actual combat.

Many game-breakers require not just having a specific character build, but also require that the player plays it in an unconventional way the developers did not expect. It depends on your actual gameplay, but when it isn't that trivial, developing an AI which can come up with unconventional tactics on its own might be a project magnitudes more complex than the entire rest of your game.

# Answer
> 3 votes
As ultrahuman pointed out AI for this would be very hard to do. In addition your algorithm would balance the game for the AI players. :-) What I mean is that human players will often behave quite unexpectedly and will tend to exploit weaknesses etc.

However, you are somewhat on the right track. Except you should use real players instead of AI. :-) Or in other words it is called a beta. So, I suggest you should create a reasonable set of starting conditions. Then with each level of testing you should get more people involved and with each iteration you should refine the rules.

It is actually exactly what you propose, except instead of spending months on test AI, you let humans replace AI players. As a bonus, they can comment on the fun factor of the game/balance, something AI players cannot.

# Answer
> 1 votes
I recommend taking a look into the "Genetic Algorithms: Evolving the Perfect Troll" chapter from AI Game Programming Wisdom. I remember that the author describes using a genetic algorithm to create the proper parameters that will give him the best troll to launch at players and the process he followed to achieve the result.

The summary from my recollections (i don't have the book available anymore and read it at least 3 years ago) is that is quite likely you will find surprising results on your first attempts because your fitness function will not really describe what you want. In the example, the author used "time alive" as the first measure of how good a given individual performed, and after several generations he ended up with a bunch of coward and hard-to-find trolls that indeed gave him the best "survivability" :P. The lesson here, is that it is possible to use genetic algorithms in order to look for the "best set of parameters to maximize X", but you have to take into account that your fitness will prepare your character exactly to do X, and sometimes that's not what you want.

With that said, I think is a good starting point for your purpose. My guess is that you will have to run several simulations using different fitness functions in order to generate your "current objective oriented" best character. For example the "hardest hitting" character or the "magic user" character.

---
Tags: level-design, testing, character
---


title: Directional Lights

text:
# Question
Title: Directional Lights
I'm working on a game idea (2D) that needs directional lights. Basically I want to add light sources that can be moved and the light rays interact with the other bodies on the scene.

What I'm doing right now is some test where using sensors (box2d) and ccDrawLine I could achieve something similar to what I want. Basically I send a bunch of sensors from certain point and with raycast detect collisions, get the end points and draw lines over the sensors.

Just want to get some opinions if this is a good way of doing this or is other better options to build something like this?

Also I would like to know how to make a light effect over this area (sensors area) to provide a better looking light effect. Any ideas?

# Answer
> 1 votes
The better way would be to generate and render shadow volumes. The algorithm itself is too complex to correctly describe it from memory but the idea itself, at least for directional lights, is quite simple. Since you're using Box2D, I'll assume you have convex polygons everywhere prepared.

Shadow volume polygon generation:

For each edge, check dot(edge normal, light direction) to know if edge is lit or in shadow. Remember the same value of the previous edge. There are 4 cases to process from here:

* Current edge (CE) is lit, previous edge (PE) is lit: just add second vertex
* CE in shadow, PE in shadow: add second vertex + offset (light direction * big number)
* CE in shadow, PE is lit: add first vertex + offset, add second vertex + offset
* CE is lit, PE in shadow: add first vertex, add second vertex

This shadow volume will include the polygon itself so as to avoid making it appear lit. It is also convex so there should be no problems rendering it.

Rendering: for each light, clear shadow buffer, draw all volumes to buffer, use the buffer to draw the light.

The buffer can be a z-buffer or a stencil buffer (creates pixel-perfect shadows) but it can also be a shadowmap, though in that case you'll also have to use the stencil to prevent the solid polygon from appearing lit.

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


# Question
Title: Panning a 3d viewport in 2d direction with rotated camera
I am using below code to pan the viewport (action script 3 code using flare3d framework)

```
_mainCamera.x-= Input3D.mouseXSpeed;
_mainCamera.z+= Input3D.mouseYSpeed;

```

Where as Input3D.mouse\[X|Y\]Speed gives the displacement of the mouse on the X/Y axis starting from the position of the last frame.

This works perfect if my camera is not rotated. However, if I rotate the camera (x by 30, y by 60) and pan the camera then it goes wrong. Which is actually correctly panning according to the code. But this is not desired and I know I need to do some math to get the correct x/y which I am not aware of it.

Can some one help me achieving it?

Update:

I am getting an Idea but I am not sure how to do it :(

1. Get the mouseX/Y deltas (xd,yd)
2. Get the current camera coords (pos3d)
3. Convert to screen coords (pos2d)
4. Add deltas to screen coords (pos2d+ (xd,yd))
5. Convert above coords to 3d coords

# Answer
> 2 votes
I've faced this exact same issue a few days ago. I have a camera class which deals with camera logic. It has a method which receives the mouse deltas and according to it, changes the camera speed (because I have a smooth panning using speed instead of position), but for the position the reasoning is completly analogous. This code is in java but you can easily extract the math from it:

```
public void incSpeed(float deltaX, float deltaY){
    //{upx,upy} is the up vector of your camera
    float angDifUp = - (float) (Math.PI/2.0) + MyMath.vector2dAngle(new float[]{upx,upy});
    float angDelta = MyMath.vector2dAngle(new float[]{deltaX,deltaY});
    //Norm of the delta vector
    float normDelta = MyMath.distance2d(new float[]{deltaX,deltaY}, new float[]{0,0});
    float newDelta[] = new float[]{normDelta*FloatMath.cos(angDelta+angDifUp),normDelta*FloatMath.sin(angDelta+angDifUp)};

    vx += newDelta[0];
    vy += newDelta[1];
}

```

Up vector: http://www.charglerode.com/blog/wp-content/uploads/2009/07/cameranav2.jpg

This works by manipulating the panning vector according to the rotation of the camera.

You might have to provide the negative of deltaX and/or deltaY to the method for it to work correctly depending on how you calculate the deltas.

You may also need to take the minus sign out of the angDifUp variable.

If I were you I'd try the 8 combinations of (+/-|+/-|+/-) if it doest work right away.

If you want I might add extra explanations later.

Good luck.

**Edit** I made a sketchy illustration explaining the reasioning:

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


# Question
Title: What's a good entity hierarchy for a 2D game?
I'm in the process of building a new 2D game out of some code I wrote a while ago.

The object hierarchy for entities is like this:

* `Scene` (e.g. `MainMenu`): Contains multiple entities and delegates `update()`/`draw()` to each
* `Entity`: Base class for all things in a scene (e.g. `MenuItem` or `Alien`)
* `Sprite`: Base class for all entities that just draw a texture, i.e. don't have their own drawing logic

Does it make sense to split up entities and sprites up like that? I think in a 2D game, the terms *entity* and *sprite* are somewhat synonymous, right?

But I do believe that I need some base class for entities that just draw a texture, as opposed to drawing themselves, to avoid duplication. Most entities are like that.

One weird case is my `Text` class: It derives from `Sprite`, which accepts either the path of an image or an already loaded texture in its constructor. `Text` loads a texture in its constructor and passes that to `Sprite`.

Can you outline a design that makes more sense? Or point me to a good object-oriented reference code base for a 2D game? I could only find 3D engine code bases of decent code quality, e.g. Doom 3 and HPL1Engine.

# Answer
In general, it's not a bad idea to separate the game mechanics from their visual representation. When you have a game logic which is completely oblivious to how it is displayed on the one hand, and a graphic engine which creates a visual presentation of the current game state but doesn't care about how this state is created on the other, your code will be much more flexible. You could, for example, easily create an alternative visual game state representation, like a minimap, overview map, or an entirely different perspective. You could even switch from a 2d engine to a 3d engine without even touching the game mechanics code. Your visual representations would be equally flexible. When your graphic engine is gameplay-agnostic, you can easily reuse it for a completely different game (just look at how many games make use of the Unreal engine - many of them are not even first person shooters).

So I wouldn't recommend to use Sprite as a base class.

Another reason is because there might be entities in your game scene which don't have a visual representation (event trigger areas, for example). Or you could have objects which have more than one sprite. In a 2d RPG project I took part in, we had characters with a nude base sprite and multiple cloth sprites which were layered over the base sprite. So each entity had 0..n sprites. I could also imagine other genres where it could make sense to have objects which are represented by multiple images blitted on top of each other.

How to build your object hierarchy is very application-specific and depends a lot on your gameplay. So it's hard to provide a definite guideline.
> 8 votes

# Answer
Generally you should prefer composition over inheritance where possible. In this example I would not have Sprite as a base class that game objects derive from. Whether to draw a sprite or not would just be a property of the Entity object. I might have Sprite and Text following a Drawable interface, and just associate them with Entities as appropriate.
> 3 votes

# Answer
Consider to use component-based game object system:
https://stackoverflow.com/questions/1901251/component-based-game-engine-design

It is very flexible and modern approach which is good for middle- and big-sized games.
> 2 votes

---
Tags: c++, 2d, scene, oop, entities
---


# Question
Title: How to store and update data table on client side (iOS MMO)
Currently I'm developing an iOS MMO game with cocos2d-x. The game depends on many data tables (Excel file) given by the designers. These tables contain data like how much gold/crystal will be cost when upgrade a building (barracks, laboratory, etc.). We have about 10 tables, each have about 50 rows of data.

My question is how to store those tables on client side and how to update them once they have been modified on server side?

My opinion: use SQLite to store data on client side, the server will parse the Excel files and send the data to client with JSON format, then the client parse the JSON string and save it to SQLite file.

Is there any better method? I find that some game stores CSV files on client side, how do they update the files? Could server send a whole file directly to client?

# Answer
You can just zip Sqlite db file on server, download it, then unpack with overwrite. No need for intermediate format like JSON as I see it.
> 2 votes

# Answer
When you have only ten tables of only 50 rows each, do you really need a relational database for that? When we estimate that each row will have about a kByte of data (which seems like a gross overestimate for the one use-case you described, but maybe you have others with more data), that wouldn't even be a single MB.

You are still very well in the area where you can store all that information in RAM while the game is running. I also think that incremental updates of these files (only update the rows which changed) wouldn't be worth the hassle. To update whole files, there are different approaches:

1. The checksum approach: Client and server calculate the checksum of each content file. The client sends a list of all files with their checksums to the server. When the server notices that checksums are incorrect or that files are missing, it resends the file. The nice thing is that when a file gets corrupted for some reason, it will be fixed automatically with the next update.
2. The versioning approach: Each of your content updates gets a version number. When the client connects to the server, it reports its latest content version number. When it's lower than the one on the server, the server sends new versions of all files which changed since that version. This is harder to develop (the server needs to track which files changed with each past update) and doesn't protect against broken updates, but it is much less CPU-intensive, because checksum calculation can be expensive when you have a lot of very large files.
> 1 votes

# Answer
If you send the data from server to client and store this data on the client, this data could be modified before sending the request to the server and that would result in cheating. I would do like this:

1. Client sends a build-House request to the server
2. Server checks if the player's resources are enough to build what the player wants
3. If the player has everything that is required, the building will be build and then the server will send a packed giving the required information to show this House on the screen
4. House is shown on the screen

I actually don't have any experience with MMOs, but that's the way I'd make what you want :)
> 0 votes

---
Tags: ios, mmo, databases, synchronization
---


title: Random World Generation

text:
# Question
Title: Random World Generation
> **Possible Duplicate:**
> How are voxel terrain engines made?

I'm making a game like minecraft (although a different idea) but I need a random world generator for a 1024 block wide and 256 block tall map. Basically so far I have a multidimensional array for each layer of blocks (a total of 262,114 blocks).

This is the code I have now:

```
Block[,] BlocksInMap = new Block[1024, 256];

public bool IsWorldGenerated = false;

Random r = new Random();

private void RunThread()
{
    for (int BH = 0; BH <= 256; BH++)
    {
        for (int BW = 0; BW <= 1024; BW++)
        {
            Block b = new Block();
            if (BH >= 192)
            {

            }
            BlocksInMap[BW, BH] = b;
        }
    }

    IsWorldGenerated = true;
}

public void GenWorld()
{
    new Thread(new ThreadStart(RunThread)).Start();
}

```

I want to make tunnels and water but the way blocks are set is like this:

```
Block MyBlock = new Block();
MyBlock.BlockType = Block.BlockTypes.Air;

```

How would I manage to connect blocks so the land is not a bunch of floating dirt and stone?

# Answer
> 12 votes
For a Minecraft-like world it will be tremendously beneficial to do some research on the topic of coherent noise. Such noise will form a heightmap for your terrain that will be connected and have actual transitions between heights. However, applying noise allows you to do more amazing things.

The most common type of noise used is probably Perlin noise and Simplex noise. There are a lot of things that can be done with these two alone, as demonstrated by the open source libary libnoise.

Refer to the following links for more info on how to apply coherent noise for terrain generation.

Minecraft like world generation. -- especially relevant.

More procedural voxel world generation -- Shows how to do material distribution with noise

libnoise tutorial -- Shows terrain generation but also explains the noise library libnoise

As for actual noise implementation I would recommend checking out:

Ken Perlin's reference implementation

Stefan Gustavson's article on Simplex noise including an implementation

Diamon Square algorithm

libnoise and its source code

If you base your generation algorithm on coherent noise the "roughness" of the terrain highly depends on your specification of the noise map's attributes. Within normal range, problems like having some tiles of the world floating about without any connection to the ground will not occur. Additionally, since coherent noise basically has no boundaries the scale of the world does not have any either. Increasing terrain size is therefore less of an issue.

# Answer
> 3 votes
Allow me to answer this for you, by searching the site for you:

How are voxel terrain engines made?

Random map generation

How is a 3d perlin noise function used to generate terrain?

Procedural terrains in 3D: what has been done ? Are there common algo and/or theories about it?

Voxel heightmap terrain editor

How to generate random level from a seed?

Random World Generator

How to generate caves that resemble those of Minecraft?

How to remove floating terrain when generated with 3D Perlin Noise?

Correct way to "randomly" generate flowing terrain

Simple noise generation

Huge procedurally generated 'wilderness' worlds

C# Perlin noise - generating “endless” terrain chunks?

How can I generate a terrain heightmap from the perlin algorithm?

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


# Question
Title: How much memory can i safely use on android?
To make my game more fluid, I try to prevent memory allocations during the game I am writing. To that end, I allocate a whopping 16MB of buffers on startup and then use those as I go along. When I check in Eclipse my game now uses 24MB in total, which does not change noticeably during the game.

This all works fine on the phone I have now (android 2.3, motorola defy) but I wonder if I'm going to run into problems with this on other phones or tablets that run android 2.2 or higher (which is what I'm aiming for)?

# Answer
> 1 votes
I found this : https://stackoverflow.com/questions/3590443

Apparently the memory limit seems to be device specific and often related to screen density. This seems to correspond to my test device : my motorola defy has a high-density screen so propably has a 24MB process limit or higher. If I want to support older android 2.2 devices with low density screens, I should reduce my memory usage to 16MB.

# Answer
> 1 votes
I do not think it has much to do with the android version you are running as well as de device specs you are aiming for. Most new tablets and phones have 512MB to 1Gb memory so even 24mb doesn't sound that much. It just a matter of choice, do you want to aim for high end devices or not.

---
Tags: android
---


# Question
Title: What are some methods which can be applied to make arcade-highscore games fun/interesting?
Consider an arcade game where you shoot falling objects and the goal is to beat the high-score.

What are some methods you can apply to such games to make the player feel it is fun and wants to play it again and again?

# Answer
> 7 votes
I'll try to answer this question in a way that it can be helpful for other games. Your game has a lot in common with arcade highscore games , so maybe you can grab some ideas from them:

**Combos:** Combos are a good way to keep the adrenaline of the player going up. Combos must increase the score proportionally to its difficulty. It is nice if they trigger rare special game mechanics and visual/sound effects to keep the player interested in what happens if he can do the next difficulty level combo. Street fighter and fruit ninja (blitz) are good examples. This could be done in your game by hitting multiple hearts with the same arrow or in a small amount of time.

**Increasing difficulty:** In your game it seems possible that if a player has enough skill, he can keep playing forever. You can increase the hearts/arrow bags speed in your game as the score goes up (this has already been mentioned). Good examples of this mechanic are tetris and puzzle bubble.

**Random good/bad luck prizes:** In fruit ninja arcade, there are bananas and bombs. In puzzle bubble there are special bubbles. In your game there could be special hearts that would award the player with a good or bad bonus of some kind.

More specific ones:

* Hearts of different sizes so the game visual doesn't feel too repetitive.
* In the combos/bonus hearts you could temporarily create extra bows that would mimic the bow the player controls. This would result in the player throwing more then one arrow at a time.
* There could be wind which would cause hearts not to fall completly vertically.
* Have new bows/arrows with different properties to be unlocked as the player beats certain scores.

The general advice is to be creative and keep in mind that in these kind of games you can use the player curiosity, adrenaline and persistence to keep him playing the game.

# Answer
> 2 votes
Try adding various game modes.

**Bird Hunting**: A bird (or multiple birds/any target you want) fly horizontally across the screen at different heights.

**Target**: A standard circular target bounces around the screen. Points are based on proximity to center. To keep it from just registering a hit at the bottom of the target, you could have a thin hitbox laid over the center. The target could move faster as the score goes up. This mode would typically have a finite number of shots.

**Time Attack**: Any game mode you feel like implementing, but with infinite ammo in a limited time. Possibly add a time penalty for missing (timer loses a few seconds, or can't shoot for a short time).

**Point Multipliers**: Consecutive hits gain more points than normal, while missing resets back to standard scoring.

---
Tags: game-mechanics
---


# Question
Title: Can I randomly generate an endless road?
So suppose we stand on a position(x0, y0) of a map. We can only move on the horizontal plane(no jump and stuff) but we can move forward, left, or right (in a discrete math way, i.e. integer movement).

As soon as we move to the next position(x1, y1), everything around us is generated randomly by a program. We could be surrounded by one of mountain, lake, and road. We can only move on the road. The road is always 2D as the map itself.

My question is, are we able to play this game endlessly? "End" means that we come across a dead end and the only way out is to go backward.

# Answer
Perhaps I'm not understanding your question, but this is really not a math question at all.

The answer is yes, we could go on "forever" if the algorithm for generating the road allows it. It depends entirely on the how the random generation occurs. The algorithm for randomly generating the road and landscape can easily be tailored to never end.

If the selection of mountain, lake and road was truly random each time. There is a high likelihood that you would eventually turn back on your path. So it would depend on how you define handling that situation. If you're allowed to overwrite the previous tiles then you wouldn't have a problem. However, if you're not allowed to overwrite tiles then eventually the path would end. It would loop back on itself and you would be forced to stop.
> 3 votes

---
Tags: procedural-generation, random
---


# Question
Title: How can I implement smooth rotation from one direction to another?
I'm having a problem with animating rotations with 1`Matrix.CreateRotationY()` with my basic 3D game. Based on where you click the mouse, I want the 3D object to rotate to that direction and then move.

I am using this to determine the target direction:

```
float rot = (float)(Math.Atan2(X, Z));

```

It gives me the correct value, but I am not sure how to handle the rotation animation from current direction to new direction. I've tried a few things, but to no avail.

Do you guys know of any good ways of solving this issue?

# Answer
If I read you correctly, you need some way of animating between the pointing at current angle to pointing at a target angle. I was severely tempted to resort to vectors and dot products to solve this more elegantly, but as the questioner phrased the problem in terms of angles, I figured the solution had better be in terms of angles too.

The (simpler) vector approach is outlined in this answer to a similar question

Most of the code is figuring out whether to move the current angle clockwise(decreasing) or anti-clockwise (increasing). We need to figure out which direction is the shortest route to arrive at targetAngle. This is a simple check, except for the case where both angles are on opposite sides of the x-axis. The question becomes, whether it is shorter to move towards the positive-x-axis or negative-x-axis?

In the code below, making angleInc bigger or smaller will make the animation quicker or slower;

```
float currentRot; //current angle (direction) of entity
float targetRot; // angle entity SHOULD be at
float angInc=MathHelper.Pi/100.0f; //how much we should turn each frame (adjusts speed of animation)

public void Update(){

//first need to make sure that both angles are in the range -pi to +pi
//if they are outside the range, adjust them accordingly
if(currentRot>MathHelper.Pi) currentRot-=MathHelper.TwoPi;
if(targetRot>MathHelper.Pi) targetRot-=MathHelper.TwoPi;
if(currentRot<-MathHelper.Pi) currentRot=MathHelper.TwoPi-currentRot;
if(targetRot<-MathHelper.Pi) targetRot=MathHelper.TwoPi-targetRot;

//next figure out which direction we should be changing currentAngle
bool increasingAngle=false;  this will be true if currentAngles needs to get bigger and vis-versa

//four cases to consider
//both angles are positive
if(currentAngle>=0 && targetAngle>=0){
    if(currentAngle<targetAngle)
        increasingAngle=true;
}
//both angles are negative
else if(currentAngle<0 && targetAngle<0){
    if(currentAngle<targetAngle)
        increasingAngle=true;
}
//both angles are on opposite sides of the x-axis
else{
    if(Math.Abs(currentAngle-targetAngle)<MathHelper.Pi){// shorter to go via zero
        if(currentAngle<0)
            increasingAngle=true;
     }
    else{ // need to go via ±pi
        if(currentAngle >0)
            increasingAngle=true;

if(Math.Abs(currentRot-targetRot)< angleInc){// we've (almost) reached our target angle
    currentRot=targetRot; //in case we are not *exactly* at the target angle
}
else{ //need to move currentAngle towards targetAngle
      //direction to move has been calculated  in the previous section
    if(increasingAngle==true)
        currentRot+=angInc;
    else
        currentRot-=angInc;

}

enityRotationMatrix=Matrix.CreateRotationY(currentRot);
}

```

}

**EDIT** fixed bugs mentioned in comments below
> 5 votes

# Answer
I wrote a lerp function for angles a while back.

```
private float AngleLerp(float nowrap, float wraps, float lerp) {

    float c, d;

    if (wraps < nowrap) {
        c = wraps + MathHelper.TwoPi;
        //c > nowrap > wraps
        d = c - nowrap > nowrap - wraps
            ? MathHelper.Lerp(nowrap, wraps, lerp)
            : MathHelper.Lerp(nowrap, c, lerp);

    } else if (wraps > nowrap) {
        c = wraps - MathHelper.TwoPi;
        //wraps > nowrap > c
        d = wraps - nowrap > nowrap - c
            ? MathHelper.Lerp(nowrap, c, lerp)
            : MathHelper.Lerp(nowrap, wraps, lerp);

    } else { return nowrap; } //Same angle already

    return MathHelper.WrapAngle(d);
}

```
> 0 votes

---
Tags: c#, xna-4.0, matrix, rotation
---


title: How do I detect ledges?

text:
# Question
Title: How do I detect ledges?
In my game, I'd like my character to be able to grab and hold onto ledges, and to be able to pull themselves up if there's room to do so.

How do I detect if there's a ledge, and if the character has enough space to climb up?

# Answer
The video for Overgrowth Alpha 132 shows how they implemented ledge climbing.

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

Their ledge detection involves two parts:

### Wall detection (using the sphere)

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

### Ledge detection (using the cylinder)

If the player's contacting a wall, a cylinder is swept downwards from a certain distance above the player's position until it touches a ledge. That certain distance is the maximum reach height of the player: if the character can reach a ledge at most 1 meter above their position, the sweep starts at that height. This determines three things:

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

(You also need to determine there's nothing in the way between the ledge and the player, such as a hard floor or ceiling above them.)
> 23 votes

---
Tags: physics
---


# Question
Title: Which is the way to pass parameters in a drawableGameComponent in XNA 4.0?
I have a small demo and I want to create a class that draws messages in screen like fps rate. I am reading a XNA book and they comment about GameComponents. I have created a class that inherits DrawableGameComponent

```
public class ScreenMessagesComponent : Microsoft.Xna.Framework.DrawableGameComponent

```

I override some methods like Initialize or LoadContent. But when I want to override draw I have a problem, I would like to pass some parameters to it.

Overrided method does not allow me to pass parameters.

```
        public override void Draw(GameTime gameTime)
        {
            StringBuilder buffer = new StringBuilder();

            buffer.AppendFormat("FPS: {0}\n", framesPerSecond); // Where get framesPerSecond from???

            spriteBatch.DrawString(spriteFont, buffer.ToString(), fontPos, Color.Yellow);
            base.Draw(gameTime);
        }

```

If I create a method with parameters, then I cannot override it and will not be automatically called:

```
        public void Draw(SpriteBatch spriteBatch, int framesPerSecond)
        {
            StringBuilder buffer = new StringBuilder();

            buffer.AppendFormat("FPS: {0}\n", framesPerSecond);
            spriteBatch.DrawString(spriteFont, buffer.ToString(), fontPos, Color.Yellow);
            base.Draw(gameTime);
        }

```

So my questions are:

* Is there a mechanism to pass parameter to a drawableGameComponent? What is the best practice?
* In general is a good practice to use GameComponents?

# Answer
Give your DrawableGameComponent some properties e.g. framesPerSecond, which you set before calling Draw(GameTime). This might only be appropriate if the property is a 'natural' part of the Component.

The other alternative is to use the game service mechanism. Game services are a mechanism for maintaining loose coupling between objects that need to interact with each other. Add a service class to the game service container;

```
  //this is usually in the Game.Initialize()
  Services.AddService(typeof(ContentManager), Content);
  Services.AddService(typeof(Camera), camera);

```

The DrawableGameCompontent object can then access that service object through the service provider;

```
//DrawableGameComponent method
public void Draw(GameTime gt)
    {
        Camera camera = (Camera)Game.Services.GetService(typeof(Camera));
        foreach (ModelMesh mesh in invaderModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                //Effect Settings Goes here
                effect.LightingEnabled = true;
                effect.EnableDefaultLighting();
                effect.World = world;
                effect.Projection = camera.Proj;
                effect.View = camera.View;
            }
            mesh.Draw();
        }

    }

```

This question has an interesting discussion on the pros and cons of using GameComponents.
> 3 votes

# Answer
There are mainly two ways:

1. As Luis Estrada says, add logic to count Update- and Draw-Calls (this numbers might differ) to the component. If no other component needs this properties, this might be the best way.
2. If other components also need to know about the current frame-rate, it might be a good way to implement a GameService that is responsible for this. In each DrawCall to your ScreenMessagesComponent access the Service and draw the values to the screen.

Have a look at this for calculating frame-rates: Calculating frames per second in a game
> 1 votes

# Answer
I have answered a very similar question to this over on Stack Overflow. To summarise:

The best way to pass an argument into a game component's method is to **pass an argument in!** Unfortunately this precludes the use of `GameComponent` \- because its interface is fixed. It's a fairly weak API for this reason.

It's best to treat `GameComponent` as an *example* of how you can set up a "game component" or "actor" system in your game. Like many other parts of XNA (sprite fonts, models, the `Game` class itself, etc) - you're able to and encouraged to replace it if you need functionality that it does not provide.

Although it sounds like you don't really need an actor or component system here at all. I imagine each "component" you have will need different data passed in? Simply create a class with a `Draw` method? Take a look at this answer.

---

But, if you must use `GameComponent`, then perhaps the next-best method is to set member properties or fields on the `GameComponent` before their `Draw` and/or `Update` methods get called (they get called in `Game.Draw` and `Game.Update` \- so where you call `base.Draw` and `base.Update` in your own game class).

(You could use another method, though. Just do the simplest thing that could possibly work.)
> 1 votes

# Answer
The problem is that something like `GameComponent` has a fixed interface; you can't pass it in as an argument. Thus, what you can do is create a new item that acts as a `Service` in your main game class. Then, just add it to your game's services and try to get it when you need to draw it.

So, at the start of your game (constructor or `Initialize` method, whatever works) you can do:

```
DebugInformer informer = new DebugInformer();
Services.AddService(typeof(DebugInformer), informer);

```

`DebugInformer` is a class of your own design. Give it properties that work for you like `FramesPerSecond`. You can add other things you want that are specific to your game, such as `ItemsOnGround` and whatever else suits your fancy. Later in the code, you can get the properties out and use them like so:

```
//In the middle of your specific Component's draw call:
DebugInformer informer = Game.Services.GetService(typeof(DebugInformer)) as DebugInformer;
if (informer != null) {
    // Informer is present, use informer.FramesPerSecond and other stuff
}

```

Services were designed just for problems like this, so don't feel afraid to use it.

Good luck!
> 1 votes

---
Tags: xna, xna-4.0, game-component
---


title: Why is this 8 puzzle unsolvable?

text:
# Question
Title: Why is this 8 puzzle unsolvable?
I am developing a 8 puzzle game. I went through the rules in this (see **Detecting Unsolvable Puzzles**) link, which tell you how to detect if an initial state is unsolvable. It says that if the number of **inversions** is odd, then the goal state *cannot* be reached and if even the goal state *can* be reached.

An **inversion** is defined as follows:

> Given a board, an inversion is any pair of blocks i and j where i \< j but i appears after j when considering the board in row-major order (row 0, followed by row 1, and so forth).

There is a 8-puzzle solver (applet) here. Choose 8-puzzle from the options.

```
1,0,3,2,4,5,6,7,8

```

and

```
7,0,2,8,5,3,6,4,1

```

As you can see both of them contain an even number of inversions. Still the program says that the puzzle is unsolvable. So is the `Princeton` link wrong?

# Answer
The sequence 1,0,3,2,4,5,6,7,8 only has one inversion:

```
 1. 3,2

```

1 is odd, therefore this configuration is unsolvable.

Similarly, in 7,0,2,8,5,3,6,4,1:

```
 1. 7,2
 2. 7,5
 3. 7,3
 4. 7,6
 5. 7,4
 6. 7,1
 7. 2,1
 8. 8,5
 9. 8,3
 10. 8,6
 11. 8,4
 12. 8,1
 13. 5,3
 14. 5,4
 15. 5,1
 16. 3,1
 17. 6,4
 18. 6,1
 19. 4,1

```

Nineteen inversions is odd. Hence, unsolvable.

I think your mistake is that you're counting the "0" as if it was a tile, when you're working out the number of inversions. But if you check the instructions in the article you linked, it isn't considering the blank space at all.
> 11 votes

---
Tags: puzzle
---


title: Jumping Logic Issues

text:
# Question
Title: Jumping Logic Issues
> **Possible Duplicate:**
> How to make a character jump?

I have been working on a 2D platformer and am trying to implement jumping. At the moment I have it simply teleporting upward and then falling back down:

```
if(Keyboard.GetState().IsKeyDown(Keys.Space) && !jumping) _position2D.Y -= 64f;

```

Is there any way to smooth it out and make it more parabolic?

# Answer
Some variables:

```
    Vector2 velocity;
    Vector2 fallSpeed;

    // Init
    velocity = Vector.Zero;
    fallSpeed = new Vector(0, 20)  // This is our pseudo-gravity

    // Time is needed
    var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

    velocity = new Vector2(0, velocity.Y); // Keep our change in the Y-axis from previous Updates.

    if (Keyboard.GetState().IsKeyDown(Keys.Space) && !jumping)
    {
        jumping = true; // So we don't jump again til ready.

        velocity.Y = -500; // break through our pseudo-gravity coming up.
    }

    if (jumping)
        velocity += fallspeed;  // not blocking this off will make you entity continue to drift down after he has landed.

    var moveAmount = velocity * elapsed; // store how much we moved in this given time period

    position = position + moveAmount;

```

//Assuming you have no other collision logic we need a way to tell our guy he is no longer in the state of jumping and can jump again.

```
    if (position.Y >= 300)
    {
        jumping = false;

        velocity.Y = 0;
    }

```

Tweak jump strength and fallSpeed to you liking
> 2 votes

# Answer
I would think the logic should be a loop up to the peek jump point like so:

```
if(Keyboard.GetState().IsKeyDown(Keys.Space) && !jumping) {
    float peek = 64f;
    while(_position2D.Y != peek) { _position2D.Y += 1; }
}

```

Personally, and this is just me, I would move the variable peek out to a more publicly accessible point so that it can be easily edited/referenced. That is just me though.

\[**edit**\] As pointed out in the comments, this might seem like good logic at first glance, but is made of fail in practice, for the reasons attached to the comments. I'm leaving this here for those wanting to learn from my uber mistake =D
> 0 votes

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


# Question
Title: How do I protect sending scores from HTML5 games to my server
On backend I am using java. I have a game in HTML5; when user completes it I sends an Ajax call to save the score to database. Now, someone can easily use tools like Fiddler and firebug to modify this ajax request and send a much better score to the server. How do I make sure that user cannot manipulate scores !

# Answer
> 18 votes
Don't just send an integer score to the server. Send a collection of game stats that can be used to verify the score was realistic. Or you can implement some pre-shared key for calculating the score. You could send incremental scores and stats throughout the game and ensure that the increase is reasonable.

However, I wouldn't worry too much about it. The suggestions above will make it more difficult, but not impossible to send a fake score. However, if you just make it slightly difficult a vast majority of people that play your game will not be interested in trying to cheat it.

Do be careful about how you're allowing your game to communicate with your server. You don't want your game to be an entry point into your server for hacking. Make sure you always validate your input and never trust the client.

# Answer
> 11 votes
As Byte56 said: "never trust the client", but:

Never trusting the client comes at a price:
Having all games being played on the server will increase your infrastructure cost a lot.

Assuming most of the players won't cheat
and the top highscore will settle after a little time and stop changing a lot

there is a middle way.

**Record the games** (on the client).
(Depending on the game type that might be super easy (e.g. chess) or a little complicated (e.g. a multiplayer FPS),
but it's always doable.)

When a player finishes a game just submit the score.
If the score is within a certain range at the top (e.g. top 1% or top 5)
request the recorded data from the player
and replay that game on the server.
If the scores match, accept the score.

This way you don't need any additional server side resources for most of the plays,
but can ensure the top scores are valid.

# Answer
> 5 votes
Reduce social motivation to cheat by e.g. using social leaderboards (cheating only makes you look good to a handful of friends, it doesn't spoil it for everyone).

Verify on server. Joel Poloney had a good write-up of techniques in Game Developer 2012 September "Scale Your Online Game"

# Answer
> 4 votes
Do not worry about it; protecting from all attacks is essentially impossible if you trust the client. If nobody uses Fiddler etc, to modify the AJAX request, they can simply fire up a JS debugger and modify your game data to give themselves 1000 lives, etc, or modify your code, or do 100 other things you haven't thought of.

I wrote such a game several years ago, and to the best of my knowledge, nobody cheated in this way. There was no prize, except having your name on the score table.

# Answer
> 2 votes
When you want to create a cheat-proof online game, you need to handle all game logic on the server. Everything that happens on the client-side can be controlled and manipulated by the user. There are techniques like encryption or obfuscation you can try, but in the end it's all just security through obscurity which can be circumvented by someone who is sufficiently determined.

Sure, a game which runs on the server is a lot more complicated to develop, requires a lot more resources server-sided and network latency is detrimental to the game experience (especially for fast-paced games), but it's the only way to effectively prevent the players from cheating.

---
Tags: javascript, html5, security
---