# Question
Title: How can I draw an arrow at the edge of the screen pointing to an object that is off screen?
I am wishing to do what is described in this topic:

http://www.allegro.cc/forums/print-thread/283220

I have attempted a variety of the methods mentioned here.

First I tried to use the method described by Carrus85:

> Just take the ratio of the two triangle hypontenuses (doesn't matter which triagle you use for the other, I suggest point 1 and point 2 as the distance you calculate). This will give you the aspect ratio percentage of the triangle in the corner from the larger triangle. Then you simply multiply deltax by that value to get the x-coordinate offset, and deltay by that value to get the y-coordinate offset.

But I could not find a way to calculate how far the object is away from the edge of the screen.

I then tried using ray casting (which I have never done before) suggested by 23yrold3yrold:

> Fire a ray from the center of the screen to the offscreen object. Calculate where on the rectangle the ray intersects. There's your coordinates.

I first calculated the hypotenuse of the triangle formed by the difference in x and y positions of the two points. I used this to create a unit vector along that line. I looped through that vector until either the x coordinate or the y coordinate was off the screen. The two current x and y values then form the x and y of the arrow.

Here is the code for my ray casting method (written in C++ and Allegro 5)

```
void renderArrows(Object* i)
{
    float x1 = i->getX() + (i->getWidth() / 2);
    float y1 = i->getY() + (i->getHeight() / 2);

    float x2 = screenCentreX;
    float y2 = ScreenCentreY;

    float dx = x2 - x1;
    float dy = y2 - y1;
    float hypotSquared = (dx * dx) + (dy * dy);
    float hypot = sqrt(hypotSquared);

    float unitX = dx / hypot;
    float unitY = dy / hypot;

    float rayX = x2 - view->getViewportX();
    float rayY = y2 - view->getViewportY();
    float arrowX = 0;
    float arrowY = 0;

    bool posFound = false;
    while(posFound == false)
    {
        rayX += unitX;
        rayY += unitY;

        if(rayX <= 0 ||
            rayX >= screenWidth ||
            rayY <= 0 ||
            rayY >= screenHeight)
        {
            arrowX = rayX;
            arrowY = rayY;
            posFound = true;
        }
    }

    al_draw_bitmap(sprite, arrowX - spriteWidth, arrowY - spriteHeight, 0);
}

```

This was relatively successful. Arrows are displayed in the bottom right section of the screen when objects are located above and left of the screen as if the locations of the where the arrows are drawn have been rotated 180 degrees around the center of the screen.

I assumed this was due to the fact that when I was calculating the hypotenuse of the triangle, it would always be positive regardless of whether or not the difference in x or difference in y is negative.

Thinking about it, ray casting does not seem like a good way of solving the problem (due to the fact that it involves using sqrt() and a large for loop).

# Answer
So you have two coordinates or vectors, one is the center of the screen (C from now on) and the other is your object (P from now on.)

If you know some math, you might know that a line can be expressed as an origin and a direction vector. The origin is your screen-center, while the direction vector can be found subtracting C from P. This equation can also be expressed in parametric form, which is essentially the same:

```
x = (P.x - C.x)t + C.x;
y = (P.y - C.y)t + C.y;

```

See the `(P.? - C.?)` bit? That's your direction vector (as I said, subtract C from P). The last `C.?` bit is the origin of the line.

`t` is a variable which can vary from `0` to `1`, `0` being the origin of the vector (if you operate, `x` and `y` woulld become `C.x` and `C.y`), `1` being your object coordinate (again, operating, it'd become `P.x` and `P.y`, or the "end" of the vector, if you wish) and values in between interpolating between both ends of your segment. You can also assign outer values: below `0` you'll get your vector direction reversed and above `1` you'll "extend" your vector further in the same direction.

Once you get this, it gets pretty easy. Your objective is to find the point of this vector (`x` and `y` for a given value of `t`) where `X=WIDTH` or `Y=HEIGHT`, whatever comes first. As you can see, `t` is your only variable here:

```
(0)
WIDTH = (P.x - C.x)t + C.x;
and
HEIGHT = (P.y - C.y)t + C.y;

```

Or re-expressing it:

```
(1)
t = (WIDTH - C.x)/(P.x - C.x)
and
t = (HEIGHT - C.y)/(P.y - C.y)

```

This will get the cutting point of the line defined by your vector on your right and top borders. The same goes for the left and bottom borders of your screen, where you need to check against `0` for both cases, not `WIDTH` and `HEIGHT`.

Since it will eventually cut the borders, even off-screen, the lowest `t` value will be your first point of contact. Reversing the operation and applying your found `t` value on the equations at `(0)` (the same value for both!) will bring a new `(x,y)`, which will be your cutting coordinates.

There might be some math errors or implementation differences for your problem, but that's the basic idea. I left some parts out too (there are always **four** cases of cutting, and you need just one) but a bit of thought will get you to a final solution :)
> 6 votes

---
Tags: c++, screen, raycasting, allegro, trigonometry
---


title: Pixel Collision - Detecting corners

text:
# Question
Title: Pixel Collision - Detecting corners
How would I go about detecting the corners of a texture when I use pixel collision detection? I read about corner collision with rectangles, but I am unsure how to adapt it to my situation.

Right now my map is tile based and I do rectangular collision until the player is intersecting with a blocked tile, then I switch to pixel collision.

The effect I would like to achieve is when the player hits the corner of an object to push him around the side so he doesn't just hit the edge and stop.

Any ideas?

# Answer
You should check several pixels ahead your sprite.

A exhaustive article about it (in Sonic games) is located here: http://info.sonicretro.org/Sonic\_Physics\_Guide?v=0
> 1 votes

---
Tags: xna, 2d, collision-detection
---


title: 2D Particle Explosion

text:
# Question
Title: 2D Particle Explosion
I'm developing a 2D action game, and in said game I've given my primary character an ability he can use to throw a fireball. I'm trying to design an effect so that when said fireball collides (be it with terrain or with an enemy) that the fireball will explode. For the explosion effect I've created a particle that once placed into game space will follow random, yet autonomic behavior based on random variables.

Here is my question: When I generate my explosion (essentially 90 of these particles) I get one of two behaviors,

1) They are all generated with the same random variables, and don't resemble an explosion at all, more like a large mass of clumped sprites that all follow the same randomly generated path.

2) If I assign each particle a unique seed to its random number generator, they are a little bit -more- spread out, yet clumping is still visible (they seem to fork out into 3 different directions)

Does anybody have any tips for producing particle-based 2D explosions? I'll include the code for my particle and the event I'm generating them in.

Fire particle class:

```
    public FireParticle(xTile.Dimensions.Location StartLocation, ContentManager content)
    {
        worldLocation = StartLocation;
        fireParticleAnimation = new FireParticleAnimation(content);
        random = new Random();

        int rightorleft = random.Next(0, 3);
        int upordown = random.Next(1, 3);
        int xVelocity = random.Next(0, 101);
        int yVelocity = random.Next(0, 101);
        Vector2 tempVector2 = new Vector2(0,0);

        if (rightorleft == 1)
        {
            tempVector2 = new Vector2(xVelocity, tempVector2.Y);
        }

        else if (rightorleft == 2)
        {
            tempVector2 = new Vector2(-xVelocity, tempVector2.Y);
        }

        if (upordown == 1)
        {
            tempVector2 = new Vector2(tempVector2.X, -yVelocity);
        }

        else if (upordown == 2)
        {
            tempVector2 = new Vector2(tempVector2.X, yVelocity);
        }

        velocity = tempVector2;
        scale = random.Next(1, 11);
        upwardForce = -10;
        dead = false;
    }

    public FireParticle(xTile.Dimensions.Location StartLocation, ContentManager content, int seed)
    {
        worldLocation = StartLocation;
        fireParticleAnimation = new FireParticleAnimation(content);
        random = new Random(seed);

        int rightorleft = random.Next(0, 3);
        int upordown = random.Next(1, 3);
        int xVelocity = random.Next(0, 101);
        int yVelocity = random.Next(0, 101);
        Vector2 tempVector2 = new Vector2(0, 0);

        if (rightorleft == 1)
        {
            tempVector2 = new Vector2(xVelocity, tempVector2.Y);
        }

        else if (rightorleft == 2)
        {
            tempVector2 = new Vector2(-xVelocity, tempVector2.Y);
        }

        if (upordown == 1)
        {
            tempVector2 = new Vector2(tempVector2.X, -yVelocity);
        }

        else if (upordown == 2)
        {
            tempVector2 = new Vector2(tempVector2.X, yVelocity);
        }

        velocity = tempVector2;
        scale = random.Next(1, 11);
        upwardForce = -10;
        dead = false;
    }

    #endregion

    #region Update and Draw

    public void Update(GameTime gameTime)
    {
        elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        fireParticleAnimation.Update(gameTime);

        Vector2 moveAmount = velocity * elapsed;

        xTile.Dimensions.Location newPosition = new xTile.Dimensions.Location(worldLocation.X + (int)moveAmount.X, worldLocation.Y + (int)moveAmount.Y);

        worldLocation = newPosition;

        velocity.Y += upwardForce;

        if (fireParticleAnimation.finishedPlaying)
        {
            dead = true;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(
            fireParticleAnimation.image.Image,
            new Rectangle((int)drawLocation.X, (int)drawLocation.Y, scale, scale),
            fireParticleAnimation.image.SizeAndsource,
            Color.White * fireParticleAnimation.image.Alpha);
    }

```

Fireball explosion event:

```
    public override void Update(GameTime gameTime)
    {
        if (enabled)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            foreach (Heart_of_Fire.World_Objects.Particles.FireParticle particle in explosionParticles.ToList())
            {
                particle.Update(gameTime);

                if (particle.Dead)
                {
                    explosionParticles.Remove(particle);
                }
            }

            collisionRectangle = new Microsoft.Xna.Framework.Rectangle((int)wrldPstn.X, (int)wrldPstn.Y, 5, 5);

            explosionCheck = exploded;

            if (!exploded)
            {
                coreGraphic.Update(gameTime);
                tailGraphic.Update(gameTime);

                Vector2 moveAmount = velocity * elapsed;

                moveAmount = horizontalCollision(moveAmount, layer);
                moveAmount = verticalCollision(moveAmount, layer);

                Vector2 newPosition = new Vector2(wrldPstn.X + moveAmount.X, wrldPstn.Y + moveAmount.Y);

                if (hasCollidedHorizontally || hasCollidedVertically)
                {
                    exploded = true;
                }

                wrldPstn = newPosition;
                worldLocation = new xTile.Dimensions.Location((int)wrldPstn.X, (int)wrldPstn.Y);
            }

            if (explosionCheck != exploded)
            {
                for (int i = 0; i < 90; i++)
                {
                    explosionParticles.Add(new World_Objects.Particles.FireParticle(
                        new Location(
                            collisionRectangle.X + random.Next(0, 6),
                            collisionRectangle.Y + random.Next(0, 6)),
                            contentMgr));
                }
            }

            if (exploded && explosionParticles.Count() == 0)
            {
                //enabled = false;
            }
        }
    }

```

