title: Building a shape out of two rectangles

text:
# Question
Title: Building a shape out of two rectangles
I would like to build a body with Farseer out of two rectangles so it looks like this:

I am a real beginner, so please describe it carefully.

Thanks in advance!

# Answer
There are two ways you can do this:

**1. With Fixtures**
I recommend doing it this way as it's much easier to manage. Here's the code with comments:

```
//Create the initial body + 1 fixture in the shape of a rectangle
// The fixture is 2 world units wide and 1 world unit high
Body body = BodyFactory.CreateRectangle(world, 2, 1, density);
//Create a new fixture on the body.
body.CreateFixture(
    //The new fixture is a PolygonShape (CreateFixture accepts a Shape parameter)
    new PolygonShape(
        //This method returns a list of vertices which represent the shape of the fixture.
        //  Note the parameters are HALF width/height and that we've set
        //  it up so it's already "rotated".
        PolygonTools.CreateRectangle(0.5f, 1)
    , density));
//Set up body data
body.BodyType = BodyType.Dynamic;
//Etc...

```

*Note: I've spanned some lines in order to explain what's going on, you obviously don't need to do this.*

**2. With Bodies**
You should also be able to weld two bodies together like this:

```
//Create the first body with a width of 3 and height of 1
Body part1 = BodyFactory.CreateRectangle(world, 3, 1, density);
//Create the second body
Body part2 = BodyFactory.CreateRectangle(world, 3, 1, density);
//Rotate the body by pi / 2 radians (90 degrees)
part2.Rotation = MathHelper.PiOver2;
//Use a weld joint to stick them together
JointFactory.CreateWeldJoint(world, part1, part2, Vector2.Zero, Vector2.Zero)

```
> 1 votes

# Answer
You should be able to create a Body with 2 Fixtures attached if Farseer follows what Box2D does.

I've never used Farseer but the following is what can be done in Box2D and there should be something similar in Farseer:

Create 2 PolygonShapes using function below

```
void SetAsBox(float32 hx, float32 hy); //default centers each fixture at center of body

```

For example `tallRect` and `wideRect` are PolygonShapes

```
tallRect.SetAsBox(1,2);
wideRect.SetAsBox(2,1);

```

Create two Fixtures, one for each shape and attach both shapes to your Body using

```
myBody.CreateFixture(a);
myBody.CreateFixture(b);

```

I created something like this:
> 1 votes

---
Tags: xna, c#, xna-4.0, physics, farseer-physics-engine
---


title: Linear search vs Octree (Frustum cull)

text:
# Question
Title: Linear search vs Octree (Frustum cull)
I am wondering whether I should look into implementing an octree of some kind.

I have a very simple game which consists of a 3d plane for the floor. There are multiple objects scattered around on the ground, each one has an aabb in world space.

Currently I just do a loop through the list of all these objects and check if its bounding box intersects with the frustum, it works great but I am wondering if if it would be a good investment in an octree. I only have max 512 of these objects on the map and they all contain bounding boxes. I am not sure if an octree would make it faster since I have so little objects in the scene.

# Answer
http://publications.dice.se/attachments/CullingTheBattlefield.pdf

Linear brute force frustum culling is...

**Simpler:**

* Easier to code
* Easier to debug
* Easier to maintain
* Easier to optimize

```
/**
 * Returns wheter the given sphere is in the frustum
 * @param center The center of the sphere
 * @param radius The radius of the sphere
 * @return Wheter the sphere is in the frustum
 */

public boolean sphereInFrustum(Vector3 center, float radius) {
    for (int i = 0; i < 6; i++)
        if ((planes[i].normal.x * center.x + planes[i].normal.y * center.y + planes[i].normal.z * center.z) < (radius + planes[i].d))
            return false;
    return true;
}

```

**Faster:**

* Easier to multithread
* Memory is bottleneck

512 is so little amount of objects that you are just wasting your time to even thinking this problem. My java implementation use about 2ms for 1000 objects on cheap android phone. Just testing against bounding sphere is good enough and lot simpler.

Code: http://pastebin.com/7i4wknx7
> 5 votes

# Answer
If your game is going to remain a game with just a 3D plane, you could simplify by using a quad-tree instead of an octree. However, an octree will cover all the bases, in case you decide to have things that fly, or decide not to have only a 3D plane for the ground.