# Answer
> 6 votes
Judging by your description of the problem, and from the following code, I bet you are storing the location of the particles as integers.

```
Vector2 moveAmount = velocity * elapsed;

xTile.Dimensions.Location newPosition = new xTile.Dimensions.Location(worldLocation.X + (int)moveAmount.X, worldLocation.Y + (int)moveAmount.Y);

```

If you change the position to be a Vector2 or floats, I believe your problem will go away.

# Answer
> 0 votes
```
int rightorleft = random.Next(0, 3);
int upordown = random.Next(1, 3);

if (rightorleft == 1)
else if (rightorleft == 2)
if (upordown == 1)
else if (upordown == 2)

```

I am not sure if this is everything, but I do note that Right or Left have 0,3 as their range while up or down has 1,3.. both of them only do something on 1 or 2 however. Was this done on purpose to get some of the particles to not move? It may explain the clumping you are seeing.

---
Tags: xna, 2d, xna-4.0
---


title: File format for animated scene

text:
# Question
Title: File format for animated scene
I've got a custom OpenGL based rendering engine and I'd like to add support for cinema-type scene animation. The artist that is helping me uses primarily 3DSMax. I'd like a file format for exporting and importing this data. I'm also in need of a file format for skeletal animation data, which may have an impact here.

I've been looking at MAXScript to manually export this stuff, which would buy me the most flexibility, but I have virtually no experience with 3DSMax itself, so I get a little lost when it comes to terminology.

So I'd like to know what file formats exist for animated scene data, and whether they are appropriate for my use (my fear is that they will be *way* too broad for my fairly simple needs.)

The way I view animated scene data is basically a bunch of references to \[animated\] models with keyframe-based matrices describing their orientation over time. And probably some special camera stuff to handle perspective. I might also want some event type stuff for adding/removing objects. Is this a sane concept?

# Answer
> 1 votes
One file format that might work is the ASE file format:

http://wiki.beyondunreal.com/Legacy:ASE\_File\_Format

It seems to conform to (and validate) my theoretical scene concept I described in my question. It's also a plaintext format, which should make importing straightforward. It's well supported by 3DSMax, and from the looks of it other modeling programs.

The only problem I have with it is that includes mesh data, which doesn't fit my needs. I have meshes that will be shared between many scenes, and used independently in gameplay, so it's important that the scene file *reference* the data instead of including it. Any suggestions?

---
Tags: opengl, animation, 3dsmax, file-format
---


title: Loading a series of PNGs as a texture

text:
# Question
Title: Loading a series of PNGs as a texture
If I have a series of PNGs that I'd like to use as a single animated texture, would I be able to use them as they are, or would I first need to convert them to a different format, like a single TGA?

# Answer
There are programs helping you in this task. I personally use Zwoptex. Basically you load all your pngs, it arranges them (translating and rotating each sprite) into a bigger image (you decide the size) called texture atlas. You can then export the atlas with a xml file containing the coordinates of each single sprite in the atlas.
> 5 votes

---
Tags: xna, textures
---


# Question
Title: How can I generate signed distance fields (2D) in real time, fast?
In a previous question, it was suggested that signed distance fields can be precomputed, loaded at runtime and then used from there.

For reasons I will explain at the end of this question (for people interested), I need to create the distance fields in real time.

There are some papers out there for different methods which are supposed to be viable in real-time environments, such as methods for Chamfer distance transforms and Voronoi diagram-approximation based transforms (as suggested in this presentation by the Pixeljunk Shooter dev guy), but I (and thus can be assumed a lot of other people) have a very hard time actually putting them to use, since they're usually long, largely bloated with math and not very algorithmic in their explanation.

What algorithm would you suggest for creating the distance fields in real-time (favourably on the GPU) especially considering the resulting quality of the distance fields?

Since I'm looking for an actual explanation/tutorial as opposed to a link to just another paper or slide, this question will receive a bounty once it's eligible for one :-).

Here's why I need to do it in real time:

> If you have to precompute these SDFs for large 2D environments (think of a large Terraria-like map), this would mean that you're accepting a rather large overhead in storage space (and map-generation time) in favour of implementing a more complicated algorithm that is fast enough for real time SDF generation.
>
> For example, a relatively small map with 1000\*256 (width\*height) with a tile size of 10\*10 pixels and thus total dimensions of 10000\*2560 pixels would already cost you around 2 megabytes of size, if you choose a relatively small SDF resolution of 128x128, assuming that you're storing only the distance values from 0 to 255.
>
> Obviously, this can quickly become too much and is an overhead that I don't want to have.

There's something else:

> SDFs can be used for many things (like collision detection), and some useful applications are potentially not even discovered yet. I think a lot of people are going to look for these things in the future, and if we get a comprehensive answer in here, I think we're going to help a lot of people.

# Answer
Catalin Zima explains how to achieve dynamic 2D shadows in his article \- and he does use a signed distance field (from what I can tell that is just a fancy name for a shadow buffer in this context). His method does need a GPU, and his implementation as-is isn't the best (his dropped below 60Hz at about 20 lights on my machine, mine got about 500 lights); which is to be expected as he has favoured clarity of code over speed.

**Implementation**

Exactly as implemented by him:

1. Render all shadow casters into a texture.
2. Calculate the distance to the centre of the light for each pixel, and assign that value to the RGB of opaque pixels.
3. Distort the image so that it represents how a 3D camera would have seen those pixels.
4. Squash the image into a 2xN sized image using the unusual resize described in his article (a plain resize won't work).
5. The 2xN image is now your signed distance field for all four quadrants of the light (remember that one quadrant is basically a single camera frustum at 90 degrees).
6. Render the lightmap.
7. Blur the lightmap (based on the distance from the light) so that you get soft shadows.

My final implementation was (each step being a single shader):

1. Do (1).
2. Do (2) and (3).
3. Do (4). His implementation is really slow: if you can try and use GPGPU for this. I couldn't use GPGPU (XNA) so what I did was:
    * Set up a mesh where the first N/2 columns were represents by N/2 quads with the EXACT same position (covering the first column of the final buffer) but differing texture co-ordinates (same thing for the second N/2 columns)
    * Turn off depth-testing on the GPU.
    * Use the MIN pixel blending function.
4. Do (6) and (7).

It's quite ingenious: it's basically a direct translation of how shadows are handled in 3D into 2D.

**Pitfalls**

The main pitfall is that some objects shouldn't be shadowed: in my example I was writing a Liero (real-time worms) clone and hence didn't want, for example, the players' worms to be shadowed (at least the one on each player's screen). All I did for these 'special' objects was redraw them as a last step. The irony was that most objects were not shadowed (worms, landscape foreground) so there is an overdraw issue here.
> 9 votes

---
Tags: 2d, signed-distance-field
---


# Question
Title: Box2D platformer movement. Should i mess with velocity?
I have a platformer game in which I implemented the movement using a wheel attached to the hero. For jumping I use this:

```
player.body.applyLinearImpulse(new Vec2(0, 30000000), player.body.getPosition());

```

The problem is that the xVelocity doesn't remain the same during the jump so it isn't looking natural. Is there any way to modify only the x velocity of the body so that before jumping I store it in a variable and after jumping I apply it to the body?

I hope you understand what I am trying to say.

# Answer
You are defining your bodies in pixels instead of meters. Box2D uses meters. This way, your bodies got a very very huge mass, which causes you having to apply to big forces / impulses.

You have to define the lengths in meters and upscale your scene when you draw it.
> 3 votes

---
Tags: java, box2d, physics
---


# Question
Title: Draw a projection of a mesh on a surface
I have a mesh looking almost like a cylinder, the cylinder goes through a mesh and continues on the other side. What I want to do is to draw the projection of the cylinder on the mesh. So if you look at the images down below. I just want draw the green color on the surface. Any ideas? Im working in opengl.

# Answer
You're talking about the cylinder going through a *mesh*. But your picture shows a much simpler scenario where you're projecting into simple quad. So the main question is, can you represent your surface with a *plane*?

If that's the case, then I think you may be able to work with a **shadow matrix** to achieve this. A shadow matrix is one that typically takes a *ground plane* and a *light position* and projects any geometry that you render *into* the ground plane, *from* the point of view of the light.

It was normally used in conjunction with a stencil buffer to render planar shadows of objects, but it should also work in your case, since it's going to project your mesh into the plane. I found the following OpenGL implementation here which I have not tested:

```
void shadowMatrix(GLfloat shadowMat[4][4], GLfloat groundplane[4], GLfloat lightpos[4])
{
    GLfloat dot;

    /* Find dot product between light position vector and ground plane normal. */
    dot = groundplane[X] * lightpos[X] +
          groundplane[Y] * lightpos[Y] +
          groundplane[Z] * lightpos[Z] +
          groundplane[W] * lightpos[W];

    shadowMat[0][0] = dot - lightpos[X] * groundplane[X];
    shadowMat[1][0] = 0.f - lightpos[X] * groundplane[Y];
    shadowMat[2][0] = 0.f - lightpos[X] * groundplane[Z];
    shadowMat[3][0] = 0.f - lightpos[X] * groundplane[W];

    shadowMat[0][1] = 0.f - lightpos[Y] * groundplane[X];
    shadowMat[1][1] = dot - lightpos[Y] * groundplane[Y];
    shadowMat[2][1] = 0.f - lightpos[Y] * groundplane[Z];
    shadowMat[3][1] = 0.f - lightpos[Y] * groundplane[W];

    shadowMat[0][2] = 0.f - lightpos[Z] * groundplane[X];
    shadowMat[1][2] = 0.f - lightpos[Z] * groundplane[Y];
    shadowMat[2][2] = dot - lightpos[Z] * groundplane[Z];
    shadowMat[3][2] = 0.f - lightpos[Z] * groundplane[W];

    shadowMat[0][3] = 0.f - lightpos[W] * groundplane[X];
    shadowMat[1][3] = 0.f - lightpos[W] * groundplane[Y];
    shadowMat[2][3] = 0.f - lightpos[W] * groundplane[Z];
    shadowMat[3][3] = dot - lightpos[W] * groundplane[W];
}

```