An octree will almost certainly make things faster if you have 512 of those objects in existence all at one time (unless they're all very close to each other), especially if you're not batching your drawing of those objects, 512 draw calls is quite a bit for most devices. Since you've not asked, I'll assume you understand how an octree works and won't explain the details. Long story short, you should be able to check the camera frustum against the root of the octree, and then against that node's child nodes, and through recursion keep going until you reach the leaf nodes (nodes with no children of their own).

One thing to keep in mind is the size you want the smallest nodes to be. Too many subdivisions will use more memory and will result in too many frustum\<-\>AABB checks which will end up being slower than the 512 draw calls would. For example I use a quad-tree in my engine, and in a 4096x4096 map I found that 512x512 was the optimal smallest size. This resulted, in my case, in a tree that had a depth of 4. I would recommend tweaking the minimum size until you find the sweet spot for performance.
> 0 votes

# Answer
Octrees aren't the only way of handling spatial partitioning. If your objects are static - which it sounds like they might be - then you may be better off not using an octree but instead using a hierarchy of bounding volumes. And even if they're dynamic, you don't necessarily need a full octree; you can go down to a *quadtree*, the two-dimensional version, and treat all boxes (for purposes of the spatial partitioning) as having the same height.

As for whether it's worth it, a lot of that depends on just what you're intending to do; 512 objects is few enough that individual frustum culling is probably fine, but you may find yourself wanting the spatial partition for other reasons (for instance, for object interaction).
> 0 votes

# Answer
I would like to emphasize that you should only optimize when you need to. If your game is simple enough perhaps you don't need to cull anything. If the game is small enough having an octree could actually make your game slower. Is speed really an issue for you? Then why? Try running a profiler and see where all the time spent is and really analyze why that might be the case. If culling is than an issue try the simple solution (linear search), then do the octree after that. This should help you get your game out faster as well.

You would be adding the extra steps of checking the octree, moving the objects from octree to octree, handling weird cases like objects being on both sides of an octree.

Lastly, I'd recommend finding an octree implementation with unit tests and such. It isn't super easy to implement (as I remember) and there are a good amount of corner cases.
> 0 votes

---
Tags: opengl, culling, frustum
---


# Question
Title: How to improve collision detection memory usage?
I am making an action platform 2D game, something like Megaman. I am using XNA to make it.

I already made player physics, collisions, bullets, enemies and AIs, map editor, scrolling X Y camera (about 75% of game is finished ). As I progressed I noticed that my game would be more interesting to play if bullets would be destroyed on collision with regular(stationary) map blocks, only problem is that if I use my collision detection (each bullet with each block) sometimes it begins to lag(btw if my bullet exits the screen player can see it is removed from bullet list)

So how to improve my collision detection so that memory usage would be so high? :) ( on a map 300x300 blocks for example don't think that bigger map should be made);

```
            int block = 0;
            int bulet= 0;
            bool destroy_bullet = false;

            while (bulet < bullets.Count)
            {
                while (block <  blocks.Count)
                {
                    if (bullets[bulet].P_Bul_rec.Intersects( blocks[block].rect))
                    {//bullets and block are Lists that holds objects of bullet and block classes
                        //P_Bul_rec just  bullet rectangle

                        destroy_bullet = true;
                    }
                    block++;
                }
                if (destroy_bullet)
                { bullets.RemoveAt(bulet); destroy_bullet = false; }
                else { bulet++; }
                block = 0;
            }

```

# Answer
Your collision detection is slow because you're checking for collisions between every bullet and every block, even if they're nowhere near one another. You should implement a space-partitioning scheme such as a quadtree. This will greatly minimize the number of potential collisions you have to detect, and should keep things at a playable speed.

Here's an article that talks specifically about using Quadrees in XNA.
> 5 votes

# Answer
I don't think a Quadtree is necessary, since you already have the blocks/map grid. Basically convert the bullet coordinates to grid coordinates (aka position divided by block size) and then check collisions only with blocks that are near it. I guess you could also check it based on velocity of the bulled (if +x/+y then check only blocks that are forward or upward of the bullet and so on).
> 1 votes

---
Tags: xna, 2d, collision-detection, game-mechanics, tilemap
---


title: Recording equipment for game sounds

text:
# Question
Title: Recording equipment for game sounds
I was wondering if anybody knows about any good pieces of equipment fit for recording sound effects for games. If you can, also tell please me the price range for professional equipment.

# Answer
> 11 votes
Recording sound effects is an expensive process, and requires sound-proofing, expensive equipment and professional actors / real life objects.

Game studios and Film studios generally have huge sound banks from which they take basic sounds and mix, filter, compress and generally manipulate the basic sounds to their needs.

The Wilhelm Scream is a great example of re-use of sound effects in films: I never noticed it until I saw this video and now I hear it everywhere!

I believe that a lot of the work a Sound Designer has to do is find the right sounds from a sound bank and mess about with them until they're perfect for the game. This is why I think that with any basic recording equipment you could start recording and just use noise filters and compression to get some ok quality sounds. If you're starting off the best thing to know is how to use filters and apply sounds to a certain situation.

Software-wise I know SoundForge is widely used for sound editing, I really think it's a great, but expensive tool. For other software you can search the site, but Audacity is a good free sound editing tool.

Equipment-wise you'd be best going to a local store and asking for professional advice; the price is dependant on your budget and the target of what you want to do exactly.

# Answer
> 1 votes
To record sound effects, you need a decent recording device and microphone. You **do not need to spend a lot of money**. For example, here is a nice Tascam stereo mic for iPhone around $69 dollars. Couple that with a good audio editor on a computer or iPhone and you are ready to go. Companies like Blue Microphones also make inexpensive high quality microphones and audio interfaces for PC or Mac which you can use to record your sounds.

---
Tags: audio, sound, sound-effects
---


# Question
Title: Connecting tiles to make a large image based on text file
If I am building my level from a text file

```
0,0,0,0,0
0,1,0,1,0
0,2,1,0,0
0,0,0,0,0

```

and I want to draw a large image, how do I go about doing that? do I take the image, separate it in tiles (the same size as the other ones) and then add a value to each image

```
0,1,2,3,4,5,6
0,7,8,9,10,11,12

```

or is there another way to do this? Lets say I want to add a house, or a something like this ship?

# Answer
> 3 votes
Old-school RPG engines like that typically render 2 or more layers of tile maps, f.e.:

* Ground layer (below sprites; roads, floor, etc.)
* Upper layer (above sprites; stuff in front; the upper part of the ship in your image)

This allows sprites to walk behind stuff on the upper layer. So in your text file, you'd define 2 layers per tilemap, f.e.:

```
// ground layer
1,1,1,1,1,
1,2,2,1,1,
1,2,2,1,1,
1,1,1,1,1,

// upper layer
0,0,0,0,0,
0,3,0,0,3,
0,4,3,0,0,
0,0,0,0,0

```

(I'd recommend using 0 as "no tile")

---
Tags: tiles, art, tilemap
---


title: What is the kd tree intersection logic?

text:
# Question
Title: What is the kd tree intersection logic?
I'm trying to figure out how to implement a KD tree.

On page 322 of "Real time collision detection" by Ericson

The text section is included below in case Google book preview doesn't let you see it the time you click the link

text section

Relevant section:

> The basic idea behind intersecting a ray or directed line segment with a k-d tree is straightforward. The line is intersected against the node's splitting plane, and the t value of intersection is computed. If t is within the interval of the line, 0 \<= t \<= tmax, the line straddles the plane and both children of the tree are recursively descended. If not, only the side containing the segment origin is recursively visited.

So here's what I have: (*open image in new tab* if you can't see the lettering)

The logical tree

Here the orange ray is going thru the 3d scene. The x's represent intersection with a plane. From the LEFT, the ray hits:

* The front face of the scene's enclosing cube,
* The (1) splitting plane
* The (2.2) splitting plane
* The right side of the scene's enclosing cube

But here's what would happen, naively following Ericson's basic description above:

* Test against splitting plane (1). Ray hits splitting plane (1), so left and right children of splitting plane (1) are included in next test.
* Test against splitting plane (2.1). Ray actually hits that plane, (way off to the right) *so both children are included* in next level of tests. (This is counter-intuitive - shouldn't only the bottom node be included in subsequent tests)

Can some one describe what happens when the orange ray goes through the scene correctly?

# Answer
It's pretty simple really; the test against splitting plane (2.1) should fail, because of the following:

When the ray hits splitting plane (1), you "split the ray", or; you set the `t`-range for which it is valid, and continue down the tree with the resulting parts.

Thus, when checking against plane (2.1), you should be checking if only the part of the ray left of plane (1) intersects with plane (2.1), which it doesn't. The "far off to the right" intersection you speak of has a `t` \> the `t` value where you split the ray with plane (1).

I hope that's clear enough.

Summary: Subsequent ray/plane intersections should be done only with the part of the ray remaining after splitting it with the plane in question.
> 14 votes

---
Tags: space-partitioning, kd-tree
---


# Question
Title: How to decompose a rectangular shape in a Voronoi diagram, only generating convex shapes?
I think this is a very straighforward question, lets say i have a building in 2D, a rectangle shape. Now i want to decompose that area in a lot of convex shapes, as seen in a voronoi diagram, or closely like it, just so I can add those shapes to the physics engine, and have a realistic destruction.

Bonus: Possible suggestions on how to make the effect more dynamic and interesting.

Please keep in mind we re talking about realtime calculations..

# Answer
Well, you could literally generate a Voronoi diagram. That is, produce some random points in the rectangle, find their Delaunay triangulation (google for the algorithms for this), then generate the Voronoi polygons from the triangulation. The Delaunay triangulation is the dual graph of the Voronoi diagram, so there will be one Voronoi vertex for each triangle, with the Voronoi edges running perpendicular to the triangle edges.

That sounds heavyweight, but it depends on how many pieces you want each building to break into and how often you need to break a building. You might spread the computation across multiple frames or something, if it causes too much of a spike.
> 2 votes

---
Tags: procedural-generation, procedural-destruction
---


title: Swept AABB vs Line Segment 2D

text:
# Question
Title: Swept AABB vs Line Segment 2D
I've really exhausted as much as Google has to give, I've spent a solid week googling every combination of words for an "AABBvsLine sweep", downloaded countless collision demos, dissected SAT intersection examples and an AABBvsAABB sweep trying to figure out how to approach this. I've not found a single thing covering this specific pairing.

Can anyone shed any light on how to get the **hit time** of a swept AABB vs a Line segment in 2D? I'm still getting familiar with the SAT but I do know how to implement it to a degree, I'm just not sure how to extract the hit time from the velocity in the non axis aligned separating axes for the sweep.

I really would appreciate anything at the moment, some code or even some helpful links, I'm at my wits end!

# Answer
After a gruelling mind destroying week working on this, I managed to figure it out by myself, I would have killed for some help online somewhere, there is so little information on swept checks on anything but an AABB.

Wish I didn't have to answer my own questions on here, a few minutes from someone could have saved me days on this bloody nightmare.

Anyway! :p

What I did,

First I calculate an AABB constructed from the extents of the line segment.

I then calculate the radius of the Box in respect to the line direction. (covered in Gomez's simple intersection for games article)

Following that I projected a vector from the line to the Box and the velocity onto the normal of the line segment, I then divide the distance projection by the velocity projection for the velocity intersection. For the first hit time I minus the radius from the distance projection and for last hit time I add the radius.

I also had to add a small check for when the velocity is facing away from the line to flip the Box's radius calculation (sign flipping error).

After that I run a standard AABBvsAABB sweep against an AABB constructed from the extents of the line segment. (Christer Ericson's AABB sweep)

Here's my code.

```
private bool SweepBoxLine( Box a, Line l, Vector2 v, out Vector2 outVel, out Vector2 hitNormal  )
{
    Vector2 lineDir = l.b - l.a;
    Vector2 lineMin = new Vector2(0,0);
    Vector2 lineMax = new Vector2(0,0);

    if(lineDir.x > 0.0f) //right
    {
        lineMin.x = l.a.x;
        lineMax.x = l.b.x;
    }
    else //left
    {
        lineMin.x = l.b.x;
        lineMax.x = l.a.x;
    }

    if(lineDir.y > 0.0f) //up
    {
        lineMin.y = l.a.y;
        lineMax.y = l.b.y;
    }
    else //down
    {
        lineMin.y = l.b.y;
        lineMax.y = l.a.y;
    }

    //Initialise out info
    outVel = v;
    hitNormal = new Vector2(0,0);

    float hitTime = 0.0f;
    float outTime = 1.0f;
    Vector2 overlapTime = new Vector2(0,0);

    float r = a.extent.x * Mathf.Abs(l.n.x) + a.extent.y * Mathf.Abs(l.n.y); //radius to Line
    float boxProj = Vector2.Dot(l.a - a.center, l.n); //projected Line distance to N
    float velProj = Vector2.Dot(vel, l.n); //projected Velocity to N

    if(velProj < 0f) r *= -1f;

    hitTime = Mathf.Max( (boxProj - r ) / velProj, hitTime);
    outTime = Mathf.Min( (boxProj + r ) / velProj, outTime);

    // X axis overlap
    if( v.x < 0 ) //Sweeping left
    {
        if( a.max.x < lineMin.x ) return false;
        hitTime = Mathf.Max( (lineMax.x - a.min.x) / v.x, hitTime);
        outTime = Mathf.Min( (lineMin.x - a.max.x) / v.x, outTime);
    }
    else if( v.x > 0 ) //Sweeping right
    {
        if( a.min.x > lineMax.x ) return false;
        hitTime = Mathf.Max( (lineMin.x - a.max.x) / v.x, hitTime);
        outTime = Mathf.Min( (lineMax.x - a.min.x) / v.x, outTime);
    }
    else
    {
        if(lineMin.x > a.max.x || lineMax.x < a.min.x) return false;
    }

    if( hitTime > outTime ) return false;

    // Y axis overlap
    if( v.y < 0 ) //Sweeping down
    {
        if( a.max.y < lineMin.y ) return false;
        hitTime = Mathf.Max( (lineMax.y - a.min.y) / v.y, hitTime);
        outTime = Mathf.Min( (lineMin.y - a.max.y) / v.y, outTime);
    }
    else if( v.y > 0 ) //Sweeping up
    {
        if( a.min.y > lineMax.y ) return false;
        hitTime = Mathf.Max( (lineMin.y - a.max.y) / v.y, hitTime);
        outTime = Mathf.Min( (lineMax.y - a.min.y) / v.y, outTime);
    }
    else
    {
        if(lineMin.y > a.max.y || lineMax.y < a.min.y) return false;
    }

    if( hitTime > outTime ) return false;

    outVel = v * hitTime;

    return true;
}

```

I'm pleased that it came out with only simple float comparison and just two dot products, nice and fast! I hope it helps someone as hopelessly stuck as I was!
> 6 votes

# Answer
This should be equivalent to testing the ray of the AABB path against the Minkowski sum of the line segment and the AABB. The Minkowski sum in this case should be pretty simple - it's a convex polyhedron formed by sweeping the AABB from one endpoint of the segment to the other.

Once you can figure out the planes that define the polyhedron, you can use e.g. 5.3.8 from Christer Erison's RTCD book. The hit fraction from the raycast is the same as the hit fraction for the AABB cast.
> 4 votes

---
Tags: collision-detection
---


title: 2D non-tile based map editor

text:
# Question
Title: 2D non-tile based map editor
I am currently developing a relatively simple 2D, topdown oriented adventure game for the iPhone and was wondering what would be the easiest way to create the maps for my game. I figured I would need some kind of visual editor that would give me immediate feedback and would allow me to place all objects in the world exactly where I want them. I could then load the saved representation of the world I create in the editor in my game.

So, I am looking for a simple map editor that allows me to do this. All the objects in my game are simply textured rectangles build up from two triangles. All I need to be able to do is position different rectangles/objects in the map, and give them a texture. I am using texture atlases, so it would be useful to be able to assign portions of textures to the objects. I then need to be able to extract all the objects from the saved representation of my maps, together with the name/identifier of the texture(atlas) they use, and the area of the texture atlas.

I have looked at some tile-based map editors like Tiled and Ogmo, but they don't seem to be able to do what I want. Any suggestions?

EDIT: a more concrete example: something like the GameMaker level editor, but then with added export functionality in a handy format.

# Answer
> 9 votes
Try Gleed. From its site:

> GLEED2D (Generic LEvel EDitor 2D) is a general purpose, non tile-based Level Editor for 2D games of any genre that allows arbitrary placement of textures and other items in 2D space. Levels are saved in XML format. Custom Properties can be added to the items in order to represent game-specific data/events/associations between items etc. Check the video tutorials under the Documentation tab to get an idea of its powerful features.

# Answer
> 3 votes
If you haven't already read it, I'd recommend reading this, gives some ideas of how non-tile-based 2D can be done very effectively:

http://www.davidhellman.net/blog/the-art-of-braid-index/

You could also take a look at the Aquaria source code, and see if its editor is adaptable to your needs (that used a mix of tiles and arbitrary object placement)

I've been working on a non-tile-based editor myself (screenshots: http://www.bluescrn.net/projects/twodee6.png , http://www.bluescrn.net/projects/twodee4.png), but it's still very much a work-in-progress.

# Answer
> 2 votes
Offhand, I don't know of any game-agnostic editors aimed at this task. However, you could consider using any existing paint program (Photoshop, GIMP, Paint.net, Acorn, Pixelmator, et cetera) that supports layers, build each level sprite in its own layer, then simply saving each layer individually to some directory, and then writing a tool to post-process that directory to isolate the position and bounds of each image within the layer file, save out that position and bounds information, and slice up the layer and re-composite all of them back on to a texture atlas.

Fundamentally that algorithm isn't any different than what a dedicated tool would be doing, and if you can do it on a bunch of distinct image files you can do it on images in memory -- in other words, it might not be terribly complex to write your own simple tool that does this after you get the basics of the process down using a paint program.

One problem might be if your levels are huge, editing them in a paint program might not be pleasant depending on the power of your machine. But for iPhone-game style levels I suspect you'd be fine.

# Answer
> 0 votes
I've recently released a non tile based level editor for iPhone and Android. It has in built physics simulation for testing and can load game elements from SVG or by tracing PNG images. For your game you could just import rectangular PNGs and position them where you wanted. The level designer produces a config file and a packed sprite sheet (optional) which can be exported straight to XCode (code is supplied to read the config file). It's pretty simple but very flexible. The program's called Shape Workshop and can be downloaded here.

---
Tags: 2d, iphone, maps, levels, editors
---


# Question
Title: Calculating instantaneous speed and acceleration for a simple car software model
I am trying to model a speedometer and tachometer for a simple software model of a car dashboard. I want this to be relatively simple, so for my purposes I won't likely simulate variables such as drag (or, assume that drag is a constant). But I would like to know the general formulas for:

1) Calculating the RPM, depending on a position of a graphical slider representing the accelerator.

2) Using this information to find the instantaneous speed (or, magnitude of instantaneous velocity?).

I am not sure, in the case of 2), what other independent variables I need to consider. Do I need to consider the frequency of rotation of the wheels (assuming a fixed radius), in addition to the RPM?

If anyone can give me a rough explanation plus relevant formulas, or alternatively direct me to other trusted resources online (I have had a hard time sifting through info and determining the accuracy), it would be much appreciated.

# Answer
> 1 votes
It sounds like your simulator consists of an accelerators and the feedback of the tach and speedometer and these are connected together through the model of the accelerating car. Let's neglect tires slipping. The accelerator induces a power that generally depends on the engine speed. Let the car have about one hundred horsepower which is 7500 watts of power and you could just scale this linearly with engine speed afer reading about that online.

look here to convert the horsepower to torque and then use the torque and force relation involving the radius of the tire to get the linear force acting on the car due to to the tires. Chose a sensible mass for the car and get your acceleration. From there you just use kinematic equations to get the speed which you would display at the speedometer. You will also have to model the drive train and gear ratio it seems.

It's possible that there is just a linear relationship between the tach speed and the car speed. That's probably the gear ratio.

---
Tags: physics
---


# Question
Title: Multiple render targets and pixel shader outputs terminology
I'm a little confused on the jargon: does Multiple Render Targets (MRT) refer to outputting from a pixel shader to multiple elements in a `struct`? That is, when one says "MRT is to write to multiple textures", are multiple elements interleaved in a single output texture, or do you specify multiple discrete output textures?

By the way, from what I understand, at least for DX9, all the elements of this struct need to be of the same size. Does this restriction still apply to DX11?

# Answer
Multiple discrete output textures. You'd set up several individual render targets, each in exactly the same way as you set up one render target, then specify a list of them rather than a single one when you bind them to be drawn to.

In DX11, the render targets can be different formats and color depths. I'm not aware of any restrictions on this. You can e.g. use floating point render targets together with 8-bit integer ones. However, all the render targets must have the same pixel dimensions, e.g. 1280x720.
> 1 votes

---
Tags: directx, fragment-shader, multiple-render-targets
---


title: Rotate point by a direction vector

text:
# Question
Title: Rotate point by a direction vector
Given a vector, A, which represents a point, and a unit vector, B, which represents the looking direction, how would I rotate A so that B is the axis that's looked down on? Let's say the looking-axis is originally (0,0,1) and I want it to become B by rotating A accordingly. So it needs to rotate by (0,0,1) - B.

# Answer
> 3 votes
You can directly construct a look-at matrix without using trigometry (but using vector math). First, you need an up-vector to specify which direction should be up from the camera's point of view. This would typically be (0, 1, 0) or (0, 0, 1), depending on your choice of coordinates.

Then, you can calculate the orthonormal basis for your camera:

```
float3 right = normalize(cross(dir, up));
float3 upTrue = normalize(cross(right, dir));

```

Beware! If `dir` is parallel or antiparallel to `up`, this will break.

Then, you can construct the (left-handed) camera-to-world matrix by shoving `right`, `upTrue`, and `dir` into the first three rows (if using row vectors) or columns (if using column vectors) of a 4x4 matrix. Put the camera position into the fourth row/column.

Then calculate the inverse of this 4x4 matrix to get the world-to-camera matrix. If you just need the rotation part, use a 3x3 matrix, and you can take the transpose instead of doing a full inverse.

This matrix can then be used as a view matrix in a 3D graphics engine, or you can transform a point yourself by multiplying with this matrix.

# Answer
> 1 votes
Given direction as `d` and point as `p`

```
d = normalize(d);
double yaw = Math.Atan2(d.X, d.Y);
double pitch = Math.Atan2(d.Z, Math.Sqrt((d.X * d.X) + (d.Y * d.Y)));
p.rotateXYZ(pitch, yaw, 0); //Roll == 0

```

Well, this should do :)

---
Tags: 3d, graphics, vector
---


title: How to change speed of passage of time?

text:
# Question
Title: How to change speed of passage of time?
I have begun creating a very simple game engine and I am trying to work out how to create a time scale for the game. By time scale I mean some way of increasing and decreasing the speed of the game (not the fps) like creating a slow motion effect.

I have no idea how this could be accomplished so any help would be appreciated.

If this helps I'm using windows, OpenGL, and C++ to make my game engine.

How my engine is setup:

I have an update and draw function. The update function is called 25 times per second while display is called as much as possible.

# Answer
> 8 votes
I'm not sure about the architecture of your game, so what's follow is a rather generic answer. Usually there are two different 'rates' in the game - the screen refresh or draw rate, and the logic update rate.

The draw rate is the FPS - some game engines will try to draw as often as possible, while others will try to draw at a fixed rate. Regardless, it is not a good idea to tie logic updating to the draw rate of your game.

Most game engines instead will have a update loop, which is governed by the logic update rate. This is the rate you you to speed up, slow down, or pause the game. To pause, you simple stop updating. To slow down, you increase the time between each update, and so on.

As an example, Unity3D has a variable called `Time.timeScale`, which affects the `Time.deltaTime` variable used by all most logic functions to determine the elapsed time each frame. By setting the time scale to 1.0f, the game runs at normal speed. Setting it at 0.5f will run it half the speed.