Push this matrix before rendering the cylinder, and pop it afterwards. Draw with backface culling enabled. And if you want to limit the projected shape inside the quad's boundaries, look into how to use the *stencil buffer*.
> 3 votes

# Answer
I have a thought which might get you going.

You could take each polygon from your mesh and test to see where each edge intersects with the plane defined by your surface (you may have to get fancy to avoid duplicate testing on shared edges). The collection of these intersection points will help define a bounding area on your surface. This can then be used as a new mesh to render the intersection or You can run a pixel shader on your surface (or just a function on a texture) and look for pixels which are inside this bounding area (or just inside your original mesh if that's easier). To do this you may want to transform your collision points into texels, but how you would do that will depend largely on what surface your using.
> 0 votes

---
Tags: opengl, projection
---


title: Receive UDP packet in android

text:
# Question
Title: Receive UDP packet in android
I'm sending UDP packet to android over a wireless network from some other software . how can I receive that in android ? should I write a client in android to get the data?

# Answer
> 1 votes
You need to set up a DatagramSocket to receive DatagramPackets via UDP. There's an example in this SO question.

---
Tags: android, udp
---


# Question
Title: How do I optimize searching for the nearest point?
For a little project of mine I'm trying to implement a space colonization algorithm in order to grow trees.

The current implementation of this algorithm works fine. But I have to optimize the whole thing in order to make it generate faster. I work with 1 to 300K of random attraction points to generate one tree, and it takes a lot of time to compute and compare distances between attraction points and tree node in order to keep only the closest treenode for an attraction point.

So I was wondering if some solutions exist (I know they must exist) in order to avoid the time loss looping on each tree node for each attraction point to find the closest... and so on until the tree is finished.

# Answer
> 14 votes
Spatial hashing, quadtrees or octrees can be used to find candidates for the nearest neighbour quickly: and then you can use the loop on that candidate set to get the actual nearest neighbour.

**Initial Premature Optimization**

* `sqrt(n) > sqrt(y) if n > y and n > 0 and y > 0`
* `sqrt(n) < sqrt(y) if n < y and n > 0 and y > 0`
* `sqrt(n) = sqrt(y) if n = y and n > 0 and y > 0`
* `x*x + y*y > 0`

This means you don't need to find the square roots of the distance squared (so compare `dx*dx + dy*dy + dz*dz` instead of `sqrt(dx*dx + dy*dy + dz*dz)`).

**Spatial Hashing**

1. Get the items in the bucket that contains the item you are interested in, as well as the buckets surrounding it (in 3D that would mean you would need to get the items in 9 buckets).
2. Eliminate the original item from the set.
3. Loop through those items and find the nearest neighbour.

**Quadtree**

Consider the following diagram of a 2D quadtree.

Basically "the check" means:

```
// numberOfPointsSeen is the number of points seen in quads so far.
if numberOfPointsSeen > 0 then
   return nearestNeighbourUsingLoop(numberOfPointsSeen)
else
   continueToNextConcentricSquare()

```

If you organise your quadtree so that each quadnode can only contain one item (this might not make sense in terms of memory usage though):

```
if currentQuadContainsItem then
   return itemInCurrentQuad
else
   continueSearching()

```

# Answer
> 4 votes
Sorry I haven't read the linked document. This is how I understand your problem: you have some random points (attraction points) and given a node on your tree, you're trying to find the nearest attraction point? You don't say if this is 2D or 3D but here are a couple tips.

* **The square root**. A simple one to implement, don't use the square root when computing an comparing distances. Simply compare each squared value against each other. Square root calculations are expensive. Avoiding 300k of them can save time.
* **Spacial partitioning**. The simplest, QuadTree (for 2D) and OcTree (for 3D). These systems will help you search only the attraction points in a certain area, i.e. the area around your tree node of interest.
* **More advanced spacial partitioning**. The R-Tree this is supposedly the preferred spacial indexing method. If I remember correctly, a few of the major database systems have a version of R-Tree implemented for their databases. And kd trees, are good, and I believe are optimized for retival instead of insertions, so if you had static attraction points, this may be good.
* **Even more resources**. There's always Wikipedia coming to the rescue.

---
Tags: algorithm, tree
---


# Question
Title: Is it worth it, to try and prevent cheaters?
Perhaps one of the biggest issues that plague FPS-games are cheaters.

If you use a server-authoritative model, you will prevent some level of cheating. But why do this if people can still aimbot?

# Answer
> 1 votes
There are turnkey solutions for cheating, involving the equivalent of antivirus scanners specific to cheats. This is only cost effective for games that plan on having (or are aiming to have) an ongoing competitive community. Beyond that, you can incorporate fuzzy heuristics on the player's movement and aiming inputs to differentiate between natural and unnatural behaviors. Whether it is 'worth it' to you is primarily based on the time you wish to invest and your level of experience doing statistical analysis on streams of data; if you're learning from scratch, then it is probably not worth it.

---
Tags: first-person-shooter, anti-cheat
---


# Question
Title: XNA - Debugging/Testing Individual Sprites and Pixel Collision
I ran through the first training on XNA where you make a shooter game. They did some thing that I would not do and I want to use their starting point to learn more things.

I want to try better collision and adding a menu. I saw something online with the sonic physics where they have a frame by frame of sonic moving 1 pixel. See picture below.

I am new to development, but I have been programming for years now. What would you guys suggest to try these different things out.

How would I simulate a similar frame by frame testing as they do in the above picture?

Thanks!

# Answer
> 0 votes
What you need is another rectangle that represents the "contact body" of the sprite, different from the rectangle that represent the drawing surface of the sprite. It's the principles of the bounding boxes.

In my 2D fighting game, for example, I have one different bounding box per keyframe of the animations.

---
Tags: xna, pixel
---


title: Open Source Analysis

text:
# Question
Title: Open Source Analysis
There are a lot of code in open source projects, looking at all of the code is time consuming and can be confusing to a novice like me. Are there any sections of open-source projects that should be **focused** on?

What should I focus on when I look at code?

I'm asking this in general because if I ask this specifically, the question will only apply in one or two projects rather than an entire group of projects ranging in different types of games and difficulty.

# Answer
I'd recommend running doxygen: http://www.doxygen.nl/ Here is a list of the features: http://www.doxygen.nl/manual/features.html Doxygen uses the Graphviz tool kit to generate include dependency graphs, collaboration diagrams, call graphs, directory structure graphs, and graphical class hierarchy graphs. I find these types of diagrams helpful when trying to understand a large codebase.
> 6 votes

# Answer
Focus on what you're trying to get from the code. Are you looking for examples of design, for a working sample of how to do a particular thing, or anything specific like that?

Outside of that, have a look at the more general things around the code. Is it readable? Can you follow the program flow? How well commented it is? Do the comments provide useful info in addition to the code, or do they just repeat what is already evident from the code?

Other general factors might include: does the project actually compile as released (a surprising number don't)? What are the dependencies? What is the end-user installation experience like?

You might also find it useful to step through the code in a debugger to get a closer look at what it's doing and how it's doing it.
> 1 votes

---
Tags: open-source
---


# Question
Title: Help comparing Cocos2d and Unity3d for this project
I will not go into details, but I would like to hear your opinions about this:

Essentially, my project will be a 2d game, with lots of complex levels, where some might be simple and others might be a bit more deep, with physics, etc. We want to implement **our very own** online structure: logging in, leaderboards, achievements, friends etc with our own servers. This means no OpenFeint nor GameCenter at all. We expect this game to be very large in both graphics and audio. We wish to use in-app purchases.

---

## Now, we considered two options. Cocos2d and Unity3d.

We need help deciding using the factors I mentioned before (networking, good performance even for a large game in terms of graphics and audio like this, in-app purchases, etc) which option would fit better this?

Technically, both options can create 2d games. I'd like to hear your opinion.

# Answer
> 4 votes
For 2d game, cocos2d is surely preferable. Unity makes it easy for 3d apps, and the features that make it great for 3d will not be used in your project at all. Also considering unity is cross-platform, while cocos is single platform, that keeps you out of unnecessary overhead that is present in the engine. Cocos2d is also very polished and easy to use - features that will come very handy in large projects.

# Answer
> 2 votes
They both have their pluses and minuses, and I don't think that the little detail you've specified can really narrow down between the two which is better. It would probably be better to pick one based on desired workflow, tools support, cost, and experience of the team, I would think.

# Answer
> 1 votes
If you want to release the same game for many platforms (i.e. Chrome, Android, IOS, etc.) then Unity3D is definitely preferable. Otherwise you can enjoy cocos2D. I actually use both depending on what I want to achieve.

---
Tags: 2d, iphone, unity, networking, cocos2d-iphone
---


title: Deferred rendering + Shadow maps

text:
# Question
Title: Deferred rendering + Shadow maps
I have a 1920x1200 shadowmap which just has the depth values of my scene drawn from the point of view of the light.

I also have a 1920x1200 gbuffer that draws my scene to a fullscreen quad.

How can I sample the shadowmap from the gbuffer lighting phase? What kind of maths needs to be performed? I have access to view space normal and view space position.

# Answer
> 6 votes
Once you have the position of the shaded point, it's just the same as applying a shadow map in regular forward lighting. You need to convert the shaded point to shadow map screen space, which means getting its world position and then transforming it through the same view and projection matrices used to render the shadow map. You can bake all down into one 4x4 "view space to shadow" matrix that you pass in to your lighting shader.

Then once you have the point in shadow map space, do a texture lookup with comparison mode enabled, as usual for shadow maps.

---
Tags: opengl, shadows, shadow-mapping
---


# Question
Title: Lighting-Reflectance Models & Licensing Issues
Generally, or specifically, is there any licensing issue with using any of the well known lighting/reflectance models (i.e. the BRDFs or other distribution or approximation functions):

> Phong, Blinn–Phong, Cook–Torrance, Blinn-Torrance-Sparrow, Lambert, Minnaert, Oren–Nayar, Ward, Strauss, Ashikhmin-Shirley

and common modifications where applicable, such as:

> Beckmann distribution, Blinn distribution, Schlick's approximation, etc.

in your shader code utilised in a commercial product? Or is it a non-issue?

# Answer
> 4 votes
In the US, pure mathematical formulae cannot be copyrighted or patented (reference), so no, there is no issue with any of the lighting models you mentioned.

A specific piece of software implementing such a formula could be copyrighted or patented, but the formulae themselves are unencumbered and can be freely used to create your own implementation.

(Disclaimer: I am not a lawyer.)

---
Tags: licensing
---


title: Game development: Pre-production stage

text:
# Question
Title: Game development: Pre-production stage
I´m starting up a new project. It´s going to be a web browser game, developed using HTML5, JavaScript and CSS3.

I have some general questions regarding the process of game developing.

1. Should you know everything about your game by the time you start writing the first lines of code? I mean should you know all the details, all the things the player can and can not do? Basically: should you be done writing down new ideas before you begin coding?
2. I understand the pre-production process is about documenting, doing research etc. What does that mean? Does it mean I should open up Word and write down everything about the game? For example what should happen when you click on different things etc.

Thanks for your help!

# Answer
> 2 votes
Whoa, sounds like you're going for a "design up-front" model, i.e. waterfall. That works, but for stuff like games, a more iterative model works better.

What I mean is: have a general idea what your game is about. Know, at least, the main core mechanic of your game. Rotating blocks to make lines (Tetris)? Running to the end goal of a platformer level (Mario)? And so on.

Once you have that, you'll get more benefit from **actually trying out the working prototype** over designing it on paper. So I recommend you break it down into small iterations, and play it.

That's not to say "don't plan it out up front." For sure, know your vision, core gameplay mechanic, and major features. Beyond that, discovery of what works is half the fun :)

---
Tags: game-design, planning, process, documentation
---


title: Billboard rendering without distortion?

text:
# Question
Title: Billboard rendering without distortion?
I use the standard approach to billboarding within Unity that is OK, but not ideal:

`transform.LookAt(camera)`

The problem is that this introduces distortion toward the edges of the viewport, especially as the field of view angle grows larger. This is unlike the perfect billboarding you'd see in eg. Doom when seeing an enemy from any angle and irrespective of where they are located in screen space.

Obviously, there are ways to blit an image directly to the viewport, centred around a single vertex, but I'm not hot on shaders.

Does anyone have any samples of this approach (GLSL if possible), or any suggestions as to why it isn't typically done this way (vs. the aforementioned quad transformation method)?

EDIT: I was confused, thanks Nathan for the heads up. Of course, Causing the quads to look at the camera does not cause them to be parallel to the view plane -- which is what I need.

# Answer
> 4 votes
I'm confused by your question because in a standard perspective projection, drawing a billboard parallel to the view plane does *not* introduce distortion. It's equivalent to blitting the image to the viewport with some scaling, where the scaling depends on depth (perpendicular distance from the view plane).

The "distortion" you're seeing might happen if the system is actually orienting particles to face the camera rather than the view plane; that causes skewing near the screen edges. Or, you might be seeing that the sprite's scale changes as you rotate the camera, since when distance is measured to the view plane rather than to the camera, the sprite gets "closer" and hence bigger as it goes offscreen.

# Answer
> 1 votes
I believe you can set the top 3x3 matrix (in column-major speak) to the identity to do this. I don't see any reason why you couldn't do this in the shader, but you might be doing more work that way. You'd lose scale (in your xformation matrix) this way.

Edit: this article was helpful to me for billboard-ing and imposter-ing:

http://www.flipcode.com/archives/Billboarding-Excerpt\_From\_iReal-Time\_Renderingi\_2E.shtml

I don't know how conventional this is, but I call it "impostering" when perspective is maintained and "billboarding" when it is not.

---
Tags: unity, shaders, glsl
---


# Question
Title: Android Java rectangle collision detection not working
I had been hard coding a collision detection system which was buggy. Then I came across using rectangles for collision detection. So I put it all in and it does not work, I put a log in and it never logged.

Note to Java programmers who are not Android programers: Android uses the word `Rect` instead of `Rectangle`.

Code for Block.java:

```
public Rect getBounds(){
    return new Rect (this.x, this.y, 10, 20);
}

```

Code for Sprite.java:

```
public Rect getBounds(){
    return new Rect (this.x, this.y, 20, 20);
}

```

Code for MainGame.java:

```
for(Block block : BLOCKS) {
    block.draw(canvas);
    block.rigidbody();

    Rect spriter = sprite.getBounds();
    Rect blockr = block.getBounds();

    if(spriter.intersect(blockr)){
        showgameover = 1;
        Log.d(TAG, "Game Over");
    }

}

```

Is anyone able to help?

# Answer
Have you tried the debugger? The code looks like it should work, if the sprite and a block are indeed colliding.

Here's what you do, create a sprite and a block at the same position. Have a breakpoint on your `if(spriter.intersect(blockr))` statement. When it breaks inspect the elements rectangle values to ensure they do intersect.

I imagine that if these are currently intersecting you're just not set up to see the log properly and/or not doing anything with the `showgameover` variable.

**EDIT**

According to the documentation you're using the `intersect` method correctly.

One of the few remaining things to check is to ensure that your `for(Block block : BLOCKS)` is actually getting run. What I told you to do with the debugger should help answer that. Otherwise you can stick a `Log.d()` inside the loop and ensure that it's actually being run. But I recommend the debugger method, as that's more useful in the long run.
> 2 votes

# Answer
I am not sure if this is your problem, but I struggled with a subtle intersection bug for a long time. I traced it to Android's implementation of intersects:

```
public boolean intersects(int left, int top, int right, int bottom) {
     return this.left < right && left < this.right
            && this.top < bottom && top < this.bottom;
 }

```

Whereas the algorithm I was using assumed that 'touching' rects are intersecting, using the following implementation:

```
public static boolean intersects(Rect rect, Rect otherRect) {
    return  rect.left <= otherRect.right && otherRect.left <= rect.right
        && rect.top <= otherRect.bottom && otherRect.top <= rect.bottom;
}

```

Additionally, you should probably be using the intersects method instead of intersect as the latter modifies the rectangle (of the sprite rect in your case) to match the intersection area.
> 0 votes

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


# Question
Title: What does "kTriangles/s" mean in hardware graphics benchmark reports?
I've looked around and found several sites offering benchmarking statistics for mobile platforms and I've been seeing the unit of measure as "kTriangles/s". Originally I misread this, missing the 'k'; does this translate to "thousand(s) of triangles/s", e.g.:

8902 kTriangles/s = 8,902,000 triangles/s

(I'm pretty sure that my interpretation is correct, but I hope someone can confirm this for me)

# Answer
Your interpretation is correct, it's thousands of triangles per second.
> 6 votes

# Answer
In terms of utility as a measurement for how good hardware is?

**Absolutely nothing**

Yes, it means thousands of triangles per second. But it means nothing in terms of how good hardware is. It's about as useful a performance metric as CPU clock-speeds: at best an order-of-magnitude approximation.

These metrics are usually taken under ideal, benchmarking conditions, not real-world situations. In general, achieving these numbers in real applications will be impossible outside of the most ideal conditions. And what constitutes "ideal conditions" will change from hardware to hardware.
> 9 votes

---
Tags: performance
---


title: Need the co-ordinates of innerPolygon

text:
# Question
Title: Need the co-ordinates of innerPolygon
Let say I have this diagram,

Given that i have all the co-ordinates of outer polygon and the distance between inner and outer polygon is d is also given. How to calculate the inner polygon co-ordinates? **Edit:** I was able to solved the issue by getting the mid-points of all lines. From these mid-points I can move d distance, So I can get three points. No I have 3 points and 3 slopes. From this, I can get three new equations. Simultaneously, solving the equation get the 3 points.

# Answer
> 3 votes
March counterclockwise on the edge list. For each Pi-Pi+1 edge, project Pi and Pi+1 inwards via the perpendicular on the Pi\_Pi+1 line. Use a simple positive/negative half space check to get the correct inwards direction. ( perpendicular vectors in 2D, positive half plane/negative half plane).

Once you compute the normally displace Pi\_Pi+1 line, you can check it for intersection with its homologous Pi+1\_Pi+2 normally displaced line. The intersection is called P'i+1 and is a vertex of your required polygon.

Do note that the set of points that are *d* units away from the initial polygon and lie inside your polygon do not form a polygon, they form a "rounded corner" polyline. Note the little circle I drew. The arc between the two green and blue radii is part of this set. But the polygon you get is a "decent" approximation.

# Answer
> 1 votes
I know this has already been answered, but I believe the following code may be helpful to readers looking for an implementation of the solution.

```
// This function is a bit tricky. Given a path ABC, it returns the
// coordinates of the outset point facing B on the left at a distance
// of 64.0.
//                                         M
//                            - - - - - - X
//                             ^         / '
//                             | 64.0   /   '
//  X---->-----X     ==>    X--v-------X     '
// A          B \          A          B \   .>'
//               \                       \<'  64.0
//                \                       \                  .
//                 \                       \                 .
//                C X                     C X
//
FTPoint FTContour::ComputeOutsetPoint(FTPoint A, FTPoint B, FTPoint C)
{
    /* Build the rotation matrix from 'ba' vector */
    FTPoint ba = (A - B).Normalise();
    FTPoint bc = C - B;

    /* Rotate bc to the left */
    FTPoint tmp(bc.X() * -ba.X() + bc.Y() * -ba.Y(),
                bc.X() * ba.Y() + bc.Y() * -ba.X());

    /* Compute the vector bisecting 'abc' */
    FTGL_DOUBLE norm = sqrt(tmp.X() * tmp.X() + tmp.Y() * tmp.Y());
    FTGL_DOUBLE dist = 64.0 * sqrt((norm - tmp.X()) / (norm + tmp.X()));
    tmp.X(tmp.Y() < 0.0 ? dist : -dist);
    tmp.Y(64.0);

    /* Rotate the new bc to the right */
    return FTPoint(tmp.X() * -ba.X() + tmp.Y() * ba.Y(),
                   tmp.X() * -ba.Y() + tmp.Y() * -ba.X());
}

```

---
Tags: xna, c++, mathematics, algorithm, vector
---


# Question
Title: Calculate the direction, From Outer Polygon Point to Inner Polygon inside Point
I was able to find the co-ordinates of inner Polygon using this trick.

Need the co-ordinates of innerPolygon

But, I have some problem in getting the direction from Outer Polygon Point to Inner Polygon inside Point? See this image, I need to make sure that the direction should be from inner to outer.

# Answer
> 3 votes
In general, you need to have a parsing convention for your polygon. Once you adopt this for all your polygons, the answer is immediate. For instance, the following picture illustrates “when parsing the list of points, the inside of the polygon is always on the right”:

Now what if you don't have this information yet? Here is one simple technique:

* find the leftmost point of the polygon, call it `A = P[n]`; if there are several such points, pick the uppermost
* pick the previous point and the next point in the list, `B = P[n-1]` and `C = P[n+1]`
* compute the z coordinate of cross product `AB × AC`, *aka.* `z = (B.x - A.x) * (C.y - A.y) - (C.x - A.x) * (B.y - A.y)`
* if `z` is positive, the inside of the polygon is **on the right when parsing the list of points**.
* if `z` is negative, the inside of the polygon is **on the left when parsing the list of points**.

Note that the above needs only to be done once per polygon.

Now when you travel from `A` to `B`, a simple vector pointing to the **left** of the path is `(A.y - B.y, B.x - A.x)`.

---
Tags: xna, c++, mathematics, algorithm, vector
---


# Question
Title: How can I fade something to clear instead of white?
I've got an XNA game which essentially has "floating combat text": short-lived messages that display for a fraction of a second and then disappear.

I've recently added a gradual "fade-away" effect, like so:

```
 public void Update()
        {
            color.A -= 10;
            position.X += 3;
            if (color.A <= 10) isDead = true;
        }

```

Where `color` is the Color int the message displays as. This works as expected, however, it fades the messages to *white*, which is very noticeable on my indigo background.

Is there some way to fade it to transparent, rather than white? Lerp-ing towards the background color isn't an option, as there's a possibility there will be something between the text and the background, which would simply be the inverse of the current problem.

# Answer
If you work with premultiplied alpha, the default behaviour, you have to multiply the alpha....

```
public void Update()
{
      color*= 0.95f;
      position.X += 3;
      if (color.A <= 10) isDead = true;
}

```

The difference here is you're modifying the color, i.e. all values simultaneously and uniformly, rather than just the alpha value.
> 6 votes

# Answer
You're doing exactly what you should do - changing the alpha channel of the color you use when drawing the sprite. That isn't where the problem lies.

The problem is that if you just use the default SpriteBatch.Begin() behaviour, your sprite blends to its color (normally: white) rather than blending to actual transparency. What you need to do is set your BlendState to BlendState.NonPremultiplied, then everything will be fine.

```
SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.NonPremultiplied)

```

Blau's answer provides a different method (the premultiplied one) which apparently has a few advantages over this one.
> 9 votes

---
Tags: xna, c#, graphic-effects
---


title: Zooming to point of interest

text:
# Question
Title: Zooming to point of interest
I have the following variables:

* Point of interest which is the position(x,y) in pixels of the place to focus.
* Screen width,height which are the dimensions of the window.
* Zoom level which sets the zoom level of the camera.

And this is the code I have so far.

```
void Zoom(int pointOfInterestX,int pointOfInterstY,int screenWidth,
   int screenHeight,int zoomLevel)
{
glScalef(1,1,1);
glTranslatef( (pointOfInterestX/2) - (screenWidth/2), (pointOfInterestY/2) - (screenHeight/2),0);

glScalef(zoomLevel,zoomLevel,1);
}

```

And I want to do zoom in/out but keep the point of interest in the middle of the screen. but so far all of my attempts have failed and I would like to ask for some help.

# Answer
> 3 votes
So you want zoom just like in google maps? If you hover over city and zoom there cursor stays top of that city. This give smooth transition.

```
        public static final void zoom(float amount, float toX, float toY) {
            float oldZ = camera.zoom;
            camera.zoom += amount;
            // If zooming still has effect then we need translate map towards cursor
            if (camera.zoom < minZoom) {
                    camera.zoom = minZoom;
            } else if (camera.zoom > maxZoom) {
                    camera.zoom = maxZoom;
            } else {
                    float a = (toX - (float) HALFSCREENSIZEX)
                                    * (oldZ - camera.zoom);
                    float b = (-toY + (float) HALFSCREENSIZEY)
                                    * (oldZ - camera.zoom);
                    camera.translate(a, b, 0);
             //check boundaries if you have any.
            }
    }

```

To make this work with matrix stack you might have to peek there http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java

Zooming is just multiplier for viewport size there. I have done this with matrix stack too but its much cleaner to use camera class.

---
Tags: opengl, mathematics
---


title: Thread-safety in Cocos2d-iPhone?

text:
# Question
Title: Thread-safety in Cocos2d-iPhone?
After tinkering a bit with cocos2d, I discovered that there is no classic game loop and everything is more-or-less event driven. I guess I can wrap my head around that, no problem.

But I cannot find anything about thread safety. Say, I schedule something to occur every two seconds, which Thread will run the code? Given that I cannot find anything about that, I guess there is just one Cocos2d Thread and everything will be fine.

Nevertheless, this implicit assumption does not give me a good feeling. Knowing is better than guessing. ;-)

Can anyone shed some light onto that topic?

# Answer
as much as I can remember, there is no built-in threads in cocos2d. as you said everything is event driven but, events are queued, and run once at a time. so you don't need to worry about the thread safety at all, just keep in mind that some when you schedule two different events, they might not be run in same order as you scheduled them. but I think the priority option will solve that issue events with lower priority runs first.
> 1 votes

---
Tags: iphone, cocos2d-iphone, objective-c
---


# Question
Title: Gamestate management without evil Singletons
I wanted to use a game state management system similiar to this approach: Managing Game States in C++

But from what I've heard singletons are evil and should not be used in 99.9%.

Can you tell me how I could modify the method of the above article to work without singletons?

# Answer
> 0 votes
It is possible to handle game state management without an actual manager for game states.

The way I implemented it in my game was to create a static function in the base class to get the first state.

The first state is usually fixed or could be a different one each time you start the game based on some external settings (like in my game). I let the base class's static function to decide which state should be returned.

Now for each state, I have this policy that every state should know what its next state should be. By having this feature within each state it is always possible to move forward from one state to the next. Going back to the previous state is simply advancing to the next state. Or if required you can store previous state instance in the current state and use that as the next state to go back to the previous state. Make sure to handle memory in that case. I would suggest using SharedPtr.

Every state would need an instance of the object which the updating of the current state. In my case this is the Game class. This way I am passing around the game class and can thus avoid the Game class to be a singleton.

So with this design you have a start point defined as static function and state management with each state. This is easy if you are building a game rather than if you are trying to build a framework that doesnt know about the individual states in advance and how to transition between them.

# Answer
> 8 votes
If you just want to avoid the singletons you could create instances of every game state you need in your initialization code. Then add these to a map inside the CGameEngine class - for example:

```
game.AddGameState("Intro", new CIntroState());
game.AddGameState("Menu", new CMenuState());
...

```

You could than add a method to the CGameEngine to retrieve the game state instances:

```
GameState* GetGameState(std::string stateName);

```

like this:

```
GameState* introState = game.GetGameState("Intro");

```

and you could use these with the existing methods to change the states however you like. You just have to take care of releasing the memory of all the allocated states in the deinitialization code of your game.

The downside of this approach (and the singleton approach in the linked article) is that all game state instances are residing in memory for the whole duration of the game. But this might not be a problem depending on your requirements and target platform.

# Answer
> 2 votes
One of the reasons that it's bad to use Singletons is that it's extremely difficult to decouple them from any design.

What I would do is just to make the Engine class take a regular reference to a state, and then declare the IntroState on the stack and pass it in.

---
Tags: c++, sdl
---


title: Box2D how to implement a camera?

text:
# Question
Title: Box2D how to implement a camera?
By now i have this Camera class.

```
package GameObjects;

import main.Main;

import org.jbox2d.common.Vec2;
public class Camera {

public int x;
public int y;
public int sx;
public int sy;

public static final float PIXEL_TO_METER = 50f;

private float yFlip = -1.0f;

public Camera()
{
    x = 0;
    y = 0;
    sx = x + Main.APPWIDTH;
    sy = y + Main.APPHEIGHT;
}

public Camera(int x, int y)
{
    this.x = x;
    this.y = y;
    sx = x + Main.APPWIDTH;
    sy = y + Main.APPHEIGHT;
}

public void update()
{
    sx = x + Main.APPWIDTH;
    sy = y + Main.APPHEIGHT;
}

public void moveCam(int mx, int my)
{

    if(mx >= 0 && mx <= 80)
    {
        this.x -= 2;
    } else if(mx <= Main.APPWIDTH && mx >= Main.APPWIDTH - 80)
    {
        this.x += 2;
    }

    if(my >= 0 && my <= 80)
    {
        this.y += 2;
    }
    else if(my <= Main.APPHEIGHT && my >= Main.APPHEIGHT - 80)
    {
        this.y -= 2;
    }
    this.update();
}

public float meterToPixel(float meter)
{
    return meter * PIXEL_TO_METER;
}

public float pixelToMeter(float pixel)
{
    return pixel / PIXEL_TO_METER;
}

public Vec2 screenToWorld(Vec2 screenV) {
    return new Vec2(screenV.x + this.x, yFlip
            * screenV.y + this.y);
}

public Vec2 worldToScreen(Vec2 worldV) {
    return new Vec2(worldV.x - this.x, yFlip
            * worldV.y - this.y);
}

```

}

I need to know how to modify the screenToWorld and worldToScreen functions to include the PIXEL\_TO\_METER scaling.

# Answer
> 0 votes
I've managed to do this myself. Here is what everyone who has the same problem should do:

```
public Vec2 screenToWorld(Vec2 screenV) {
    return new Vec2( this.x + screenV.x / PIXEL_TO_METER, yFlip
            * (screenV.y / PIXEL_TO_METER + this.y));
}

public Vec2 worldToScreen(Vec2 worldV) {
    return new Vec2((worldV.x - this.x) * PIXEL_TO_METER, (yFlip
            * worldV.y - this.y) * PIXEL_TO_METER);
}

```

---
Tags: java, box2d
---


# Question
Title: How should I determine direction from a phone's orientation & accelerometer?
I have an Android application which moves a ball based on the orientation of the phone. I've been using the following code to extract the data - but how do I use it to determine what direction the ball should actually travel in?

```
public void onSensorChanged(int sensor, float[] values) {
    // TODO Auto-generated method stub
   synchronized (this) {
        Log.d("HIIIII :- ", "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
        if (sensor == SensorManager.SENSOR_ORIENTATION) {
            System.out.println("Orientation X: " + values[0]);
            System.out.println("Orientation Y: " + values[1]);
            System.out.println("Orientation Z: " + values[2]);
        }
        if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
            System.out.println("Accel X: " + values[0]);
            System.out.println("Accel Y: " + values[1]);
            System.out.println("Accel Z: " + values[2]);
        }
    }
}

```

# Answer
I'm not sure but I guess the simplest way to use those data is something like this:

```
public void onSensorChanged(int sensor, float[] values) {
    // TODO Auto-generated method stub
   synchronized (this) {
        Log.d("HIIIII :- ", "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);

        if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
            ball.x += values[0];
            ball.y += values[1];
        }
    }
}

```

note that accelerometer is a device which computes the acceleration vector applied to the device. gravity is simply applying some acceleration to the device. so the raw data itself can be used to determine direction of device. you make movements more stable you can use average value of past 10 ticks instead of just latest value. also you can multiply a rotation matrix to the values so that user doesn't need to keep device exactly parallel to the ground.
> 0 votes

---
Tags: java, android
---


title: Playing a sound on collision?

text:
# Question
Title: Playing a sound on collision?
I'm making a pool game. I've separated the gameplay logic and the physics into two systems, entities and physics. Each entity holds a reference to a body which the physics system uses. The body itself holds a reference back to it's owner. When an entity collides with another entity, the `Collided(Entity other)` method is called on both.

What I'm trying to do now is to play a sound when both entities colliding are of a certain subclass. I'm not sure how to do that. I could do it in the `Collided` method, but then the sound would be played two times at the same time, since the method was called on both entities.

How do you suggest I do this?

# Answer
Add a flag to your Collided method, and when you call a pair of Collided events only have one of them process the sound (AUDIBLE and SILENT are simply constants for TRUE and FALSE):

```
a.Collided(b, AUDIBLE); b.Collided(a, SILENT);

```

This method is very simple, but it does require that you are calling the events in pairs... in other words, that they are explicitly called right next to each other for each collision. Another method, and this is similar to what @GeorgeDuckett was suggesting, is this:

```
a.Collided(b);
b.Collided(a);
Sound.collision(a,b);

```

Regardless of whether you have the sound code external to the objects or inside them, you will be doing a table lookup in the end... asking the sound system if it has a sound that matches objects a and b in either order. Make sure that this query is order independant... it should return the same result for (b,a) and (a,b). If you will not have every combination possible, you should also have failthrough logic... for example, you might have a generic 'a' sound that you use when there is no specific sound for collisions with 'b' (or vice versa, of course).

Both of these suggestions require locality; they require that you are processing both sides of the collision at once. If your code looks like this you will need a different answer:

```
for each object
  ...

  object.Collided(other);
end

```
> 1 votes

# Answer
I am fairly new to this, but I would make the collided method a trigger for the individual call to each collide. Then you can keep the same call, but it would allow you test for type and then call the sound before each separate collision call is made.

I may be way off base, but they seems like the most logical approach since the sound would need to be triggered once and only when certain objects collide.
> 0 votes

---
Tags: physics, sound
---


# Question
Title: *DX11, HLSL* - Colour as 4 floats or one UINT
With the DX11 pipeline, would it be much quicker for the vertex buffer to pass one single UINT with one byte per channel to the input assembler, as opposed to three floats? Then the vertex shader would convert the four bytes to four floats, which I guess is the required colour format for the pipeline. In this instance, colour accuracy isn't an issue.

The vertex buffer would need to be updated many times per frame, so using a single UINT and saving 12 bytes for every vertex could well be worth it: quicker uploads to vram and also less memory used. But the cost is the extra shader work for every vertex to convert each 8 bits of the input UNIT into a float.

Anyone have an idea if it might be worth doing?

Or, is it possible for the pipeline to be set to just internally use a four-byte colour format? The swap chain buffer has been initialised as DXGI\_FORMAT\_R8G8B8A8\_UNORM, so ultimately that's how the colour will be written.

Thanks!

# Answer
> 3 votes
The pipeline will always be floating point internally, and the hardware does the int/float conversions for you, so that part of it should be very fast. If your app is vertex-bound, either on the CPU side updating the buffer or on the GPU side reading it, then the thinner UINT format could make a difference. You'll have to measure and compare the performance to see which is faster.

---
Tags: hlsl, color
---


title: Unity3d vector and matrix operations

text:
# Question
Title: Unity3d vector and matrix operations
**I have the following three vectors:**

* posA: (1,2,3)
* normal: (0,1,0)
* offset: (2,3,1)

I want to get the vector representing the position which is offset in the direction of the normal from posA.

**I know how to do this by cheating (not using matrix operations):**

```
Vector3 result = new Vector3(posA.x + normal.x*offset.x
                             posA.y + normal.y*offset.y,
                             posA.z + normal.z*offset.z);

```

**I know how to do this mathematically** Note: \[\] indicates a column vector, {} indicates a row vector

```
result = [1,2,3] + {2,3,1}*{[0,0,0],[0,1,0],[0,0,0]}

```

**What I don't know** is which is better to use and if it's the latter how do I do this in unity? I only know of 4x4 matrices in unity. I don't like the first option because you are instantiating a new vector instead of just modifying the original. Suggestions?

Note: by asking which is better, I am asking for a quantifiable reason, not just a preference.

# Answer
Hate answering my own questions, but here is what I did to solve this:

Unity has Vector3.scale. I assumed this was just scalar multiplication, but instead it's component-wise multiplication of vectors which is what I was doing with the matrices. The Vector3 class already has the + operator for component-wise addition, so this got really easy.

```
Vector3 result = posA + Vector3.Scale(normal,offset);

```

Haven't tested it, but it looks right

Though, I'm assuming the scale method is implemented using the exact code from my first example, at least it's cleaner now. I may write a method that uses references to modify the passed parameter so I'm not creating new instances just for this.
> 4 votes

---
Tags: unity, matrix
---


title: OpenGL lighting with dynamic geometry

text:
# Question
Title: OpenGL lighting with dynamic geometry
I'm currently thinking hard about how to implement lighting in my game. The geometry is quite dynamic (fixed 3D grid with custom geometry in each cell) and needs some light to get more depth and in general look nicer.

A scene in my game always contains sunlight and local light sources like lamps (point lights). One can move underground, so sunlight must be able to illuminate as far as it can get.

Here's a render of a typical situation: The lamp is positioned behind the wall to the top, and in the hollow cube there's a hole in the back, so that light can shine through.

(I don't want soft shadows, this is just for illustration)

While spending the whole day searching through Google, I stumbled on some keywords like *deferred rendering, forward rendering, ambient occlusion, screen space ambient occlusion* etc. Some articles/tutorials even refer to *"normal shading"*, but to be honest I don't really have an idea to even do simple shading.

OpenGL of course has a fixed lighting pipeline with 8 possible light sources. However they just illuminate all vertices without checking for occluding geometry.

I'd be very thankful if someone could give me some pointers into the right direction. I don't need complete solutions or similar, just good sources with information understandable for someone with nearly no lighting experience (preferably with OpenGL).

# Answer
It sounds what like you want is the standard OpenGL lighting pipeline plus shadow mapping.

In a nutshell, shadow mapping involves rendering the depth buffer from your light's point of view, and then projecting that texture onto your scene. It's a simple technique whose performance is unaffected by complex geometry (since it's an image-space algorithm) - I highly recommend it.
> 7 votes

---
Tags: opengl, lighting, shadow-mapping, shading
---


# Question
Title: How do I pick correct tile in isometric 3D map?
I want to know how to pick the correct tile on a isometric map in 3D space. Here is a 2D example.

They use a colour key map to correctly pick the coordinate. How can I achieve this in 3D space? Is the method similar?

# Answer
> 1 votes
The color picking method you linked is suitable for "3D isometric", depending on how you implement it. This is because 3D isometric is not well defined and can have a similar "ground" as 2D isometric. So the tiles will be the same, what will change is the objects in the world. The objects will be 3D and placed so they fit in with the camera angle of your isometric world. A full 3D world would not technically be called isometric.

# Answer
> 1 votes
If you are representing your objects as 3D polygons in 3D space, the word to search for is “picking”.

Brief summary: A mouse location is (x,y) in *screen* coordinates. In your 3d world, the mouse location corresponds to a *ray* (or line) in *world* coordinates. You intersect that ray with everything in your world and see what it hits. The closest object that the ray hits is the one that the mouse is pointing at.

If all you want to do is know where *on the ground* the mouse is pointing, it's fairly easy. You intersect the ray with the plane `z = 0`. Solve the equation and you get back (x, y, 0) in world coordinates. I recommend doing this even in the regular "2D" isometric world. Color keying tiles on the ground is a lot more complicated than solving this equation (color keying might make sense for more complex shapes though).

If you want to know which of many 3D objects the mouse is pointing at, you intersect the ray with each of the polygons in each of those objects. I recommend starting with brute force: intersect the ray with every polygon and see what hits. Do that first and make sure it gives you the results you want. In practice you'll want to intersect with just a few polygons instead of all of them, using a spatial hash or a gpu buffer with object ids.

---
Tags: 3d, tiles, isometric, picking
---


# Question
Title: Purchasing a TV show adaptation rights, how does it work?
Basically, I was thinking about a game based on a TV show, just for fun, and ended up thinking "well, it's not like it can be made anyway". Or can it?

In the present situation, developing a game by myself/ourselves on my/our free time, and then using crowdfunding to purchase the rights is not **that** crazy, if the show is really popular... and the rights not *too* expensive.

Purchasing the rights of the whole show is obiously a sh!tload of money, but what about adaptation rights? What is the range of price it can be? Is it a percentage of the full rights? Does it depend on the kind of adaptation (novel vs. toy vs. game)?

ps: if it can help answer, I was thinking about a MLPFIM retro RPG. Please don't laugh at me.

# Answer
The video game rights to the My Little Pony franchise appear to currently be owned by Hasbro.

While Hasbro does not appear to have an internal game development studio, Hasbro does have strong relationships with both EA and Activision, with core-audience games ("Transformers") typically being developed by Activision-owned studios, and casual games ("Monopoly") typically being developed by EA-owned studios.

So *it seems to me that you're asking the wrong question*. Acquiring the rights to make a game based on someone else's license isn't chiefly about money (although money is still a factor). It's chiefly about the license-holder trusting someone else to work with the license in order to bring it to a new marketplace or a new audience, without harming the existing value of the license. If Hasbro feels that (for example) a video game fighting game starring the cast of MLP would bring the license into disrepute, they won't sell a license to do that, regardless of the amount of money offered.

So.

*The question you should really be asking is this*: what do you bring to the table that would make Hasbro want to sell you the rights to make a game based on their license, rather than selling those rights to EA? Or to Activision? Both of whom they already know and are (as far as I know) happy to continue doing business with.
> 9 votes

# Answer
Basically, you have your lawyers call their lawyers.

Licensing a TV show or film usually goes through the production company — you can find that on imdb for movies. So, for example, to license *Stargate Universe* you would call up Rob Cooper at Syfy, or more likely you'd go through their original programming department at 100 Universal City Plaza. Licensing a book generally goes through the author's agent, or the publisher, depending on who owns the rights.

This seems like a simple transaction, but there are many important details:

It's expensive. *Really* expensive. The cost varies with the popularity of the product license, whether you're getting exclusive or nonexclusive rights, whether you'll end up owning the game yourself or you're doing the work or hire, the personality of the executive producer involved, etc. Usually it is an up front cash licensing fee and then some percentage of revenue. The cost can range from several hundred thousand dollars for a Nintendo DS port of a minor childrens' animated series, to many millions for primetime brands.

A failed game can harm the parent brand. So, most production companies need to be confident that the licensing studio can make a successful product, on budget, without missing milestones. Typically that means you need to be an established studio, or a well-funded one, or have some kind of relationship with the rightsolder where you're doing it as work-for-hire, or they own equity in you, or something like that.

Hollywood is a cliquish business; deals are made through networks of relationship and trust. This is why you need an experienced IP lawyer or agent to land licensing deals: you need someone who knows exactly who to reach, how to call them, and how to broker a deal with all the people who need to be involved. That's what's meant by "I'll have my people call your people."

So basically, to license a TV show, you need:

1. To convince the production company that your studio *will* make a good game that helps the brand, on schedule, on time, without needing more money from them. That means either being an established business, or having all of your own funding lined up first, or doing the work for hire.
2. Someone who knows a guy who knows a guy inside the company that can broker the deal between you.
3. Lots of lawyers.
> 4 votes

---
Tags: legal, copyright
---


title: Client-side prediction for FPS

text:
# Question
Title: Client-side prediction for FPS
People that understand client-side prediction and client-side interpolation, I have a question:

When I play the game Team Fortress 2, and type `cl_predict 1` into the developer's console, it enables client-side prediction. The also says "6 predictable entities reinitialized". It says this regardless of how many players are on the server, which makes sense, because other players are not predictable entities.

I thought client-side prediction was only for the movement of the player. Are there other entities that the client can provide prediction for?

# Answer
> 1 votes
Client-side prediction can be used for everything that needs to stay synced between all players, like physics objects and bullets. You basically run the simulation on all computers, but every so often the server "overwrites" the current state so everybody sees the same thing.

Most objects don't really need to be updated that often, and non-gameplay objects like ragdolls or particles don't need to be synced at all.

---
Tags: first-person-shooter
---


# Question
Title: I finished "Beginning Android Games", should I use its framework?
I've worked through Mario Zechner's "Beginning Android Games" and have made my own pong and asteroids game using the framework used in the book. I have also downloaded the source code for Replica Island and am able to run that.

I like Replica Island's framework over the one I made from reading the book. Some differences are that Replica Island uses different activities for each screen instead of Zechner's Screen class and that Replica Island can use a lot of textures and isn't limited to textures with dimensions of powers of 2.

If I'm serious about writing games and apps for Android should I learn Replica Island's framework and use that instead of the one I made while reading Zechner's book?

# Answer
I'm not sure that your question will be flagged but I started out down the same path as you. I started by learning Rokon, then did a game with the Replica Island codebase, then a few games with libgdx and now am using Unity. I would say up front that the final choice you make on a technology will depend on what type of game you make.

Replica Island: The first thing I would mention about the RI platform created by Chris Pruett (former Googler) is that he built RI as a company sponsored project while he was there. Remember that at the time, devices were nothing like they are now and he had access to almost every device running Android so he was able to build a stable game across many devices. It's a good platform, has some basic physics and helper components but to my knowledge, is not actively supported by continued development. Pruett has since moved on to start a indie game company and now uses Unity3d.

RI uses a binary file format for levels that took me some time to learn. There were no resources available to edit the files to create new levels so I had to build one which I did release (in flash) but it was just basic enough for me to use. I actually continued some development on the editor but didn't release the updates. If you ever decide to learn RI and need a level editor, I could post the updated flash editor but it assumes that you know flash and requires you to run php locally to create the .bin files for the game.

Libgdx: After creating a game with RI, I started learning libgdx. This was over a year ago and the biggest advantage it has over RI is that it's always being improved. It's made significant progress over that time and is still very active, both in development and community/support. Mario is very helpful and is very much available to help (although I wouldn't bother him personally) he does answer the forums as well as many other knowledgeable people. I made a very resource intensive game that ran on many low end devices and was very stable. It has support for box2d and bullet physics, has a particle effect editor, font editor, etc. It's a really nice platform to use IMO but if you want to build a game in 3d, you may find there are less resources available.

At the end of the day, I would recommend libgdx solely for the fact that it's an active project. The other nice thing is that you can prototype for devices much faster running in a LWJGL or JOGL frontend instead of using the emulator.
> 8 votes

# Answer
I wouldn't use the exact framework written throughout the book. However, the writer has built an entire new framework on some of the same principles, called libgdx. It's more advanced and much better, and after reading the book you should have a headstart.

The framework is really good, but choose the one you like the best.

Edit: just have to add that developing and debugging a libgdx game is like a dream. You can run the games directly on your computer with only a second of build time. Np super slow emulator or install on phone. Saves you a bunch of time!
> 5 votes

# Answer
If you like the Replica Island framework, use it. This is totally up to you.
> 2 votes

---
Tags: android
---


title: how to add water effect to an image

text:
# Question
Title: how to add water effect to an image
This is what I am trying to achieve: A given image would occupy say 3/4th height of the screen. The remaining 1/4th area would be a reflection of it with some waves (water effect) on it.

I'm not sure how to do this. But here's my approach:

* render the given texture to another texture called mirror texture (maybe FBOs can help me?)
* invert mirror texture (scale it by -1 along Y)
* render mirror texture at height = 3/4 of the screen
* add some sense of noise to it OR using pixel shader and time, put pixel.z = sin(time) to make it wavy

(Tech: C++/OpenGL/glsl)

Is my approach correct ? Is there a better way to do this ? Also, can someone please recommend me if using FrameBuffer Objects would be the right thing here ?

Thanks

# Answer
I assume you're after this kind of old-school, 2d effect:

If so, you're correct.

1. Render your "real" frame to an FBO.
2. Render the top part to the framebuffer using a simple textured quad, using the FBO as the texture.
3. Render the bottom part mirrored, with some horizontal waves.

You have several options on how to achieve the third. The simplest way would be to render one pixel high textured spans, stretch and offset them. Alternatively you could use shaders and do even more interesting effects.

Other things to try include tinting the mirrored version towards blue a bit, as well as varying the brightness of the scanlines ("wave" them too).

You can also grow the waves further away from the mirroring point.

This effect is also completely possible with good old plain opengl 1.x, even without FBOs. Render to texture and use glReadPixels to read the top part back to system memory, upload it as a texture and then do the scanline-by-scanline rendering. This, however, is so slow that if you can use FBOs, it's always a much better option.

**EDIT: suggestions for the shader bit**

I recommend doing these step by step, so you'll see what each change does, and adjust them based on what you're after.

* Render the mirrored bit, top-down.
* Adjust the horizontal texture coordinate (u or v, depending. I'm assuming u here) with sin() function, such as:

`u+sin((v+t)*FREQ)*AMP`

where FREQ and AMP are constants you'll find by trial and error. Both are below zero. Let's say start with 0.1. 't' is a time constant, probably a float uniform.

* Scale the waviness so that it's weaker near the mirror line, like:

`u+(sin((v+t)*FREQ)*AMP) * v`

or possibly (1-v), depending on how the texture is oriented. You may wish to increase AMP after this change.

* Since the texture coordinates go outside the 0..1 range, you may wish to scale it back, like..

`u+((sin((v+t)*FREQ)*AMP+AMP)/(1.0 + 2*AMP)) * v`

Depending on the scene you're rendering, the above may look worse than letting it wrap.

Note though that all the calculations above are off the top of my head without texting, and may contain mistakes, but that's the basic principle anyway. You may also want to try swapping u and v for another kind of wavy effect, or even combine the two.
> 4 votes

# Answer
You can find a nice looking water tutorial here and check out this link for screenshots of the effect. There are a number of ocean shaders that you can have a look at for a more realistic water effect than a sine wave.

There's lot of papers, articles, shaders etc here which ranges from fairly intermediate to advanced, and they use OpenGL and GLSL.

Hope that helps.
> 2 votes

# Answer
brainydexter, check out GeeksLab, it has a nice "water/ripple" shader. It's not simulating water but a ripple. Maybe this helps you a bit:

http://www.geeks3d.com/20110428/shader-library-swirl-post-processing-filter-in-glsl/
> 0 votes

---
Tags: opengl, rendering, glsl
---


# Question
Title: How do I read the an environment map CPU side? (Similar to texCube function on GPU)
I need to extract the one pixel from a environment mapping (I already have the 6 textures) using the normal vector. How can I achieve this ?

I want something very similar to what `texCUBE`(link) does in GPU but in CPU.

I am using XNA and C#, but an example in any language may help.

# Answer
> 4 votes
Someone answered in another forum - the original post is here:

> The largest component of the normal vector tells you which face it intersects. Next divide the normal vector by the absolute value of the largest component. Then scale and shit the other two components into the usual range for uvs (\[0, 1\] on each axis).
>
> For example if you had the vector \<-3, -1, 2\>.
>
> First it intersects the negative x face. Then
>
> \<-3, -1, 2\> / |-3| = \<-1, -1/3, 2/3\>.
>
> Finally just scale the remaining two components from \[-1, 1\] to \[0, 1\], \<-1/3, 2/3\> * 0.5 + 0.5 = \<2/3, 5/6\>. And similarly for each other face.

---
Tags: xna, shaders, graphics-programming
---


title: Creating a 2D Line Branch

text:
# Question
Title: Creating a 2D Line Branch
I'm looking into creating a 2D line branch, something for a "lightning effect". I did ask this question before on creating a "lightning effect" (mainly though referring to the process of the glow & after effects the lightning has & to whether it was a good method to use or not); Methods of Creating a "Lightning" effect in 2D

However i never did get around to getting it working. So i've been trying today to get a seconded attempt going but i'm getting now-were :/.

So to be clear on what i'm trying to-do, in this article posted; http://drilian.com/2009/02/25/lightning-bolts/

I'm trying to create the line segments seen in the images on the site. I'm confused mainly by this line in the pseudo code;

```
// Offset the midpoint by a random amount along the normal.
midPoint += Perpendicular(Normalize(endPoint-startPoint))*RandomFloat(-offsetAmount,offsetAmount);

```

If someone could explain this to me it would be really grateful :).

# Answer
> 1 votes
That line gets a unit vector (vector of length 1) from `startPoint` to `endPoint`

```
Normalize(endPoint-startPoint)

```

then gets a vector perpendicular to that (i.e. at right angles to the line)

```
Perpendicular(Normalize(endPoint-startPoint))

```

then multiplies it by some amount with a range (+ve or -ve).

```
* RandomFloat(-offsetAmount,offsetAmount)

```

It then adds this to `midPoint` thereby offsetting it.

# Answer
> 1 votes
I also tryied to implement "lighting" effect into my engine and my part of code for your problem is follows:

```
Random rand=new Random();
Vector3 dir = Vector3.Normalize(segment.endPoint - segment.startPoint);
midPoint += new Vector3(dir.Y, -dir.X, 0) *(float)(rand.NextDouble()*(offsetAmount*2)-offsetAmount);

```

Trick is hidden here:

```
  new Vector3(dir.Y, -dir.X, 0)

```

This creates normal vector, witch is perpendicular.

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


title: Implementing a Risk-style board

text:
# Question
Title: Implementing a Risk-style board
I have two images of the same dimensions. One is represents the game board in a user-appealing way, the other represents it in a computer-friendly way where each game area is painted in a unique, uniform color. When the user clicks the board, we get the click coordinates, find the color of the pixel at the same coordinates in our second image, and that color is directly translatable to a game area, since each area is painted in its own color.

Is that a good implementation? Can you suggest better, if it isn't?

Best regards.

# Answer
> 0 votes
Better to skip the image and just have a 2D array of pointers which indicate what game area it is. Since the second image is never displayed there's no reason for it to contain visible colours.

---
Tags: maps
---


title: Scale DIV with tiles

text:
# Question
Title: Scale DIV with tiles
I am trying to create a repeating background. I have a main DIV with a grid of small 16x16 DIVs. I am trying to scale the main DIV in CSS; when the small DIVs simply have a red background color everything works great, but when there is a background image in the small DIVs then borders become visible between the tiles.

This image explains the problem: http://cl.ly/FpNW/o

**Check the HTML in these examples:**

With BG-COLOR: http://jsfiddle.net/pTLXw/

With BG-IMG: http://jsfiddle.net/vkpuY/

Does anyone know what is causing this problem and how to fix it? If it is not possible to fix while using DIV, is there another way to do this?

Thanks you so much!

# Answer
> 1 votes
It's a result of the different scaling methods used by the different browsers. I'd generally stay away from using that scaling, but if you want your current problem solved, have the tiles overlap slightly.

---
Tags: tiles, html5, web
---


# Question
Title: Do open world games need less backstory?
I've played a few open-world games and really enjoyed them, though the ones I've really enjoyed have generally received complaints about how little story there is to them.

*The Saboteur* is one example of this. Fully open-world, good enough story (for me, anyway), engaging gameplay, and still has received complaints in reviews about not having enough story.

Do open-world games actually need a full, all-encompassing story? Or can fun and engaging gameplay fill in the gap and let the designer get away with a slightly less complete story?

# Answer
There is no genre that requires an all-encompassing story to be good or even great.

In the platformer genre there is Mario, no story, great game. But there is also Braid and depending on your taste you might like one or the other better.

In shooters there is Counter-Strike and there is Deus Ex, again great games, one doesn't even pretend to have a story, while the other has you undergo several changes, reinvent yourself as a character and make moral choices.

Same goes for all the other genres. What is a problem though is that some games pretend to have a deep story, but in the end they come out lacking. A good recent example of that is the singleplayer of BF3, it's fun but the story telling happens in cut scenes, gets you out of the flow and isn't really interesting. It's gets in the way of the mechanics and makes the game feel less rich instead of richer. (But then again, who plays BF3 for the singleplayer?)

A game can be good by having fun mechanics that are easy to learn and hard to master, visuals that fit the scene and are coherent (note that I don't say photorealistic or anything) sound and music to complement the experience and level design that draws you through the game and keeps giving you new and exciting ways to use and master the mechanics.

Now a story can add to this, a great story will keep you playing longer, have you feel more engaged and it makes the experience richer. Would the Mass Effect series be so much fun if we cut away all the storytelling? I don't think so, especially in ME1 the part where you actually play were a bit boring sometimes, but the story telling made the world come to life and made me invested in the success of the mission this made the game much better.

Storytelling is also a way to make the game more actual. One of the greatest examples of this is the GTA series, especially GTA IV was filled with story telling elements that have us look back at our society and the problems there in. Sometimes I just drove around looking at the world and listening to the talk shows on the radio, contemplating what was being told there. This experience is something mechanics alone can never deliver (although they can try and help)

However there is a dark side to this, some games forget that they are a game and try to be a movie or a book this can lead to problems since you don't feel like playing a game anymore since you have no impact on what happens. But even very story heavy games can achieve greatness, see Heavy-Rain as an example.

So to answer your question, no a great (open world) game doesn't need story at all.

It's a common complaint though in open-world games because story telling in open world games is quite hard since players do not follow a linear path. Games like GTA III~IV use tricks to make the game feel open but still have missions that are important to the story appear in a linear order thus giving both the sense of freedom as the above described pros of a story.

Btw if you are as interested in this kind of stuff as I am, I recommend you start watching the Extra Credits webcast, maybe start here? http://extra-credits.net/episodes/enriching-lives/
> 8 votes

# Answer
They may not need as much back story as they do situations and things that make sense - or maybe they really need both hand in hand. It's fine to put a band of goblins in the hills outside a village, but you can expect that this means they have raided the village, or that they haven't yet and the villages are concerned. Or maybe there's an old goblin cave outside the village, now abandoned - which implies the goblins left or were killed off - and therein is a story.

A well done sandbox world with its own dynamic modelling of the environment in a way just tells it's own story without your intervention. Maybe once a month there's a chance that a pack of wolves come in from the cold north (which is off the map). If they do, you've got a story, because those wolves are going to interact with the local inhabitants (human and otherwise) either directly or indirectly.

You should check out the Storybricks project at http://www.storybricks.com \- they have some really intriguing ideas about laying down the rules of relationships between game entities, and allowing the stories to flow from that.

Also, check out Dwarf Fortress at http://www.bay12games.com/dwarves/. Procedural and "random", yet clearly there is a story to tell at the end of a game. Take a look at this really sweet set of graphics someone did that illustrated a the story behind a basically procedural Dwarf Fortress game's battle report -\> http://www.nzfortress.co.nz/forum/showthread.php?t=20768
> 3 votes

# Answer
Create the game, and then make the story around the game. Just use the story as an excuse to make your players explore your open world. For example, if I enter this huge open world and don't know what I am doing, I may just bore myself, stop exploring, and set down the controller, but if I need to find the, say, three spiritual stones in locations marked on the map, it will give me an incentive to explore. Since I have a clear destination, along the way I'll run into things and think, hey, I should go check that out. Stories don't have to make sense, they just need to give the player a reason to play.
> 1 votes

---
Tags: game-design, open-world
---


# Question
Title: Writing a dynamic achievement system without hardcoding rules into the application
I really enjoyed the solution provided here for groundwork on writing an achievement framework. The problem I have is I have game designers that would like to be able to insert achievements into a CMS at runtime. In a way, it sounds insane and complex to do this, but is it really? I think the concept of having to do a hard push of the application for every new achievement is cumbersome. I would love to be able to give our designers the capability to put together new achievements by entering them into a database. It shouldn't matter what tool I'm using, but for those interested, my backend is being written in JRuby (Ruby on top of the JVM). What are some possible ways of going about abstracting the logic in the aforementioned link even further so that rules can be interpreted at runtime?

# Answer
Break it down into concrete systems, an achievement is abstract, but an achievement to gather/do/kill/rescue/stalk X amount of T can be represented as an instance of an achievement with a predicate.

So essentially any achievement could be represented by a function, and a set of attributes.

If you want to enable arbitrary achievements you're talking about scripting in some form; represented as an AST or a runtime language, which is a major over kill IMO, as it introduces unnecessary complexity.
> 1 votes

# Answer
Instead of hardcoding rules in the game, just hardcore metrics recording, statistics.

The achievements are only values of statistics that have to be matched to generate a "reward", or preferably, they are remarkable statistics.

So what you need is only recording actions and events that are important in your game and then think later about what to make an achievement about.

Then have a way to setup rules applied to those statistics, to trigger the achievements. Maybe some scripts to call sometimes, that would do the checks, or maybe a simple rule system where you set boundaries of specific statistics to be matched to trigger the achievement.
> 0 votes

---
Tags: game-design, architecture, achievements
---


# Question
Title: How do I make an area in the screen clickable with XNA?
I am programming a penalty shoout game, my question is how make an area in the screen clickable with XNA? I know that for seeing the mouse I have to use:

```
this.IsMouseVisible = true;

```

But I want this for the direction of the soccer ball? Any ideas?

I want something like this or this but I don't find anything about this in XNA.

# Answer
You will have to do a couple of things, you have to detect if the mouse button was clicked. You do this by checking if it wasn't pressed the previous frame and is pressed currently.

Then you have to get the mouse position and check if that position was inside the clickable area. You can use a simple rectangle as the clickable area.

Anyway it would in XNA lead to code something like this:

```
MouseState prevMouseState;
MouseState mouseState = Mouse.GetState();
Rectangle clickableArea = new Rectangle(10, 10, 500, 500);

    public void DetectClick()
    {
        if (mouseState.LeftButton == ButtonState.Pressed && prevMouseState.LeftButton == ButtonState.Released)
        {
            // We now know the left mouse button is down and it wasn't down last frame
            // so we've detected a click
            // Now find the position
            Point mousePos = new Point(mouseState.X, mouseState.Y);
            if (clickableArea.Contains(mousePos))
            {
                // Yay there was a click inside the clickable area
            }
        }

        // Store the mouse state so that we can compare it next frame
        // with the then current mouse state
        prevMouseState == mouseState;
    }

```
> 2 votes

---
Tags: xna, xna-4.0
---