# Answer
> 1 votes
I guess the easiest way is to change delta\_time value you pass to your update functions, for example if you tell your update function that the last frame took 1/120s but having 1/60s for a real frame, it makes your game to update half normal speed (it doesn't affect controls but may cause some side effects like delaying buttons and etc.)

# Answer
> 0 votes
In Ogre3D, and I suspect many other engines, you'll get a callback when the latest frame has been queued to render. This can be (and often is) your source for relaying "time" to the rest of your application.

```
void frameRenderQueued(FrameEvent ev)
{
   double scaledTime = ev.timeSinceLastFrame * MY_TIME_SCALE;

   // Stuff that needs scaled time
   myAnimationManager->addTimeToAllAnimations(scaledTime);
   myParticleEffectsManager->addTimeToAllParticleEffects(scaledTime);
   myBuffManager->addTimeToAllBuffs(scaledTime);

   // Stuff that doesn't need scaled time
   myPopupManager->addTimeToPopups(ev.timeSinceLastFrame);
}

```

In the above code, you can see that you can pass scaled time along to the things you want to slow down (animations and such, and if your game operates in "real time", any effects like buffs that are designed to last a certain amount of time in-game), but use the unscaled time for things that you wouldn't expect to be affected, like a pop-up in your UI and such.

# Answer
> 0 votes
Assuming you use a delta time for updating. Just multiply it by a scalar modifier that reflects how fast or slow you want time to progress. For example, 1.0 for standard speed or 0.5 for half.

```
modifiedDeltaTime = deltaTime * scale;

```

---
Tags: c++, game-mechanics, game-loop
---


# Question
Title: What are some free online game design courses?
I have an MComp in Computer Science. I would like to specialize in game programming. What online free video game design courses are there? I as thinking something similar to coursera.org

# Answer
If you meant "design code for games" it's time to leave the classroom behind and just start writing; while there are broad guidelines on "how things are done" each game is basically a little R&D project of "how things are done for this game here." All a game programming course would teach you is how to program and you already know that.

There's also plenty of open sourced games out there to examine.

If you're talking about designing gameplay, systems or building levels the same advice applies, just start designing, with the exception that your R&D consists of playing other games critically and tearing their guts open to see how their systems work.

The answer here is that since you have a background already you are your own best teacher on how to apply what you know to the problem at hand.
> 2 votes

---
Tags: assets
---


# Question
Title: Can I animate render targets or the swap chain?
I want to animate some synthetic video bits to fullscreen w/o tearing. Can I set up D3D 9/10/11 in exclusive mode, and have it present a series of buffers that I'm writing to?

I know how to copy system memory bits into a texture, then draw that texture as a fullscreen quad, but it seems like overkill. Why should I use the triangle rasterizer when I want to do something so simple?

All I want to do is set up a long (4-8 buffer) swapchain and set the bits of the back buffer that is about to be displayed. Or, I want to allocate 4-8 RenderTargets, and on each frame, copy the bits from system memory to the RenderTarget, then set it as the next thing to display. I've never seen or heard about anybody doing this, but it seems so dead simple!

# Answer
Direct3D is not a video playback API, it's an API for doing hardware-accelerated rendering of 3D primitives.

You certainly could do what you are proposing -- create a bunch of textures, copy your frame bits into them, and present them in sequence by rendering a full screen quad. It is hardly overkill as it can be done with four vertices and a six-component index buffer, and you can't gain access to the framebuffer without going through an API like Direct3D anyhow.

If your textures are set up as render targets themselves you may be able to avoid actually rendering a quad by simply setting them as active and presenting, but never clearing. This causes you to lose a lot of flexibility in what you can do with the rendering pipeline and, because rendering fullscreen quads isn't that big of a deal, I'd recommend you stick with that approach instead.

These solutions should work if you have precomputed full-resolution "frames" of animation you want to play back. If at any point you have real video data you want to play back you should look for a real video playback API; perhaps FFMPEG.
> 1 votes

---
Tags: directx, directx11, rendertargets
---


# Question
Title: GameStateManagement and inputs not being recognized
**EDIT:** *I've removed a bit of code from the input class to make this more readable, and updated my StartScreen class, which is now at the bottom. I have the same issues though, but they are explained in my comments on the bottom of this page. It won't let me paste my additional code here (the format comes out crazy), so I've linked to pastebin with the code* pastebin

I've been trying to implement the MS provided `GameStateManagement` sample with my game, but it has proven a bit difficult. Really, I'm using Oneksoft's Starter Kit, which uses the MS provided sample, so they are identical, except for my splash screen.

I'm able to get the splash screen to launch, where it informs the player to press A to advance the screen, but this doesn't seem to accept any of my inputs. I’ve also added `Console.Writeline(“Pressing A”)` under the `IsMenuPressed` method in `Input.cs` to verify that it is getting called, but for some reason it is constantly spamming my log, rather than just appearing each time I press it. Not sure why this is happening.

I have a bit too much code to post it all here, so I’ve attached a link to my .rar with my classes, but I’ll also leave a bit here which I thinkmay be applicable. https://www.dropbox.com/sh/6ek4uru2jc2ch0k/JTeBWN\_3PQ

What do you guys think the issue is?

```
namespace Pong
{
    public class Input
    {
        public const int MaxInputs = 4;

        public readonly KeyboardState[] CurrentKeyboardState;
        public readonly GamePadState[] CurrentGamePadState;

        public KeyboardState[] LastKeyboardState;
        public GamePadState[] LastGamePadState;

        public readonly bool[] GamePadWasConnected;

        public Input()
        {
            // Get input state
            CurrentKeyboardState = new KeyboardState[MaxInputs];
            CurrentGamePadState = new GamePadState[MaxInputs];

            // Preserving last states to check for isKeyUp events
            LastKeyboardState = CurrentKeyboardState;
            LastGamePadState = CurrentGamePadState;
        }

        /// <summary>
        /// Checks for a "menu select" input action.
        /// The controllingPlayer parameter specifies which player to read input for.
        /// If this is null, it will accept input from any player. When the action
        /// is detected, the output playerIndex reports which player pressed it.
        /// </summary>
        public bool IsMenuSelect(PlayerIndex? controllingPlayer,
                                 out PlayerIndex playerIndex)
        {
            Console.WriteLine("Pressing A");
            return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) ||
                   IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) ||
                   IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) ||
                   IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
        }

        /// <summary>
        /// Checks for a "menu cancel" input action.
        /// The controllingPlayer parameter specifies which player to read input for.
        /// If this is null, it will accept input from any player. When the action
        /// is detected, the output playerIndex reports which player pressed it.
        /// </summary>
        public bool IsMenuCancel(PlayerIndex? controllingPlayer,
                                 out PlayerIndex playerIndex)
        {
            return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
                   IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) ||
                   IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex);
}

```

# Answer
> 1 votes
Dave your problem is in the **PressStartScreen** class.

In the constructor it set's up the event handler **startMenuEntry.Selected** to call the method **StartMenuEntrySelected** which has no code in it.

You need to add code to this method that will call the main menu or something.

like this :-

```
namespace Pong
{
    class PressStartScreen : MenuScreen
    {

        public PressStartScreen()
            : base("")
        {
            MenuEntry startMenuEntry = new MenuEntry("Press A to start");
            startMenuEntry.Selected += StartMenuEntrySelected;
            MenuEntries.Add(startMenuEntry);
        }

        void StartMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            this.ScreenManager.AddScreen(new MainMenuScreen(), e.PlayerIndex);
            this.ExitScreen();
        }

    }
}

```

Also where you put the "Pressing A" log entry will spam your log because that method is called once every update, and you didn't make it conditional.

---

Right, checked again and realised that you have :-

```
public Input()
{
    // Get input state
    CurrentKeyboardState = new KeyboardState[MaxInputs];
    CurrentGamePadState = new GamePadState[MaxInputs];

    // Preserving last states to check for isKeyUp events
    LastKeyboardState = CurrentKeyboardState;
    LastGamePadState = CurrentGamePadState;
}

```

which makes **LastKeyboardState** & **LastGamePadState** references of **CurrentKeyboardState** & **CurrentGamePadState**, change it to :-

```
public Input()
{
    // Get input state
    CurrentKeyboardState = new KeyboardState[MaxInputs];
    CurrentGamePadState = new GamePadState[MaxInputs];

    // Preserving last states to check for isKeyUp events
    LastKeyboardState = new KeyboardState[MaxInputs];
    LastGamePadState = new GamePadState[MaxInputs];
}

```

# Answer
> 1 votes
If the point is to preserve the last game state, wouldn't it make sense to reverse the order of these:

```
public Input()
{
    // Get input state
    CurrentKeyboardState = new KeyboardState[MaxInputs];
    CurrentGamePadState = new GamePadState[MaxInputs];

    // Preserving last states to check for isKeyUp events
    LastKeyboardState = CurrentKeyboardState;
    LastGamePadState = CurrentGamePadState;
}

```

So that the CurrentState gets passed off to Last State, and then updated? It should look something like this:

```
public Input()
    {
        // Preserving last states to check for isKeyUp events
        LastKeyboardState = CurrentKeyboardState;
        LastGamePadState = CurrentGamePadState;

        // Get New Input State
        CurrentKeyboardState = new KeyboardState[MaxInputs];
        CurrentGamePadState = new GamePadState[MaxInputs];
    }

```

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


# Question
Title: 2D Animation Smoothness - Delta time vs. Kinematics
I'm animating a sprite in 2D with key frames of rotation and xy-positions.

I've recently had a discussion with someone saying that when the device (happens to be an iPad using cocos2D) hits a performance bump due to whatever else the user may be doing, lag will arise and that the best way to fight it is to not use actual positions, but velocities, accelerations and torques with kinematics. His message is to evaluate the positions and rotations from these speeds at the current point in time.

I've never experienced a situation where I've heard of using kinematics to stem lag in 2D animations and am not sure of how effective it could be. Also, it seems to be overkill.

The application is not networked so it's all running on a local device. The desired effect is that the animation always plays as closely as it can to the target frame rate.

Wouldn't the technique suffer the same problems as just using the time since the last frame or a fixed time step since the kinematics would also require some time value to perform the calculation?

What techniques could you suggest to best achieve the desired effect?

**EDIT 1**

Thank you for your responses, they are very illuminating. I want to clarify my question before choosing an answer however, to make sure that this post really serves it's purpose.

I have a sprite of a ball, and a text file with 3 arrays worth of information (rotation,translations x, translations y) with each unit of information existing as a key frame to be stepped through (0 to 49 and back to 0 to replay it again). I have this playing by interpolating from the current key frame to the next, every n-units of time. The animation is visibly correct when compared to a video I was given of it, and it is smooth because of the interpolations between the key frames. This is the existing state of the project.

There are no physics simulated, only a static animation of a ball moving in a way an artist specifically designed.

Should I, instead of rotation in degrees and translations by positions in space, derive velocities, accelerations and torques to express this static animation as a function of time? As in, position now = foo(time now), where foo uses kinematics.

# Answer
> 0 votes
So the answers given were insightful but off target. I reworded my question a bit to hopefully clarify but I didn't receive any more responses so here is what I've found through some research.

The technique is called "Animation Accumulation".

Some one talks about it here, http://forum.unity3d.com/threads/8192-Is-Animation-Accumulation-supported. The poster sounds like they have lot of experience with the subject but does not go into it or give references.

The main idea (I believe) is that instead of setting the animation, you accumulate it. Doing this, when lag occurs the animation resumes playing exactly where it left off. If you were setting the animation (as a function of time somehow), returning from lag would create several undesirable effects (such as teleporting).

Unfortunately I haven't been able to find more material on the subject.

# Answer
> 3 votes
Like Amplify91 said, it's not recommended to depend on a fixed framerate, even for an offline game. It's best to keep the game logic and rendering logic separated.

The game logic updates the objects positions, statistics, and check for collisions and responds to inputs, and that is independent of the framerate because it's called at regular intervals. The rendering logic takes care of perspective, visibility and effects and ultimately renders objects on the screen, and that is framerate dependent because the longer it takes to render a scene, the lower will be the framerate.

So if you have an event that is called every frame, use some variable to hold the information how much time has passed since the last call and update every variable that has an impact on animations and rendering by that amount.

This is an exapmle of fixed and variable framerate. Sorry if the language is not what you use, but the exapmle is easy to read and shows how you can use the time passed from the last frame call (´FP.elapsed´ in the example) to update the game logic.

---
Tags: 2d, animation, cocos2d-iphone, ipad, lag
---


# Question
Title: How do I determine which side of the player has collided with an object?
I have some static bodies (platforms) and a dynamic body (the player) in my world. The collision between them works great, but I would like to know which side of the player (rectangle) collides with the platform. How do I get this information?

# Answer
I know this question was already answered but I needed this in one of my games as well and I found the answer in the Farseer forums and modified it for my engine. You will find the original link in the comments (Shameless link to engine http://code.google.com/p/axiosengine/ \- perhaps you will find more interesting things there) :

```
namespace Axios.Engine.Extensions
{
    public enum CollisionDirection
    {
        Right,
        Left,
        Top,
        Bottom
    }
    public static class AxiosExtensions_Contact
    {
        /// http://farseerphysics.codeplex.com/discussions/281783
        /// <summary>
        /// Returns the direction that the collision happened.
        /// Should be used in the event OnAfterCollision
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static CollisionDirection Direction(this Contact c)
        {
            CollisionDirection direction;
            // Work out collision direction
            Vector2 colNorm = c.Manifold.LocalNormal;
            if (Math.Abs(colNorm.X) > Math.Abs(colNorm.Y))
            {
                // X direction is dominant
                if (colNorm.X > 0)
                    direction = CollisionDirection.Right;
                else
                    direction = CollisionDirection.Left;
            }
            else
            {
                // Y direction is dominant
                if (colNorm.Y > 0)
                    direction = CollisionDirection.Bottom;
                else
                    direction = CollisionDirection.Top;

            }

            return direction;
        }
    }
}

```

To use it:

```
 switch (contact.Direction())
                {
                    case CollisionDirection.Left:
//ect

```
> 2 votes

# Answer
There's a few ways I can think of to do this:

1. You could make the player into several fixtures representing each side. Then you could either give each one an `OnCollision` event, or give each one an ID in the `UserData` to figure out which one is the "collider" in a shared `OnCollision` method. This was good for me because I could set the side and top fixtures to have zero friction so the player doesn't stick to platforms.
2. If you're stuff is all axis aligned rectangles, you could calculate it based on their positions and dimensions. This is probably not a great idea for more complex situations since it can get difficult to follow and Farseer already has to calculate this anyways.
3. I think you can check the `Contact`'s world manifold's normal. In your `OnContact` event, there are three parameters: two `Fixtures` and a `Contact`. `Contact` has a method called `GetWorldManifold` which has an `out` parameter called `normal`. This is a `Vector2` that, I think (someone please correct me if I'm wrong), represents the angle of contact.
> 1 votes

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


title: Cross-platform independent development

text:
# Question
Title: Cross-platform independent development
Some years ago, if you wrote in C and some subset of C++ and used a sufficient number of platform abstractions (via SDL or whatever), you could run on every platform an indie could get on - Linux, Windows, Mac OS of various versions, obscure stuff like BeOS, and the open consoles like the GP2X and post-death Dreamcast. If you got a contract for a closed platform at some point, you could port your game to that platform with "minimal" code changes as well.

Today, indie developers must use XNA to get on the Xbox 360 (and upcoming Windows phone); must not use XNA to work anywhere else but Windows; until recently had to use Java on Android; Flash doesn't run on phones, HTML5 doesn't work on IE. Unlike e.g. DirectX vs. OpenGL or Windows vs. Unix, these are changes to the core language you write your code in and can't be papered over without, basically, writing a compiler. You can move some game logic into scripts and include an interpreter - except when you can't, because the iPhone SDK doesn't allow it, and performance suffers because no one allows JIT.

So what can you do if you want a really cross-platform portable game, or even just a significant body of engine and logic code?

Is this not a problem because the platforms have fundamentally diverged - it's just plain not worthwhile to try to target both an iPhone and the Xbox 360 with any shared code because such a game would be bad? (I find this very unlikely. I can easily see wanting to share a game between a Windows Mobile phone and an Android, or an Xbox 360 and an iPad.) Are interfaces so high-level now that porting time is negligible? (I might believe this for business applications, but not for games with strict performance requirements.)

Is this going to become more pronounced in the future? Is the split going to be, somewhat scarily, still down vendor lines? Will we all rely on high-level middleware like Flash or Unity to get anything cross-platform done?

**tl;dr - Is porting a problem, is it going to be a bigger problem in the future, and if so how do we solve it?**

# Answer
> 14 votes
The Unity engine gets you a huge chunk of the way there. Write once and you've got Mac/Windows Standalone and webplayer based. Tweak your inputs, and mind your draw calls and you're on iOS/Android.

# Answer
> 12 votes
For a small indie developer, with limited funds/time (and maybe more of a focus on 'making something cool' than 'making something profitable'), trying to go cross-platform from the start could be counterproductive. It takes a lot of effort to engineer solid cross platform tools and tech (different graphics APIs, endianness, input devices, and more) - time that could be spent on the more creative side of game development.

But you probably want to make sure you've got a great game that works really well on one platform before worrying too much about getting it onto as many platforms as possible! If the game is a flop, there's no point wasting time and effort making it a multi-platform flop, is there?

If you're coding in C/C++, mostly from scratch, then as long as you keep the code fairly modular and make sensible decisions about data formats and middleware/libraries, then supporting other platforms later shouldn't be too painful.

If third-party cross-platform tech/tools (e.g. Unity) is an option for your project, then it's certainly worth considering.

The main 'problem platforms' for indies would seem to be Xbox360 Indie Games (C# only, limited network access, etc), and possibly Android (massive differences in device performance/screen size/input devices). If you're determined to support these, expect a more sizable porting job, or plan to focus on them exclusively.

# Answer
> 3 votes
You say cross-platform **independent** development. The biggest hurdle then is resources, and that means a lack of time most of the time, but also lack of know-how and possibly finances (license fees, buying devices, etc).

Indie or not, the biggest hurdle is actually design. As you say, a game that runs on Xbox360 and iPad might work, but they also need to be fundamentally different in terms of design. The 360 has a controller, the iPad a touch screen. Also, development for the 360 is done in Windows using C# as language, the iPad can only be targeted on Mac OS computers and using C, C++ or Objective-C. Or Javascript, if you prefer. Some things just don't mix that well whatever you do.

What you say about the different platforms holds true today. Use C/C++ and SDL and you can write your program cross-platform on PC-like machines, probably much more smoothly than years ago. However it was always a problem and will always remain a problem to port games from PC to console to mobile, and vice versa. It has just become more pronounced in the recent years by allowing Indie developers to program for consoles (or developers hacking access to it to create homebrew games) and by the rise of mobile devices powerful enough to run games.

Porting has the same problems it ever has, but there are more devices to port to. And some ports just don't make sense without re-designing the core of the game. This is not a problem that can be solved, it's one you have to consider from the outset even before you write your first line of code. Then it will be manageable, no more, no less.

# Answer
> 3 votes
A simple, portable and open interface framework is really needed, I think. Some musings:

There currently seem to be four common kinds of game input methods: Keyboards, Mice, Controllers and Multi-Touch Surfaces. (I'll gloss over the issues of differing capabilities between, for example, gamepads and joysticks for now, though that should eventually be addressed.)

Ideally, our developer would be able to specify in a general way a few different UIs that make sense for the kind of game being written. (They might decide to provide a Keyboard and Mouse UI, a Mouse Only UI and a Multi-Touch UI, as an arbitrary example.)

The framework is then responsible for mediating IO between the platform and the game code, similar to how cross-platform GUI frameworks like QT and GTK function.

Having such a framework wouldn't solve the incompatible language requirements problem, but would at least encapsulate all the system-specific calls behind a common API, which should make language porting much more straightforward.

Well, now that I've written all of that: Does anyone know if a framework like that already exists?

# Answer
> 3 votes
With projects like MonoTouch and XNATouch it was looking like XNA might get you on most platforms with a bit of tweaking. Unfortunately Apple kind of torpedoed that when they changed their Terms and Conditions to restrict which languages you can use. Unity goes across pretty much everything now, although on XBOX it will get you on XBLA but not XBLIG, so not an option for smaller indies.

One approach might be to create a framework that uses the same conventions across multiple languages/platforms, then it is just a matter of tweaking syntax to port games. You might want to launch your game in Flash, which can be developed quickly and reach a large audience, then if it is successful port to iPhone, XNA etc. This way you know you have a fun game before over-committing yourself.

# Answer
> 2 votes
I think this is an economic problem, not a technical problem. Platforms like xbox360 have a strong incentive to be exclusionary, because they're trying to get users choosing their platform instead of some other platform. "We have these cool exclusive games" is way more interesting than "we can also play these games that everyone else has". The ecosystem is dominated by the hardware manufacturers.

I suspect this will change when social-networked gameplay matures, because there's potentially a lot more money in getting everyone into the same social-gaming system than in making yet-another-FPS-with-sexy-graphics.

# Answer
> 2 votes
I just discovered Haxe and NME. It claims to be a cross-platform app that supports all major desktops and mobile devices, *and* Flash, from one code-base. Worth a look.

# Answer
> 1 votes
A cross-platform development tool that is so new I don't necessarily recommend it is http://www.monkeycoder.co.nz/

It hits every platform you mentioned.

While it is too new to really judge, it has a great pedigree: it's creator previously made Blitz3D and BlitzMax, which were great development tools for indie game developers.

# Answer
> 0 votes
I've had luck with the airplay SDK - at least on x86 and apparently targets iPhone well (although I still have yet to put an app on an iPhone yet).

---
Tags: cross-platform
---


# Question
Title: what's wrong with this Lua code (creating text inside listener in Corona)
If you double/triple click on the myObject here the text does NOT disappear. Why is this not working when there are multiple events being fired?

That is, are there actually multiple "text" objects, with some existing but no longer having a reference to them held by the local "myText" variable? Do I have to manually removeSelf() on the local "myText" field before assigning it another "display.newText(...)"?

```
display.setStatusBar( display.HiddenStatusBar )

local myText

local function hideMyText(event)
    print ("hideMyText")
    myText.isVisible = false
end

local function showTextListener(event)
    if event.phase == "began" then
        print("showTextListener")
        myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
        timer.performWithDelay(1000, hideMyText, 1 )
    end
end

-- Display object to press to show text
local myObject = display.newImage( "inventory_button.png", display.contentWidth/2, display.contentHeight/2)
myObject:addEventListener("touch", showTextListener)

```

Question 2 - Also why is it the case that if I add a line BEFORE "myText = ..." of: a) "if myText then myText:removeSelf() end" =\> THIS FIXES THINGS, whereas b) "if myText then myText=nil end" =\> DOES NOT FIX THINGS

Interested in hearing how Lua works here re the answer...

# Answer
> 1 votes
When you call `obj:removeSelf()`, it removes corona metatable from object and remove it from display hierarchy. But the object is not completely removed after this, it becomes a simple lua table `{}`. So you must set it to `nil`, to the garbage collector deleted it completely.

You can change your listener to this:

```
local function showTextListener(event)
    if event.phase == "began" and myText ~= nil then
        print("showTextListener")
        myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
        timer.performWithDelay(1000, hideMyText, 1 )
    end
end

```

So, your listener will executes only if `myText` is not created yet. Or to this, if you want to recreate `myText` object every tap.

```
local function showTextListener(event)
    if myText then myText:removeSelf() ; myText = nil end
    if event.phase == "began" then
        print("showTextListener")
        myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
        timer.performWithDelay(1000, hideMyText, 1 )
    end
end

```

When you call `obj:removeSelf()`, it removes corona metatable from object and remove it from display hierarchy. But the object is not completely removed after this, it becomes a simple lua table `{}`. So you must set it to `nil`, to the garbage collector deleted it completely.

---
Tags: lua, corona-sdk
---


title: A* algorithm very slow

text:
# Question
Title: A* algorithm very slow
I have an programming a RTS game (I use XNA with C#). The pathfinding is working fine, except that when it has a lot of node to search in, there is a lag period of one or two seconds, it happens mainly when there is no path to the target destination, since it that situation there is more nodes to explore. I have the same problem when the path is shorter but selected more than 3 units (can't take the same path since the selected units can be in different part of the map).

```
private List<NodeInfo> FindPath(Unit u, NodeInfo start, NodeInfo end)
{
Map map = GameInfo.GetInstance().GameMap;

_nearestToTarget = start;
start.MoveCost = 0;
Vector2 endPosition = map.getTileByPos(end.X, end.Y).Position;
//getTileByPos simply gets the tile in a 2D array with the X and Y indexes
start.EstimatedRemainingCost = (int)(endPosition - map.getTileByPos(start.X, start.Y).Position).Length();
start.Parent = null;

List<NodeInfo> openedNodes = new List<NodeInfo>(); ;
List<NodeInfo> closedNodes = new List<NodeInfo>();

Point[] movements = GetMovements(u.UnitType);

openedNodes.Add(start);

while (!closedNodes.Contains(end) && openedNodes.Count > 0)
{
    //Loop in nodes to find lowest cost
    NodeInfo currentNode = FindLowestCostOpenedNode(openedNodes);

    openedNodes.Remove(currentNode);
    closedNodes.Add(currentNode);

    Vector2 previousMouvement;

    if (currentNode.Parent == null)
    {
        previousMouvement = ConvertRotationToDirectionVector(u.Rotation);
    }
    else
    {
        previousMouvement = map.getTileByPos(currentNode.X, currentNode.Y).Position -
            map.getTileByPos(currentNode.Parent.X, currentNode.Parent.Y).Position;
        previousMouvement.Normalize();
    }

    //For each neighbor
    foreach (Point movement in movements)
    {
        Point exploredGridPos = new Point(currentNode.X + movement.X, currentNode.Y + movement.Y);

        //Checks if valid move and checks if not if closed nodes list
        if (ValidNavigableNode(u.UnitType, new Point(currentNode.X, currentNode.Y), exploredGridPos) &&
            !closedNodes.Contains(_gridMap[exploredGridPos.Y, exploredGridPos.X]))
        {
            NodeInfo exploredNode = _gridMap[exploredGridPos.Y, exploredGridPos.X];
            Tile.TileType exploredTerrain = map.getTileByPos(exploredGridPos.X, exploredGridPos.Y).TerrainType;

            if(openedNodes.Contains(exploredNode))
            {
                int newCost = currentNode.MoveCost + GetMoveCost(previousMouvement, movement, exploredTerrain);
                if (newCost < exploredNode.MoveCost)
                {
                    exploredNode.Parent = currentNode;
                    exploredNode.MoveCost = newCost;

                    //Find nearest tile to the target (in case doesn't find path to target)
                    //Only compares the node to the current nearest
                    FindNearest(exploredNode);
                }
            }
            else
            {
                exploredNode.Parent = currentNode;
                exploredNode.MoveCost = currentNode.MoveCost + GetMoveCost(previousMouvement, movement, exploredTerrain);

                Vector2 exploredNodeWorldPos = map.getTileByPos(exploredGridPos.X, exploredGridPos.Y).Position;

                exploredNode.EstimatedRemainingCost = (int)(endPosition - exploredNodeWorldPos).Length();

                //Find nearest tile to the target (in case doesn't find path to target)
                //Only compares the node to the current nearest
                FindNearest(exploredNode);

                openedNodes.Add(exploredNode);
            }
        }
    }
}

return closedNodes;
}

```

After that, I simply check if the end node is contained in the returned nodes. If so, I add the end node and each parent until I reach the start. If not, I add the nearestToTarget and each parent until I reach the start.

I added a condition before calling FindPath so that only one unit can call a find path each frame (60 frame per second), but it makes no difference.

I thought maybe I could solve this by allowing the find path to run in background while the game continues to run correctly, even if it takes a few frame (it is currently sequential sonce it is called in the update() of the unit if there's a target location but no path), but I don't really know how...

I also though about sorting my opened nodes list by cost so I don't have to loop them, but I don't know if that would have an effect on the performance...

Would there be other solutions?

P.S. In the code, when I get the Move Cost, I check if the unit has to turn to perform the move, and the terrain type, nothing hard to do.

# Answer
When there is no path from the start to the end, the algorithm must search every possible location. This means that A\* becomes as least as slow as a naive flood-fill algorithm (as it is covering the whole graph) and probably slower (as it is performing extra work to manage the queue and calculate heuristics). Optimising your algorithm is unlikely to help much as this is the worst-case scenario and the issue is the number of nodes you will evaluate.

Sorting your open list by cost may or may not help matters in the usual case, because you end up making `FindLowestCostOpenedNode` a lot cheaper but it makes adding nodes to the open list more expensive, so the benefit depends somewhat on how straight your paths typically are. But in this case, you're exploring the whole map, which means every single node is added to the list at least once and taken off the list at least once, meaning no real benefit - sorting a list gains you nothing if you're going to be looking at every element anyway.

So, all you can do here is try and find some short-cuts to avoid examining the whole map in these situations or to reduce the cost of doing so. Ideas include:

* Doing a cheap hierarchical search first, and only performing the detailed search if the top level search succeeds. bobobobo's answer describes this approach.
* Annotate your map with regions that can't be reached from other regions. You may be able to pre-process your map and use a flood-fill technique to determine all the contiguous areas that can be reached (and by extension, also find all the areas that cannot ever be reached). By marking these you can cancel the A\* algorithm as soon as it begins, by spotting that the start node and end node are not in the same contiguous region.
* You can run the A\* search concurrently with your game updates, so that although it will take a long time, it won't hold up the game. The safest way to do this is to wrap the `FindPath` data and function into a class, change it so that instead of just returning a path, it can return a Finished or Not Finished value, make it return Not Finished after processing 50 nodes (or some other arbitrary amount), and call `FindPath` every frame until the algorithm completes. Another way is to push the processing into a background thread, but that is generally not safe and is quite error-prone unless you are familiar with threads.
> 7 votes

# Answer
Without looking at your code, the only thing I can suggest is to *make your graph coarser*. So I would plan the route in 2 steps:

given desired route:

If you find the route (from the o to the x) using the full graph (with 1 graph node per tile in this case) it would be more expensive than it needs to be.

Consider the following (more sparse) set of graph nodes:

You would use this to determine initial path direction, but you would need to have a per-frame collision management system (if you run into another unit on the way, you need to find a way around that unit and not get stuck).
> 10 votes

# Answer
This is using two lists (and both unsorted!), not priority queues and sets. Unless you are using data structures with complexity guarantees similar to those, the algorithm is not A\* but just a slow pile of crap.

Please read something, anything about the A\* algorithm's implementation and rewrite it to use proper data structures.
> 3 votes

# Answer
As your problem is unreachable locations, you really need some kind of hierarchy.

Here's an excellent writeup for the RTS game 0ad: http://www.moddb.com/games/0-ad/news/more-fun-with-pathfinding

Here's how 0ad did it:

They split the map into smaller tiles, and then flood-fill in each tile to discover navigable zones.

You likely only need to do this once, obviously. You may then need to recompute tiles when users build walls and such on them, but that's very rare.

You can then build a lookup that tells you if any zone is reachable from any other; you might build a graph to do so, and you might collapse that graph when build into a simple hashmap keyed by concatenated start and destination zones. Or you might keep the graph around and use it to direct your A\*.

As you are concerned about A\* performance, also consider - when you have the navigability problem solved - adding the excellent Jump-Point-Search to optimise the A\* runtime itself when it does have to find a path.
> 2 votes

---
Tags: xna, c#, path-finding, performance, multithreading
---


# Question
Title: Detecting extremely fast joystick button presses?
Is it usually possible for the player to press and release a button within a single frame, so that the game engine doesn't have time to detect it?

How do programmers usually handle this situation? Is it even necessary to handle it?

While testing, I was able to press and release a button within about 14 or 15 milliseconds (over 1 click/frame). I was not, however, able to do this while holding the joystick normally, and the press-release cycle would have to start at almost the exact time the frame starts.

Specifically, I am asking about GLFW's joystick input capabilities.

I am currently using GLFW to make a game, and I've noticed that keyboard and mouse have callback functions, while joysticks do not. Also, it does not appear to be possible to enable "sticky keys" for a joystick. (I have only recently started using GLFW, so please correct me if I am wrong, as having either of those would solve the problem.)

Although I am asking about GLFW, answers related to any library/engine/language are welcome.

# Answer
> 7 votes
On Nintendo and Sony hardware we sometimes polled the input at a higher rate than we drew frames; use a timer-driven thread to look at the controller I/O at 120hz, for example, even when we were rendering at 30hz. By "a timer-driven thread" I mean there was a hardware timer that poked an interrupt that caused a particular function to get called in realtime. On these system the controller appeared as memory-mapped I/O, so you'd simply load a word out of a particular memory location and that would have the position of the joystick's X-axis at that moment. You'd save that off somewhere in main memory, and then when your main game loop ran it would have a history of 4 or 8 or however many samples of input data at a consistent time interval.

This wasn't to detect button-mashing, but to get crisp intraframe timing for fighting games where it mattered (because you were allowed to queue up inputs "before" a critical trigger frame in the animation, and the animation rate might not be as stable as we like, so we needed to distinguish whether you'd hit the button before the frame boundary or on it).

I don't know if it's possible with GFWL. DirectX's input system is pretty tightly bound to the render cycle, and there's a heck of a lot of operating system between you and the switches in the USB gamepad.

# Answer
> 2 votes
Are you sure about that? I can possibly see a state transition going that fast here and there, but you do realize it would take a sustained 70 presses per second to see a button down every 14ms? Sorry but that is not physically possible, although perhaps you can induce it here and there with some crazy all-knuckles button-mashing, and maybe there is even some bounce in the hardware itself. Have you ever watched a video of professional StarCraft players, where they use all the fingers on one hand plus a mouse and click so fast it's a blur? Those guys are gods if they can do 300 actions per *minute* which is 5 per second using both hands...

That said, in general with a lot of games you just see input polled every frame. The possibility of an entire press-release-press happening within a frame and getting lost is pretty remote at interactive framerates, and I have never known a game developer to worry about this.

On some systems you may get buffered input. The system monitors the input devices asynchronously and fills up a queue with all the state changes that took place since the last query, and generally you would let the buffer fill up between frames and process it each frame, so the resolution may be higher than polling the state each frame.

Some systems are event driven, so you can register a callback that fires every time input state changes, although the resolution will be dependent on the rest of the software stack and may or may not be significantly better than a per-frame check. For example if the API is just polling the hardware every frame, comparing it to the last frame and then firing the applicable callbacks, you aren't doing any better.

With embedded systems and some old game systems that were programmed to the metal, you would have had interrupts for the buttons. An interrupt is a little piece of code you register with the system that runs every time something happens. In the case of a button interrupt, the hardware would be physically designed so that when the voltage on the wire connected to the button goes from low to high or high to low, it runs this bit of code. This would be the most direct and responsive system but most games these days have a ton of hardware and software between you and the buttons.

# Answer
> 0 votes
Assuming a game running at 60 fps, each frame is about 17 milliseconds. Highly unlikely someone could press **and** release in that amount of time. If you can click fast enough to get about 60 clicks *per second*, then you'd be pressing and releasing fast enough to beat the frames.

---
Tags: input, joystick
---


# Question
Title: Question about mipmaps + anisotropic filtering
I'm a bit confused here and maybe someone can explain this to me. I created a simple test texture for my terrain which is nothing more than a solid green color with a black grid overlayed on top of it. If I look at the terrain in the distance with mipmapping on and linear filtering, the grid lines become blurry fairly quickly and further back the grid is pretty much invisible. With these settings, I don't get any moire patterns at all. If I turn on anisotropic filtering, however, the higher the anisotropic level, the more the terrain looks like it did with without mipmapping. The lines are much crisper nearby but in the distance I start to see terrible moire patterns.

My understanding was that mipmapping is supposed to get rid of moire patterns. I've always had anisotropic filtering on in every game I play and I've never noticed any moire patterns as a result, so I don't understand why it's happening in my game. I am using logarithmic depth however, could that be causing any problems? And if it is, how do I resolve it?

I've created my sampler state like so (I'm using slimdx):

```
ssa = SamplerState.FromDescription(Engine.Device, new SamplerDescription
{
       AddressU = TextureAddressMode.Clamp,
       AddressV = TextureAddressMode.Clamp,
       AddressW = TextureAddressMode.Clamp,
       Filter = Filter.Anisotropic,
       MaximumAnisotropy = anisotropicLevel,
       MinimumLod = 0,
       MaximumLod = float.MaxValue
});

```

Point Filtering

Anisotropic 1

Anisotropic 8

Anisotropic 16

Anisotropic 16 at an angle

# Answer
> Would the fact that I'm using a texture atlas cause this?

Anisotropic filtering only works within a topologically continuous surface. Two adjacent triangles that share an edge position-wise, but have different texture coordinates are not topologically continuous. And thus, aniso won't work very well between triangles.

Just use mipmap filtering.
> 2 votes

---
Tags: directx, directx11, slimdx
---


title: glTranslate, how exactly does it work?

text:
# Question
Title: glTranslate, how exactly does it work?
I have some trouble understanding how does glTranslate work. At first I thought it would just simply add values to axis to do the transformation.

However then I have created two objects that would load bitmaps, one has matrix set to GL\_TEXTURE:

```
public class Background
{
    float[] vertices = new float[]
        { 0f, -1f, 0.0f,
          4f, -1f, 0.0f,
          0f, 1f, 0.0f,
          4f, 1f, 0.0f };

    ....
    private float backgroundScrolled = 0;
    public void scrollBackground(GL10 gl)
    {
        gl.glLoadIdentity();
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glTranslatef(0f, 0f, 0f);
        gl.glPushMatrix();

        gl.glLoadIdentity();
        gl.glMatrixMode(GL10.GL_TEXTURE);
        gl.glTranslatef(backgroundScrolled, 0.0f, 0.0f);
        gl.glPushMatrix();

        this.draw(gl);
        gl.glPopMatrix();

        backgroundScrolled += 0.01f;
        gl.glLoadIdentity();
    }
}

```

and another to GL\_MODELVIEW:

```
public class Box
{
    float[] vertices = new float[]
        { 0.5f, 0f, 0.0f,
          1f, 0f, 0.0f,
          0.5f, 0.5f, 0.0f,
          1f, 0.5f, 0.0f };

    ....

    private float boxScrolled = 0;
    public void scrollBackground(GL10 gl)
    {
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        gl.glTranslatef(0f, 0f, 0f);
        gl.glPushMatrix();

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        gl.glTranslatef(boxScrolled, 0.0f, 0.0f);
        gl.glPushMatrix();

        this.draw(gl);
        gl.glPopMatrix();

        boxScrolled+= 0.01f;
        gl.glLoadIdentity();
    }
}

```

Now they are both drawn in Renderer.OnDraw. However background moves exactly 5 times faster. If I multiply boxScrolled by 5 they will be in sinc and will move together. If I modify backgrounds vertices to be

```
    float[] vertices = new float[]
        { 1f, -1f, 0.0f,
          0f, -1f, 0.0f,
          1f, 1f, 0.0f,
          0f, 1f, 0.0f };

```

It will also be in sinc with the box. So, what is going under glTranslate?

# Answer
> 5 votes
Here is my full answer:

Your glPushMatrix and glPopMatrix count should be equal. It's first problem.

But main problem is in matrix mode. In first case (background), you are using texture matrix, which is modified by glTranslate. It means, that in every step texture coordinates will be multiplied by this translation.

Because texture coordinates are in range \<0,1\>, and your background rectangle is wide 4 units, **it will not be translated by 0.01** every frame, but **it will be translated by 0.04 units** in world.

In second case (box), you are changing modelview matrix. Which will cause to translate your box by 0.01 units every frame in world.

When you change background rectangle to new coordinates (x coordinates are 0 and 1), then every frame texture coordinates are really translated by 0.01 units.

# Answer
> 6 votes
**glTranslatef**

`glTranslatef` translates (a special case of "transforming") the matrix corresponding to the currently selected matrix mode. So calling it after `glMatrixMode(GL_MODELVIEW)` means you transform the model-view matrix, and after `glMatrixMode(GL_TEXTURE)` you transform the texture matrix. See the Wikipedia article about translation matrices to learn more about this.

The **model-view matrix** is applied to object coordinates to get eye coordinates, which means absolute world coordinates are transformed to coordinates relative to the "camera". (Before the object is actually rendered its coordinates are transformed a number of extra times, details are in the OpenGL FAQ regarding transformations, but they aren't important right now.)

The **texture matrix** does something completely different, it is applied to texture coordinates before they are mapped. Using it will allow you to achieve a scrolling, rotating, scaling, or perspective-warping texture effect.

Hopefully you will see now that **these two matrices aren't interchangeable** in the way you think they are. They are applied in different stages of the rendering process. When the results of transforming both matrices align on your screen, it is purely a coincidence that also depended on your objects' positions and texture coordinates, amongst others.

**Some minor extra remarks**

Then something else, the commenters are right in saying you should balance your calls to `glPush/PopMatrix`. Without seeing the rest of your code, and knowing what other objects are being rendered, it's hard to tell, but it's possible that part of the effect you are experiencing (the translation scaling by a factor of 5) is due to the model-view matrix for one object incorrectly being applied to another object because it is still on the matrix stack.

Furthermore:

* Calling `glMatrixMode` in succession with the same arguments won't change anything as the OpenGL state stays the same.
* `glLoadIdentity` loads the identity matrix: a matrix that returns the exact same coordinates it was applied to. It could be seen as a "reset" of the current matrix. Calling it multiple times won't have any effect (unless you do something to the current matrix in between).
* `glTranslatef(0f, 0f, 0f)` won't have any effect.

# Answer
> 1 votes
What exactly does glTranslate do? First of all it computes a translation matrix - this is just an identity matrix with the translation values in slots 3 (for x), 7 (for y) and 11 (for z) (assuming column-major). Then it multiplies the current matrix by this translation matrix to get a new matrix, which it then replaces the current matrix with. That's basically it.

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


title: Particle Effect Completion

text:
# Question
Title: Particle Effect Completion
In my game I use particle effect for various purposes. In that I detect the completion of the particle effect. Basically I want to do something after completion of the particle effect. But the problem is that I didn't able to find the particle effect completion. So any community member please help me.

EDIT : I was creating particle effect using following code

```
    pointParticleEmtitter = new PointParticleEmitter(pX, pY);

    particleSystem = new ParticleSystem(pointParticleEmtitter, maxRate,
            minRate, maxParticles, mParticleTextureRegion.deepCopy());

    particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
    particleSystem.addParticleInitializer(new ColorInitializer(0f, 0f, 1f));
    particleSystem.addParticleModifier(new AlphaModifier(1, 0, 0, 0.5f));
    particleSystem.addParticleModifier(new ExpireModifier(0.5f));
    gameObject.getScene().attachChild(particleSystem);

```

Using above code the particle effect was started but when finished that I want to detect. After finishing effect I want to remove the object from the scene.

# Answer
> 2 votes
You can add a timer with call back to be called when your particle system is done.

```
...
particleSystem.addParticleModifier(new ExpireModifier(particleEffectDuration));
gameObject.getScene().attachChild(particleSystem);
scene.registerUpdateHandler(new TimerHandler(particleEffectDuration, new ITimerCallback() {
    @Override
    public void onTimePassed(final TimerHandler pTimerHandler) {
        //code that triggers when timer is complete
    }
});

```

---
Tags: andengine
---


# Question
Title: Android Game Development problem with Speed = Distance / Time
I have been coding speed for an object. I have made it so the object will move from one end of the screen to another at a speed depending on the screen size, at the monemt I have made it so it will take one second to pass the screen. So i have worked out the speed in code but when I go to assign the speed it tells me to force close and i do not understand why. Here is the code:

### MainGame Code:

```
@Override
protected void onDraw(Canvas canvas) {
    setBlockSpeed(getWidth());
}

private int blockSpeed;
 private void setBlockSpeed(int screenWidth){
Log.d(TAG, "screenWidth " + screenWidth);
 blockSpeed = screenWidth / 100; // 100 is the FPS.. i want it to take 1 second to pass the screen
 Math.round(blockSpeed); // to make it a whole number
 block.speed = blockSpeed; // this is line 318!! if i put eg block.speed = 8; it still tells me to force close
 }

```

### Block.java Code:

```
public int speed;

public void draw(Canvas canvas) {
    canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2), y - (bitmap.getHeight() / 2), null);
    if(dontmove == 0){
        this.x -= speed; // if it was eg this.x -= 18; it would not have an error

    }
}

```

### The exception

```
06-08 13:22:34.315: E/AndroidRuntime(2801): FATAL EXCEPTION: Thread-11
06-08 13:22:34.315: E/AndroidRuntime(2801): java.lang.NullPointerException
06-08 13:22:34.315: E/AndroidRuntime(2801):     at com.charltonsantana.game.MainGame.setBlockSpeed(MainGame.java:318)
06-08 13:22:34.315: E/AndroidRuntime(2801):     at com.charltonsantana.game.MainGame.onDraw(MainGame.java:351)
06-08 13:22:34.315: E/AndroidRuntime(2801):     at com.charltonsantana.game.MainThread.run(MainThread.java:64)

```

# Answer
> 1 votes
Is your `block` object previously created?

# Answer
> 0 votes
In MainGame code, there is no need to round as currently written. The result of an int divided by an int is an int. Instead, cast to double by dividing by 100.0 and the round by adding 0.5 and casting result to an int

For example:

```
int screenWidth = 150;
int blockSpeed = screenWidth/100;
System.out.println("way #1 before round, blockSize is "+blockSpeed);
Math.round(blockSpeed);
System.out.println("way #1 after round, blockSize is "+blockSpeed);
blockSpeed = (int)((screenWidth/100.0)+0.5);
System.out.println("way #2, blockSize is "+blockSpeed);

```

Output:

```
way #1 before round, blockSize is 1
way #1 after round, blockSize is 1
way #2, blockSize is 2

```

---
Tags: java, android, animation, sprites, pixel
---


title: Alternatives to a leveling system

text:
# Question
Title: Alternatives to a leveling system
I'm currently designing a rough prototype of a mecha fighting game.

These are the basics I came up with:

* Multiplayer (matchmaking for up to 10 people, for now)
* Browser based (HTML5)
* 2D (`<canvas>`)
* Persistent (as in, players have accounts and don't have to use a new mech each time they start a match)
* Players earn money upon destroying another mech, which is used to buy parts (guns, armor, boosters, etc)
* Simplicity (both of the game itself, and of the development of said game)
* No "leveling" (as in, players don't get awarded with XP)

The last part is bothering me. At first, I wanted to have players gain experience points (XP) when destroying other mechs, but gaining two things at once (money and XP) seemed to be in conflict with my last point, which is simplicity. If I were to have a leveling system, that would require additional development. But, the biggest problem is that I simply couldn't fit it anywhere! Adding levels would require adding meaning to these levels, and most of the things that I hoped to achieve could already be achieved with the money mechanic I introduced. So I decided to drop leveling off completely.

That, in turn, removed a fairly popular and robust mean of progression in games from my game (not that I would use it well anyway). **Is there another way of progression in games, aside from leveling and XP points, that wouldn't get rendered redundant by my money mechanic, would be somehow meaningful (even on a symbolic level), and wouldn't be in conflict with my last point, which is simplicity?**

# Answer
> 9 votes
> That, in turn, removed a fairly popular and robust mean of progression in games from my game (not that I would use it well anyway). Is there another way of progression in games, aside from leveling and XP points, that wouldn't get rendered redundant by my money mechanic, would be somehow meaningful (even on a symbolic level), and wouldn't be in conflict with my last point, which is simplicity?

Why do you think that the leaderboard is not enough progression for your players?

There are some things you can do to show progression:

* **A league table of players** Is pretty much mandatory for PvP games.
* **Achievements** for unusual actions
    + Bare chested - win a battle without shields
    + Last one standing - be the last surviving Mech
    + Mix'em up - three kills with one shot
    + Connoisseur - try every Mech
    + Knockout punch - kill an enemy with life \> 50% in a single shot
    + Dr Robotic - loose 1000% of your health in a game without dying.
    + etc...
* **Weapon specialities**

Higher level weapons are only available when you have demonstrated skill with a particular type of weapons, for example, lvl 5 lasers are only available when you have killed 200 enemies with lasers.
* **Community bandwidth**

Reward players with bigger profiles, customisable avatars, and better ways of asserting their identities in the player community. Stackexchange does this, with profile callouts for higher ranked users, etc...
* **Customisation options**

Players love to customise their creations. Allowing them to pick a color for their Mech, or a custom flag to display on the game chat should be rewards that show player advancement. Good way to spend all the money they've earned too...
* **More powerful tools**

Rather than changing the modules, give them tools that allow them to do more with what they already have. For example, unlocking a tool to combine two modules into one for a cost.
* **Meaningful Ranks**

Instead of having ranks based on skill level alone, why not make them more interesting by having them reflect the player's playstyle too. For example:

+ **Elite Scout of Chaos** High level, prefers fast Mechs, High level of friendly fire
    + **Novice Behemoth of Sniping** Low level, prefers armoured Mechs and long range lasers
    + **Scarred Veteran of Cyberwarfare** High level, took significantly more damage than average for his level than his peers, prefers electronic warfare
    + **Stealth Mechanist** Uses stealth Mechs and cloaking devices, high rate of repairing other Mechs
    + **Pristine Elite Brawler** took less damage, high level, prefers short range weapons
    + and so on.

# Answer
> 5 votes
As a forewarning - this is kind of redundant with your own answer but with different terms and a slightly different implementation. Also I don't really have a good idea of design for your game so some points may not be relevant.

The first thing that popped into my mind was to implement some sort of licensing system (somewhat inspired by Monster Rancher and Grand Turismo). How could something like this be applied to a PVP Mecha game? I've run through some options in my head and here is what I came up with.

A license could determine what type of equipment a player can outfit his mech with and as such equipment could have license requirements. This allows a bit of progression in your game where players have a goal to work towards other than just "I need X amount of resource Y to get Z."

A license may also determine, to some extent, what a player can do. For example, if you game has matches / tournaments / special events / whatever you can make it so that the rewards from higher licenses are better but at the same time you could have license requirements to participate.

Now the challenge is how do players get licenses? Well in monster rancher there was a set of tournaments you had to complete to prove you were ready to go onto the next rank. It could be something similar in your game. If you can make it event based, that would be fun! But otherwise this system may look similar to that of achievements where you just need to accomplish tasks X, Y, Z to get the license. Since I know you want to do matchmaking - maybe you can make a "game mode" that is a license qualifier and maybe the top X players get their license as a reward plus normal rewards.

Another option might be taking a test of some sort (ala Grand Turismo) where you have a solo challenge that you could take to prove you are qualified for the next license. Behind the scenes this could include gear checks to prove that enough money has been earned that is implemented in a way that if you don't have the right gear or enough skill you will likely fail the test.

Again... I'm kind of going out on a limb here because I don't really know how your game is going to play out, but I think this will give you some ideas to play around with in your head.

# Answer
> 3 votes
I think you've got the right idea with ranks, or even some sort of **skill level**. With this being an online multiplayer experience, you could have some sort of Player Skill Level that would be determined by both match outcome and the skill levels of the other players in the match (win a match against a bunch of people with a higher skill level and yours increases a lot; beat up some people with lesser skill levels and it only goes up a little; lose and it drops, etc). Maybe even utilize it in generating matches with players of equal skill? And as a skill level it could go up or down, unlike a traditional leveling system. It probably wouldn't be hard to implement some sort of Achievement or Rank system (promotion/demotion) on top of this either.

# Answer
> 2 votes
Things that I thought of while I was writing this question:

1. Achievements
2. Ranks (novice, veteran, etc)

**Achievements** are definitely getting in, but I don't think that they will solve my problem entirely, that's why I have **ranks**. What I wanted is a small piece of information that would allow the player to estimate his success, and that is solved by a number (level) or one word (rank), but definitely not by a long list of achievements.

I'm still, of course, looking for better ways to do this and comments on what I have so far.

---
Tags: game-design, multiplayer, game-mechanics, progression
---