title: A view and projection matrix oddity?

text:
# Question
Title: A view and projection matrix oddity?
I have a bit of a dilemma ... So i setup my scene how I want it with some bits in it and now I want to move all my camera related code in to a camera class however doing so is proving to be a pain in my ass.

So in my game code (my main game class) I have ...

```
    protected override void Initialize()
    {
        model = new TerrainModel();
        base.Initialize();

        // Load known core components
        camera = new Camera(this, cameraPosition, new Vector3(10, 10, 10));
    }

```

Then in update ...

```
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        camera.Update();

        base.Update(gameTime);
    }

```

Then in draw ...

```
    protected override void Draw(GameTime gameTime)
    {
        cubeEffect.View = Matrix.CreateLookAt(cameraPosition, new Vector3(10, 10, 10), Vector3.Up);
        cubeEffect.View = camera.View;

        cubeEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1.0f, 1000.0f);
        cubeEffect.Projection = camera.Projection;
    }

```

It's these draw lines that have me confused. If i use the first pair (the lines that create the matrices there and then) it all works.

If I use the second pair (pulling the same thing from my camera class) it doesn't and i get a blank screen.

I'm only rendering a single model so there's a chance it could be pointing in the wrong direction but it seems to have done what i expect when i put breakpoints in and look at the variables.

So what have i done wrong?

Here's my camera class ...

```
public class Camera
{
    #region fields

    Matrix viewMatrix;
    Matrix projectionMatrix;
    Viewport viewPort;
    BoundingFrustum cameraViewableBounds;
    Vector3 currentTarget;
    Vector3 cameraPosition;

    #endregion

    #region Properties

    public Matrix Projection { get { return projectionMatrix; } }
    public Matrix View { get { return viewMatrix; } }
    public Viewport ViewPort { get { return viewPort; } }

    public Vector3 Position
    {
        get { return cameraPosition; }
        set
        {
            cameraPosition = value;
            Update();
        }
    }

    public Vector3 TargetPosition { get { return currentTarget; } }

    public bool CanSee(BoundingBox ObjectBounds)
    {
        if (cameraViewableBounds.Contains(ObjectBounds) != ContainmentType.Disjoint)
            return true;

        return false;
    }

    #endregion

    public Camera(Game game, Vector3 startingPosition, Vector3 startingTarget)
    {
        cameraPosition = startingPosition;

        // creates a new view matrix
        LookAt(startingTarget);

        viewPort = game.GraphicsDevice.Viewport;

        // Set the Projection matrix which defines how we see the scene (Field of view)
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 0, 1, 10000);
    }

    #region Camera state updating

    public void Update()
    {
        viewMatrix = Matrix.CreateLookAt(cameraPosition, TargetPosition, Vector3.Up);
        cameraViewableBounds = new BoundingFrustum(viewMatrix * projectionMatrix);
    }

    public void LookAt(Vector3 target)
    {
        currentTarget = target;
        viewMatrix = Matrix.CreateLookAt(Position, TargetPosition, Vector3.Up);
    }

    #endregion
}

```

}

I'm sure this is something crazy simple that i've missed ... i just can't see it.

NOTE: I have omitted a lot of code here to try and simplify my question but I'm pretty sure the rest of my code is fine because it works unless I use this new camera class, however I can provide more if its needed.

# Answer
> 2 votes
Have a look at this line in the Camera class again:

> ```
> projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 0, 1, 10000);
>
> ```

**You have your aspect ratio as zero (which won't work)**

For what it's worth I think the call to LookAt is redundant/confusing in the Camera constructor -- if anything in the scene is going to ever move you will be needing to recreate the View matrix on Update anyway.

Last thing, have you heard of Auto Implemented properties?

---
Tags: xna, c#, xna-4.0, camera
---


# Question
Title: How could I implement something like Minecraft's crafting grid?
The crafting system in Minecraft uses a 2x2 or 3x3 grid. You place ingredients on the grid, and if you put the right ingredients in the right pattern, it will activate the recipe.

Some interesting points about the design:

* Some recipes can exchange certain ingredients for others. For example, a pick uses sticks for the haft, and may use wooden planks, cobblestone, iron ingots, gold ingots, or diamond gems for the head.
* Relative position within the pattern is what matters, not absolute position on the grid. That is, you can craft a torch by placing the stick and coal (or charcoal) in the correct pattern in any of six positions on the 3x3 grid.
* Patterns may be flipped horizontally.

I may be overthinking it, but this seems like an interesting search/set-reduction problem. So, how does (or could) this work, algorithmically speaking?

# Answer
Another solution is to use a somewhat complicated tree. The branch nodes in your tree would be created by iterating over the recipe (once again using `for (y) { for (x) }`); this is your stock-standard by-the-book tree structure. Your final node would contain an additional structure (`Dictionary`/`HashMap`) that maps dimensions to recipes.

Essentially what you are going for is this:

The black nodes are your branches that indicate item type - the red ones are your leaves (terminators) which allow you to differentiate size/orientation.

To search over this tree you would first find the bounding box (as outlined in my first answer) and then iterate over the nodes in the same order traversing the tree as you go. Finally you would simply look up the dimension in your `Dictionary` or `HashMap` and you would get the result of the recipe.

*Just for kicks I went and implemented this \- which will probably clarify my answer. **Also**: I realise this is a different answer - and rightfully so: it's a different solution.*
> 15 votes

# Answer
You have to remember that Minecraft only uses a very small set of possible recipes, so there is no need for anything all that smart.

That said what I would do is find the smallest grid that fits (i.e. ignore empty rows and columns to find out if it's a 2x2 or 3x3, or 2x3 (door)). Then loop through the list of recipes with that size, simply checking whether the item type is the same (i.e., at worst 9 integer comparisons in minecraft since it uses an integer type id for items and blocks) and stop when you find a match.

This way also makes the relative position of the items irrelevant (you can put a torch anywhere on the crafting grid and it will work because it sees it as a 1x2 box, not a 3x3 box which is mostly empty).

If you have a huge amount of recipes so that doing a linear search through the possible matches takes to long it would be possible to sort the list and do a binary search (O(log(N)) vs O(N)). This would cause some extra work in building the list, but this can be done at startup once and kept in memory afterwards.

Also one last thing, to allow flipping the recipe horizontally simplest would be to just add the mirrored version to the list.

If you want to do it without adding a second recipe you can check whether the input recipe has an item in \[0,0\] with higher id than in \[0,2\] (or \[0,1\] for 2x2, no check needed for 1x2 and if so mirror it, if not continue checking the next row until you've reached the end. Using this you also have to make sure the recipes are added in the correct rotation.
> 23 votes

# Answer
Seeing if a certain grid configuration matches a certain recipe is simple if you encode the **3x3 grid as a string** and use a **regular expression** match. Speeding up the look up is a different matter, which I'll talk about in the end. Read on for more information.

**Step 1) Encode grid as String**

Simply give a char id to each type of cell and concatenate everything side by side in this order:

```
123
456 => 123456789
789

```

And as a more concrete example, consider the stick recipe, where W stands for wood and E is an empty cell (you could simply use an empty char ' '):

```
EEE
WEE => EEEWEEWEE
WEE

```

**Step 2) Match Recipe using Regular Expression (or String.Contains with a bit of processing on the data)**

Continuing from the example above, even if we move the formation around, there's still a pattern in the string (WEEW padded by E on both sides):

```
EEW
EEW => EEWEEWEEE
EEE

```

So no matter where you move the stick around, it will still match the following regular expression: `/^E*WEEWE*$/`

Regular expressions also let you perform the conditional behavior you mentioned. For instance (made up recipe), if you wanted a pickaxe made of iron *or* stone to give the same result, i.e:

```
III    SSS
EWE or EWE
EWE    EWE

```

You could combine both into the regular expression: `/^(III)|(SSS)EWEEWE$/`

Horizontal flips can also be added just as easily (using the | operator too).

**Edit:** *Anyway, the regex part is not strictly necessary. It's just one way to encapsulate the problem in a single expression But for the variable location problem you could just as well trim the grid string of any padding spaces (or E's in this example) and do a String.Contains(). And for the multiple ingredient problem or the mirrored recipes, you could just handle all of them as multiple (i.e. separate) recipes with the same output.*

**Step 3) Speeding up Lookup**

As for reducing the search, you will need to create some data structure to group recipes together and help with lookup. *Treating the grid as string has some advantages here too*:

1. You could define the "length" of a recipe as being the distance between the first non-empty character and the last non-empty character. A simple `Trim().Length()` would give you this information. Recipes could be grouped by length and stored in a dictionary.

*or*

An alternative definition of "length" could be the number of non-empty characters. Nothing else changes. You could group recipes by this criteria too.
2. If point number 1 is not enough, recipes may also be further grouped by the type of the first ingredient that appears in the recipe. This would be as simple as doing `Trim().CharAt(0)` (and guarding against Trim resulting an empty string).

So for instance you would store recipes in a:

```
Dictionary<int, Dictionary<char, List<string>>> _recipes;

```

And perform the lookup as something like:

```
// A string encode of your current grid configuration
string grid;

// Get length and first char in our grid
string trim = grid.Trim();
int length = trim.Length();
char firstChar = length==0 ? ' ' : trim[0];

foreach(string recipe in _recipes[length][firstChar])
{
    // Check for a match with the recipe
    if(Regex.Match(grid, recipe))
    {
        // We found a matching recipe, do something with it
    }
}

```
> 14 votes

# Answer
I can't tell you how the Minecraft one works - although I am sure if you looked at MCP (if you have a legal copy of Minecraft) you could find out.

I would implement this as follows:

1. Have some disk-based dictionary/hashmap (*B+Tree/SQL-Light*) - the value would be the item ID of the recipe result.
2. When a user is crafting something simply find the first row/column with an item **INDEPENDENTLY**; combine those into an offset.
3. Find the last row/column with an item, again, independently.
4. Compute the width and height from the items and add it to the key.
5. Loop over the range of the bounding box you just computed and append the ID of each item (using your usual `for (y) { for (x) }`).
6. Look the key up in the database.

So for example lets say we have two ingredients; X and Y and blanks being \*. Take the following recipe:

```
**X
**Y
**Y

```

First we work out the bounding box, yielding `(2,0)-(2,2)`. Therefore our key would look like this `[1][3]` (1 width, 3 height). Next we loop over each item within the bounding box and append the ID, thus the key becomes `[1][3][X][Y][Y]` \- you then look this up in your dictionary/DB and you will get the result of that recipe.

To explain the independence in step 2 more clearly, consider the following recipe:

```
*XX
XXX
XX*

```

The top/left is clearly at 0,0 - however the first item you would typically encounter would be either 0,1 or 1,0 (depending on your loop). However if find the first non-empty column as well as the first non-empty row and combine those co-ordinates you will get 0,0 - the same principal applies to the bottom/right of the bounding box.
> 3 votes

# Answer
Here is how I did it in Block Story:
> 2 votes

---
Tags: minecraft-modding, patterns, search
---


title: unity3d nullreferenceexception

text:
# Question
Title: unity3d nullreferenceexception
i want to display a mesh sequence so i imported my obj files and found a script and partially edit it a bit.My project looks like this:

the script is this:

using UnityEngine; using System.Collections;

/\** * Animate a mesh by cycling through different meshes. * @author bummzack \*/ public class MeshAnimation : MonoBehaviour {

```
public Mesh[] Meshes;
public bool Loop;
public float FrameDuration;

private int _index;
private bool _playing = true;
private float _accumulator;
private MeshFilter _meshFilter;

public void Start()
{
    _meshFilter = GetComponent<MeshFilter>();
    _index = 0;
}

public void Update()
{
    _accumulator += Time.deltaTime;

    if(_accumulator >= FrameDuration){
        _accumulator -= FrameDuration;
        _index = (_index + 1) % Meshes.Length;

        if(_index == 0 && !Loop){
            Stop();
            return;
        }

        _meshFilter.mesh = Meshes [_index];
        print ("Hello World");
    }
}

```

}

the line that causes the problem is this:

\_meshFilter.mesh = Meshes\[\_index\];

and the problem shown in the console is this:

NullReferenceException MeshAnimation.Update () (at Assets/MeshAnimation.cs:43)

i know it has something to do with Meshes\[\_index} being null but i cant find the solution because i think the Meshes array is properly filled.Can anyone suggest a solution? Thank you all in advance.

# Answer
> 0 votes
michael.bartnett made a good point in the comments, and the only object left to put the blame on is the `MeshFilter`. Be sure one is added via the editor as a gameobject component, otherwise `GetComponent<MeshFilter>()` will return `null`.

**Extra piece of advice!** Do this for every `GetComponent<T>` call:

```
SomeComponent = GetComponent<SomeType>();
if (SomeComponent == null)
{
    Debug.LogError("ERROR! Unable to get component in GameObject: " + this.name);
}

```

This will log an error message in the console every time a component is not found. It will help you a lot with debugging.

**Extra piece of advice #2!** You can use the `[RequireComponent (typeof (YourComponent))]` attribute to make things easier. Take a look at this:

http://docs.unity3d.com/Documentation/ScriptReference/RequireComponent.html

In short, setting `[RequireComponent (typeof (MeshFilter))]` in your script will force Unity to auto-add a MeshFilter component to any GameObject to which you add your script.

---
Tags: unity
---


title: Realistic 2D Planetary Physics Engine?

text:
# Question
Title: Realistic 2D Planetary Physics Engine?
I'm doing a spaceflight simulator in C++ (using Allegro 5), and I realised that I could just use a physics engine instead of writing my own physics.

So that's what I'm doing.

Since this is going to be a 2D only (for simplicity's sake) simulation, I've looked at 2D physics engines only. And since this will be running on low-end hardware, just not using the z-axis of a 3D engine won't work.

I've narrowed it down to the two big physics engines: Box2D and chipmunk. I'm trying out Box2D now, but the manual says that:

> Box2D works with floating point numbers and tolerances have to be used to make Box2D perform well. These tolerances have been tuned to work well with meters-kilogram-second (MKS) units. In particular, Box2D has been tuned to work well with moving objects between 0.1 and 10 meters. So this means objects between soup cans and buses in size should work well. Static objects may be up to 50 meters big without too much trouble.

Obviously I'm going to be using Box2D for objects ranging from 100 m to 1.4e9 m (from a ship to the Sun). However, most of the time I'm going to be flying around in a ship (no collisions), or parked on the surface of a planet. Of course, there will also be accelerations of up to 275 m/s/s (at the surface of the Sun).

Is this order of magnitude going to work with Box2D? Has anyone worked with this kind of stuff in Box2D before? Should I just try another physics engine (suggestions welcome)?

# Answer
> 3 votes
Well, if you look at it, 1.4e9 is *much* greater than 50, so obviously it isn't going to work that well. As to whether you should use another physics engine, I'm apprehensive - I can't think of a physics engine that would work well with objects that large. The computations would lose all accuracy - floating point arithmetic only works with numbers that are relatively similar in magnitude - and you may have the issue of overflow.

My personal opinion is that there won't be a (publicly available) physics engine to handle planetary physics, and that it would be best to either make the ship *much* bigger (and then scale down), or to never come that close to planetary objects - in which case you could use abstract calculations for the planetary physics, and background geometry for the planets, until you come to park - in which case you could then play a cut-scene, or use a different level/world for the landing sequence; this would culminate in a final world for the actual planet. Of course, that many worlds get confusing - it's up to you to decide which way you should go, but I hope I've helped answer your question.

EDIT:

From what you've said, my advised next course of action would be to salvage what you can from your previous physics engine and start again - I still don't think that there's a physics engine out there which can handle planetary physics (but correct me if I'm wrong). In this case, you'd almost certainly benefit from rewriting it from scratch anyways - you'll end up learning a lot more about physics, and it'll likely perform better.

---
Tags: 2d, physics, physics-engine, simulations
---


# Question
Title: Handling Different Aspect Ratios for a Multiplayer Game
I'm currently designing a competitive 2D, side-scrolling multiplayer game and I want support full screen play at any aspect ratio (e.g., 4:3, 5:4, 16:10, 16:9). Doing that is not so much a problem, my concern is that the viewable area of the game for a player with a 4:3 monitor will differ from that of a player with a 16:9 monitor quite a bit. In a competitive multiplayer game where being able to see more of the game world gives a player a significant advantage over players who cannot this is a serious problem.

So far I've come up with two possible solutions for this:

1. Just support different aspect ratios and don't worry about it.
2. Pick a specific aspect ratio (say 16:9) and do a best fit on all other aspects (i.e., letterbox or pillarbox)

Option 1 doesn't suit me because it's a lazy cop out. Option 2 is much better but then a portion of the screen will be unused for some players. Certainly not the end of the world but not incredibly desirable either. This could be mitigated by rearranging the UI based on the aspect ratio and filling the letter/pillarbox with UI elements instead of simple black bars making better use of available screen real estate.

How is this sort of thing handled in games like Quake, CoD, StarCraft and Battlefield?

# Answer
Basic rule of thumb is: **Don't artificially handicap the player.**

It is each players own decision if they want to invest into better hardware so they can play the game better.

You wouldn't limit the framerate to 30 so that people with better GPU have no advantage over people with a bad GPU due to more fluid gameplay, you wouldn't limit the update rate of the input so that people who invested in better mouses or keyboards would have no advantage. It's not your role as game designer to play the judge for those who like to play competitively with sub-optimal hardware.

The games you mentioned do nothing, and as far as I know there are no games who do such a thing. There maybe a few games who make the amount of displayed content independent from the resolution, but most likely out of reasons of artistic control not because of the idea of fairness.

If the limited amount of visible information is important for the gameplay, you might want to apply techniques like "Fog of War".
> 1 votes

---
Tags: 2d, game-design, multiplayer, side-scroller, aspect-ratio
---


# Question
Title: Translate camera position toward camera orientation
I have a camera position (Vec3) and camera horizontal/vertical angle. Now I want to translate my camera position toward the current camera orientation - what is the best way to do that? I am sure it's simple but the logic escapes me.

(I am using GLM math lib btw)

# Answer
The best way to do that is to generate a vector in the direction your camera is pointing. The simplest way to do it would be to rotate it around the corresponding axes:

```
Vec3 GetCameraDir(float horiz, float vert) {

    // Start out pointing to the right
    Vec3 dir = Vec3 (1, 0, 0);

    // Rotate dir around the Y axis by your horizontal angle
    dir = RotateY(dir, horiz);

    // Rotate dir around the X axis by your vertical angle
    dir = RotateX(dir, vert);

    return dir;
}

```

Once you have this vector, you can translate your camera by some amount along this direction:

```
// Translate the camera's position by your time-step times the speed in the
// direction that your camera is pointing
Vec3 newCamPos = camPos + dT * speed * GetCameraDir(horiz, vert);

```

That being said, you may want to take a look at this question:

Camera rotation - First Person Camera using GLM
> 1 votes

# Answer
Given your description, your camera representation might look like this. I also included the headers of your maths library GLM needed for the following implementation.

```
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/constants.hpp>
using namespace glm;

struct Camera
{
    vec3 Position;
    vec2 Angles;
    mat4 View, Projection;
};

Camera cam;

```

To more your camera, you can first calculate the vector for the directions forward and sidewards (in this implementation to the right side). Then update the position based on that vector, the speed of movement, and the elapsed time `Delta`. Relying on the time is important to make the movement independent from the FPS of your game. Otherwise the camera rotation would be faster on faster machines and vise versa.

Calculating the forward vector is just basic trigonometry. If you have no basic understanding of sine and cosine you can look it up on Wikipedia or somewhere else. After computing the forward vector, we can derive the sidewards vector like shown in the code.

```
void Move(vec3 Amount, float Delta, float Speed = 10.f)
{
    vec3 forward = vec3(sinf(cam.Angles.x), 0, cosf(cam.Angles.x));
    vec3 right = vec3(-forward.z, 0, forward.x);

    cam.Position   += forward * Amount.x * Speed * Delta;
    cam.Position.y +=           Amount.y * Speed * Delta;
    cam.Position   += right   * Amount.z * Speed * Delta;
}

```

As you can see we only depend on the view direction for the X and Z coordinate. Otherwise the player could fly if the player walks facing the sky.

Because you haven't especially asked about rotation, I guess you already implemented that. But as a reference this might help other users. The negation because of the different direction of the world coordinates and the mouse coordinates.

```
void Rotate(ivec2 Amount, float Delta, float Speed = .08f)
{
    cam.Angles += vec2(-Amount.x, -Amount.y) * Speed * Delta;
}

```

The last step is to create the view matrix. Since you use GLM you can use its `lookAt` function to do so. Before, I wrap the horizontal angle if it exceeds 360 degrees and I limit the maximum vertical angle a bit. So the player wouldn't loose orientation if he looks straight to the top or to the bottom and rotate the camera then.

```
void Calculate()
{
    const float pi = glm::pi<float>();
    if      (cam.Angles.x < -pi) cam.Angles.x += pi*2;
    else if (cam.Angles.x >  pi) cam.Angles.x -= pi*2;

    const float margin = 0.2f;
    if      (cam.Angles.y < -pi/2+margin) cam.Angles.y = -pi/2+margin;
    else if (cam.Angles.y >  pi/2-margin) cam.Angles.y =  pi/2-margin;

    vec3 lookat(
        sinf(cam.Angles.x) * cosf(cam.Angles.y),
                             sinf(cam.Angles.y),
        cosf(cam.Angles.x) * cosf(cam.Angles.y)
    );

    cam.View = lookAt(cam.Position, cam.Position + lookat, vec3(0, 1, 0));
}

```

If you still have questions about that, feel free to ask.
> 1 votes

---
Tags: c++, opengl, glm
---


title: OpenGL VBO Additional Attributes

text:
# Question
Title: OpenGL VBO Additional Attributes
If I have a buffer with my vertices, normals and texture coordinates, and I use glDrawArrays to draw the VBO to the screen, how can I send attributes per vertex that I placed in an array to the shader program? I'm making a voxel terrain, and every chunk is 1 VBO, this works all great, but I want to send the light value of each block (Just an array filled with int's) to the shader as well, how would I do that?

Edit: After reading some comments, here some clarification: I'm trying to avoid the deprecated glVertexPointer etc, so I'm using Vertex Arrays. Here is the layout of my vertex array:

X, Y, Z, NX, NY, NZ, X, Y, Z, NX, NY, NZ,X, Y, Z, NX, NY, NZ

I'm using this to draw it: (ofcourse with the array buffer bound)

```
glVertexAttribPointer(0, 3, GL_FLOAT, false, 12, 0);
glVertexAttribPointer(1, 3, GL_FLOAT, false, 12, 12);

glDrawArrays(GL_TRIANGLES, 0, arraySize / 6);

```

However I get some weird shapes on my screen. Apart from the light problem, that is essentially the same thing, I don't get why this doesn't just work. When I remove the normals, and use just 1 vertexattribpointer it works fine. Yes, the attributes are bound to in\_position and in\_normal, and the vertex shader is nothing more than gl\_Position = gl\_ModelViewProjectionMatrix * vec4(in\_position, 1.0);

Thanks!

This is what I get:

(This are 6X6 chunks, so this code is called 6\*6 times.)

# Answer
> 1 votes
```
glVertexAttribPointer(0, 3, GL_FLOAT, false, 12, 0);
glVertexAttribPointer(1, 3, GL_FLOAT, false, 12, 12);

```

This doesn't make sense. Your stride is 12 bytes, so OpenGL will offset the current location for that attribute by 12 bytes for each vertex.

But your data is *interleaved*. The first 3 floats are a position, and the next three are a normal. Your 12-byte stride means that the positions are *tightly packed*. So the positions for vertex 0 will be the first 3 floats, the postiions for vertex 1 will be the *next three floats*. You want it to be 6 floats from the first, not three.

Your stride for both needs to be 24, not 12.

---
Tags: opengl, shaders, glsl, vbo
---


# Question
Title: How to add a movieclip to the stage then make it move down?
I am making a game where i want to spawn zombies then make them move down the screen. I also want to have multiple on the screen at once. I have tried multiple ways now but none of them have worked.

Here is my code

```
if ((zombie == 1)||(zombie == 3)||(zombie == 5)||(zombie == 7))
{
    var Z = new Z;
    Z.x = 403.25;
    Z.y = -86.9;
    Z.rotation = 90;
    addChild(Z)
    zombie += 1;
}

//Functions
function startzombie(event)
{
    trace("start zombies")
    zombie = 1;
    addEventListener(Event.ENTER_FRAME,zombiemove)
}
function zombiemove(event:Event)
{
    Z.y += 1;
}

```

Z is the zombie

# Answer
> 3 votes
When you say `Z.y += 1`, you will get an error because Z is the zombie class, not the zombies themselves. The class is the blueprint you use to create zombies, by doing `new Z`. `new Z` is what actually creates a zombie object, and the zombies objects are what have the `y` property, not the Z class. This lets you create multiple zombies, each with their own independent y.

Let's start with just one zombie:

```
trace("start zombies");
var zombie : Z = new Z();
addChild(zombie);
addEventListener(Event.ENTER_FRAME,zombieMove);

function zombieMove(event:Event) : void
{
    zombie.y += 1;
}

```

Z is the class for a zombie, so I instantiate it by doing `new Z`. I store this new zombie object in a variable called `zombie`. Then, to move that zombie, I change `zombie.y`.

Now how do we move multiple zombies? Well, one way is to add the `ENTER_FRAME` listener to the object itself:

```
function createZombie() : void {
    var zombie : Z = new Z();
    zombie.x = Math.random() * 400; // randomly position zombie
    addChild(zombie);
    zombie.addEventListener(Event.ENTER_FRAME,zombieMove);
}

function zombieMove(event:Event) : void
{
    // move the zombie that caused this event
    event.currentTarget.y += 1;
}
// create two zombies
createZombie();
createZombie();

```

In this case, we add the `ENTER_FRAME` listener to the zombie when we create it. Note that the `zombie` variable only exists inside the `createZombie` function, so we can't use it in `zombieMove` anymore. Besides, which zombie would it refer to? Instead, in the `zombieMove` function, we use `event.currentTarget`. This is a property of the `event` that tells you which object is dispatching the event (a zombie). Since each zombie has its own listener, this function gets called for both zombies.

Another method is to store the zombies in an array:

```
var zombies : Array = new Array();

function createZombie() : void {
    var zombie : Z = new Z();
    zombie.x = Math.random() * 400; // randomly position zombie
    addChild(zombie);
    zombies.push(zombie); // add the zombie onto the list
}

function zombieMove(event:Event) : void
{
    // move all of the zombies in the zombies list
    for each(var zombie : Zombie in zombies) {
        zombie.y += 1;
    }
}

addEventListener(Event.ENTER_FRAME, zombieMove);

// create two zombies
createZombie();
createZombie();

```

In this case, when we create a zombie, we stick it in a list (`zombies`). We are back to one `ENTER_FRAME` listener, but now this listener will move all of the zombies in the list in one shot.

You also may want to rename your class from `Z` to `Zombie`. It's a common convention to have classes start with uppercase (`Zombie`), with the corresponding objects start with lowercases (`zombie`, `zombie1`, `myZombie`, etc.) This will help clear up your confusion about classes and objects -- the lowercased objects have the properties you want.

---
Tags: actionscript-3
---


# Question
Title: Is there a 3d animation software that prioritizes working with code rather than GUI?
All of the 3D animating softwares I've faced are centered around using GUI to work: windows, menus, mouse clicks, mouse adjustments, keyboard shortcuts. As a programmer, I find that limiting. In order to have full control over an animation, it'd be interesting to use code. For example, say you wanted to animate a magic sword which color depended on speed. Without programming, that's not possible at all.

Thus I ask: is there a 3D animation softwares that target coding, not GUI work?

# Answer
Dokkat, from my experience I can tell that Unity 3d Mecanim animation has a sophisticated system for all sorts of animations, with the Mecanim tools the ammount of code you MUST write is limited, but the sky's the limit.

You have plenty options to choose from. http://docs.unity3d.com/Documentation/ScriptReference/Animation.html

I have to note that it will only be usefull to use Unity animation, if you are going to use Unity as your native environment. You can't export those animations into Maya/Max etc.

Edition of the Magic Sword colour can be done using the V4 in the Color class http://docs.unity3d.com/Documentation/ScriptReference/Color.html

Function "operator Color Colors can be implicitly converted to and from Vector4."
> 1 votes

# Answer
Major 3D animation suites support writing custom plugins/extensions (scripts and/or .dll/.so files). For example Blender use Python for scripting (API).

This may or may not be enough for what you are trying to achieve because not all \[custom\] data (e.g. colour changes you have mentioned) will be exported to supported formats thus you might be forced to write your own exporter (or modify existing).
> 1 votes

---
Tags: 3d, animation, software-engineering, software-rendering
---


# Question
Title: How do I get a Rigged 3D Model made in blender to display and animate on the iPhone?
I have a rigged model in blender of a man walking, I would like to know how to get this to display and animate on the iPhone and if their is a good free game library out their that lets me do it (even if it means saving as another format).

I've tried Cocos3D with no luck as the convertor from collada to Pod is crap (for lack of a better word)

# Answer
There is also the open source Gamekit A cross-platform 3D game engine using Ogre or Irrlicht and Bullet for Windows, Linux, Mac, Android and iPhone

http://code.google.com/p/gamekit/
> 1 votes

# Answer
The simplest 3D game engine to use for getting an animated model from Blender onto iPhone is Unity, but that's not free: http://unity3d.com/unity/editor/importing

The best free option is probably Oolong: http://code.google.com/p/oolongengine/

---

Incidentally, the last time I was working with 3D on iPhone I was using miniB3D, the iOS port of miniB3D, which itself was an OpenGL port of Blitz3D:

https://github.com/si-design/minib3d

Unfortunately while there used to be a good .b3d exporter for Blender, I don't think that works in the latest version of Blender.
> 0 votes

# Answer
I recommend giving SIO2 a go. I've tried it a bit couple of years back with Blender2.4x and it was very easy to get started with.
> 0 votes

---
Tags: 3d, iphone, blender
---


# Question
Title: How to use an object created in a function in other functions?
I am making a game where i want to be able to shoot zombies to make their health go down, but i get a null property error on objb.

i have declared abjb and objz as Object variables

Here is my code for the bullet:

```
function mouseDown(event)
{
    var b = new Bullet();
    b.x = character_mc.x;
    b.y = character_mc.y;
    b.angleRadian = Math.atan2(mouseY - character_mc.y,mouseX -character_mc.x);
    b.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
    addChild(b);
}

function bulletEnterFrame(event)
{
    var b = event.currentTarget;
    objb = event.currentTarget;
    b.x +=  Math.cos(b.angleRadian) * speedb;
    b.y +=  Math.sin(b.angleRadian) * speedb;
    b.rotation = b.angleRadian * 180 / Math.PI;
    if (b.hitTestObject(objz) == true)
    {
        removeChild(b);
        b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
    }
    if (b.x < 50 || b.x > 675 || b.y < 50 || b.y > 500)
    {
        removeChild(b);
        b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
    }
}

```

and here is my code from the zombie:

```
function createZombie():void
{
    var zombie : Z = new Z();
    zombie.rotation = 90;
    zombie.height = 85.35;
    zombie.width = 55.9;
    zombie.x = 403.25;
    zombie.y = -86.9;
    addChild(zombie);
    trace("spawned the zombie");
    zombie.addEventListener(Event.ENTER_FRAME,zombiemove);
}

function zombiemove(event:Event)
{
    var dead:Number;
    var zombie = event.currentTarget;
    objz = zombie;
    dead = zombiehits;
    zombie.y +=  1;
    if (zombie.hitTestObject(objb) == true)//this is where the error is
    {
        dead -= 1;
    }
    if (dead == 0)
    {
        removeChild(zombie);
        zombie.removeEventListener(Event.ENTER_FRAME,zombiemove);
    }

}

```

# Answer
Your code is quite hard to read, I'm a bit puzzled by `objb` being a single global as that would imply that there can only ever be one bullet at a time.

Your use of `Event.ENTER_FRAME` seems to be one big race condition. It seems pretty clear that it matters in what order the functions are called, but with functions constantly being attached and removed from the event it's hard to grasp exactly what will happen.

In any case, if the player hasn't fired a bullet, what would the value of `objb` be?

Numerous changes could be made, but I'd suggest the following:

* Attach just one frame handler function to `Event.ENTER_FRAME` and have that function take care of everything that has to happen in a frame.
* Store all of your zombie objects in a list, store all of your bullet objects in a list. Iterate over these lists as necessary in your frame handler function.

With just one event handler you have got complete control of the handling order.
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: Selecting the entities needed for rendering
Currently I'm sorting and looping every entity on my level but I really don't need to. Only a small subset would be on screen.

If I could extract a list of entities from my main list that are on screen (or near the screen), that would be great, but I believe maintaining a different kind of list like a quad-tree or something might be in order, but I have no experience with such things.

How can I do this?

# Answer
> 2 votes
There are a few methods I can think of, and all of them involve partitioning - Binary Space Partitioning, Quadtrees (and by extension, Octrees) and k-d trees.

Binary Space Partitioning: Binary Space Partitioning, or BSP, works by dividing the list of polygons (or in your case entities) into 2, then subdivides those into 2 recursively, until it reaches a predetermined condition (e.g. 10 entities in a partition). The main benefit of BSP is that it allows you to determine groups of objects which must be drawn quickly. The disadvantage is that it can end up taking a lot more memory than the original list (because some objects are split in two - to make this work with entities, you would have to alter the algorithm slightly).

Quadtrees/Octrees: First of all, to make things clear - quadtrees and octrees work on ***exactly*** the same principle of each other, ***but*** quadtrees are used in 2-dimensional space, and octrees in 3-dimensional space. This is as a quadtree divides areas into 4 (top-left, top-right, bottom-left, bottom-right), whereas an octree divides areas into 8 (top-front-left, top-front-right, top-back-left, top-back-right, etc.). Octrees basically work by sorting the entities into the different areas, and then further subdividing the relevant/visible ones.

K-d trees: Finally, there are k-d trees. These are similar to BSP and Octrees in the sense that they divide up the area, but they operate on dimensions, and are always binary. I'll be honest, I'm not 100% clear on k-d trees - it would be best to do your own research.

At this point, I would advise reading about these (and googling the terms Denis suggested), and then making a decision. I'd go with octrees myself, but I don't know exactly what conditions you're under and what you're trying to do with these entities.

---
Tags: 2d, entity-system, game-loop
---


# Question
Title: How do I connect different parts on Blender?
I'm new to blender, trying to make my first model. I've got a body, a shoulder, an arm and a head - all separated. How do I connect them correctly?

shapes http://dl.dropbox.com/u/62862049/Screenshots/fr.png

# Answer
if parts are in the same object:

You can make new faces by selecting at least 2 edges and typing \[F\]. If you 2 have edgeloops with the same edge count you can use bridge \[W\]-\>Bridge. You can also merge vertecies. To do so, you need to select verts desired to be merged and type \[alt\]+ \[M\] and choose option. you can also access this menu from \[W\]-\>Merge

If parts are multiple objects:

select multiple objects and type \[ctrl\]+\[j\] and it will join selected to active object

tip: when you are making model and know that it will need connecting przepare the same edge count on both borders.

edit:

I would advice you to learn about topology if you are serious about modeling, ex.: http://cgcookie.com/blender/cgc-series/learning-mesh-topology-collection/
> 4 votes

# Answer
You can do that using Vertex Snapping :) http://wiki.blender.org/index.php/Doc:2.4/Tutorials/Modeling/Meshes/Snap\_to\_Mesh

You can merge two vertexes/faces/edges so that they become one

Here I found some Youtube vid tutorial that might help you get started: Search for "Vertex Snapping Blender" https://www.youtube.com/watch?v=0hCwO1KfbcQ
> 1 votes

---
Tags: blender
---


# Question
Title: How can auto-click software be detected to stop botting/cheating?
I have to completely change my question, because it was far too general. I now want to focus on how I can detect one type of cheating method.

How can auto-clicking be detected? In general, I am referring to software that will simulate mouse clicks or keyboard input automatically. It seems this would be useful for botting behaviour.

Can my software see other software the user's computer is running. If so, how does the software know what the other program is doing? Will it need to check the byte code for routines that simulate mouse/keyboard input?

Would it be useful for my software to detect if the mouse is jumping across the screen in a non-human-like behaviour? That is the first thing I can think of to stop it, as it would be the simplest but also the cheater might be able to simulate mouse movement that is human-like.

I should probably mention that I am most comfortable with Python and C++, and I am currently learning the Windows API.

# Answer
> 8 votes
That can be tricky if the auto clicker has a Random var for the interval inbetween the clicks.

There are a few things you can do to detect/stop these guys: 1) Disable the part were the clicking occurs, if people need a bot to do some action it is simply too boring for a human being. (my no.1 suggestion, as it is not in your business to bannish players, and if the game itself is boring it is only your fault)

2) As for the detection of an auto clicker. There are a few types of auto clicking bots (I scripted bots for RuneScape) and there you would have:

Clicking on a specific 3d game object mesh inside the editor, all objects have an id. (ultra hard to detect).

Clicking on one specific gamespot for eg. the minimap, always one exact pixel in the players current pos. Players can set up an auto mouse to click in one point. (less complex)

1)

> First thing you want to set, is the player online time table. - if a player has an "insomniac" entry (playing over 20h/day) mark him automatically as suspicious. In the game Tibia there is a fan website Pskonejott.com where anyone can see the online time of all players. Some stay up for 40 hours, I hardly believe it is Redbull rather than C++ :) Add it to his record if he plays over X hours.
>
> http://www.pskonejott.com/otc\_insom.php

2)

> Make up a Log for actions and if the time between the actions is nearly identical mark that person as a bot. Player clicks on something, then after some time he clicks again. if he repeats this action every five minutes +- (1-2)% for 5hours, mark him as suspicious.

3)

> Try to implement the web Captcha once every few hours if it is a browser game it will be easy to do. For instance the player gets\> teleported and then he is supposed to type in the Captcha. No bot so far has been able to handle that. (Some humans got problems with that too) http://areyouahuman.com/demo/ Doesn't matter how many mistakes he makes, If he can't do it for 10 minutes/loggs out add this to his record.
>
> http://areyouahuman.com/demo/

4)

> Set up a quick report abuse system. With an ingame report abuse button. Encourage players to report suspicious actions, tell them to ask the suspicious characters if they are alive. If the player responds immediately/the reporter doesn't speak to him directly using his name "Hey Player, you there?" it likely means that the report is fake.

5)

> Give all your workers ingame characters as Moderators/Game Masters along with volountary game masters. They actually should sometimes log into the game to know what is going on, and get a real bio from the players not just forums, if a player has a feeling that he might actually meet a Moderator it could prevent some of them from botting.

6)

> Have a community manager to manage the bans, there always should be a judge to make sure no one gets deleted without an important issue. He should look through the player logs marked as suspicious and define if his actions can actually be botting.

---
Tags: c++, anti-cheat
---


title: Pygame Bounding Box at Player Feet

text:
# Question
Title: Pygame Bounding Box at Player Feet
I'm new to python and pygame and am trying to build a very simple "game" (it's more of a test for me to figure things out) in which you move a character around the screen and he can collide with walls and things. Everything is broken up into 32x32 tiles and the player is 32x64. This means that when his head hits a wall his feet are 2 tiles away and I've been trying to get it so that he's only 1 away, ie. I'm after a 32x32 hitbox starting at x=0, y=32 on the player image.

Do I need to create a separate rect to deal with this and if so how would I go about implementing it? Any help would be greatly appreciated.

Here's the code for my player class so far, hopefully it's not too messy:

```
class Player(pygame.sprite.Sprite):
'''The Main Player Class'''
def __init__(self, x, y):
    pygame.sprite.Sprite.__init__(self) #Call sprite initialiser
    self.image, self.rect = load_image("char.png")
    screen = pygame.display.get_surface()
    self.area = screen.get_rect()
    self.rect.x, self.rect.y = x, y
    self.x, self.y = x, y
    self.vx, self.vy = 0, 0
    self.movespeed = 2

def update(self):
    self._walk()

def _walk(self):
    if self.vx != 0:
        self._walk_single_axis(self.vx, 0)
    if self.vy != 0:
        self._walk_single_axis(0, self.vy)

def _walk_single_axis(self, vx, vy):
    "normalise for diagonal movement if necessary"
    if self.vx != 0 and self.vy !=0:
        norm = 1/(2**0.5)
    else:
        norm = 1
    "set new x and y positions"
    self.x += vx * self.movespeed * norm
    self.y += vy * self.movespeed * norm
    self.rect.x, self.rect.y = self.x, self.y

    "check for collisions with any walls"
    for wall in walls:
        if self.rect.colliderect(wall.rect):
            if vx > 0: #collide with the left side of the wall
                self.rect.right = wall.rect.left
                self.x = self.rect.x
            if vx < 0:
                self.rect.left = wall.rect.right
                self.x = self.rect.x
            if vy > 0:
                self.rect.bottom = wall.rect.top
                self.y = self.rect.y
            if vy < 0:
                self.rect.top = wall.rect.bottom
                self.y = self.rect.y

    "bound the player within the screen edges"
    if self.rect.x < self.area.left:
        self.rect.x = 0
    if self.rect.x > self.area.right-32:
        self.rect.x = self.area.right-32
    if self.rect.y < self.area.top:
        self.rect.y = 0
    if self.rect.y > self.area.bottom-64:
        self.rect.y = self.area.bottom-64

```

self.x and self.y are there because applying the movement directly to self.rect.x and self.rect.y caused the character to move at different speeds depending on which diagonal direction he was travelling in. self.vx and self.vy just return either +1 or -1 depending on the direction of travel.

# Answer
> 0 votes
You want to split the rendering and collision detection into separate variables:

```
self.image, self.rect = load_image("char.png")
collisionRectPos = (self.rect.left, self.rect.top + 32)
collisionRectSz = (self.rect.width, self.rect.height - 32)
self.collisionrect = pygame.Rect(collisionRectPos, collisionRectSz)

```

Then when you go to do your collision detection, simply collide against the collision rect. Be sure to update your `self.rect` variable *after* you do your collision detection:

```
"set new x and y positions"
self.x += vx * self.movespeed * norm
self.y += vy * self.movespeed * norm
self.collisionrect.x = self.x
self.collisionrect.y = self.y + 32

for wall in walls:
    if self.collisionrect.colliderect(wall.rect):
        if vx > 0: #collide with the left side of the wall
            self.collisionrect.right = wall.rect.left
            self.x = self.collisionrect.x
        if vx < 0:
            self.collisionrect.left = wall.rect.right
            self.x = self.collisionrect.x
        if vy > 0:
            self.collisionrect.bottom = wall.rect.top
            self.y = self.collisionrect.y - 32
        if vy < 0:
            self.collisionrect.top = wall.rect.bottom
            self.y = self.collisionrect.y - 32

self.rect.x, self.rect.y = self.x, self.y

```

---
Tags: python, pygame
---


# Question
Title: DXGI and 2+ full screen displays on Windows 7
I am developing a program that needs two full screen Direct3D dispalys. According to the documentation I should create the swap chains in windowed mode and then switch to full screen mode. While this works fine on Windows 8 (currently I'm just using Alt-Enter to do the switch), it does not work on Windows 7. On Windows 7 I get a problem similar to this issue where the screen that has most recently been switched to full screen works fine, but the other screen, which was previously working just fine in full screen, goes black (and stays at the same full screen resolution) until I take it out of full screen.

You can find my mess of a rough prototype at this tag: github.com/AllenPestaluky/InputLagTimer/tree/DXGI

Apparently there have been other bugs relating specifically to Windows 7 in the past... But I appear to be getting an issue that is slightly different: scalibq.wordpress.com/2012/05/25/the-story-of-multi-monitor-rendering/

Also, I have tried disabling DWM Composition like suggested in the linked question, but that did not do anything to resolve the problem..

Please let me know if there's any more information I can provide about the issue... I guess worst case scenario is I simply fall back on DX9 which apparently works fine for multi-monitor full screen setup...

# Answer
> 1 votes
I think I may have figured out the cause of the problem: It may be because I was creating multiple ID3D11Device for the same Adapter.

My code was overly complex for what I needed as I was following techniques introduced in this article when I really didn't need anything more than a single thread for all windows and rendering. After sharing the same ID3D10Device for each Render Target (one Render Target per Output, one ID3D10Device per Adapter) I have successfully got DXGI with DX10 rendering two full screen displays as shown in my rough memory-leaking proof of concept.

Since this was my first time working with any of this tech, I used this article to help me along with this process: https://stackoverflow.com/questions/10744788/display-different-images-per-monitor-directx-10?answertab=active#tab-top

---
Tags: directx11, windows, multiple-graphics-devices
---


# Question
Title: Are there any open source projects for car engine sound simulation?
I have been thinking how to create realistic sound for a car. The main sound is the engine, then all kind of wind, road and suspension sounds.

Are there any open source projects for the engine sound simulation? Simply pitching up the sample does not sound too great. The ideal would be to something that allows me to pick type of the engine (i.e. inline-4 vs v-8), add extras like turbo/supercharger whine and finally set the load and rpm.

Edit: Something like http://www.sonory.org/examples.html

# Answer
> 22 votes
On one driving game I worked on, we had multiple samples per car - the engine held at certain rev intervals, and a sample each of the car ascending and descending the rev scale IIRC.

All of these were recorded from the exhaust, the sides, the front, and inside the real-life car so the sound could change as you moved the camera. Then we blended between them depending on what the engine was doing right now.

It sounded awesome, but obviously it took a lot of resources!

# Answer
> 9 votes
See "Capturing Engine Sounds for Games" for ideas about how the pros do it. The article references this SDK, which I worked on. Unfortunately, it is no longer supported. It was free, so there may be copies floating around somewhere.

# Answer
> 7 votes
Small university project of mine, calculates 4 given engine sound sample-sets to represent realistic engine sound.

Have fun!

# Answer
> 5 votes
Couple papers about this topic:

Design of a Driving Simulation Sound Engine http://www.nads-sc.uiowa.edu/dscna07/DSCNA07CD/papers/Section%207B%20-%20Simulator%20Characteristics%20-%20Sight%20and%20Sound/Heitbrink.pdf

Sound Synthesis for Virtual Reality and Computer Games (ch 6-4) http://circle.ubc.ca/bitstream/handle/2429/10055/ubc\_1999-389936.pdf?sequence=1

# Answer
> 3 votes
There is a very interesting thread on the subject here: http://tech.dir.groups.yahoo.com/group/gameaudiopro/message/15158

They discuss Sonory, Physical Modeling, Granular Synthesis, Pitch shifting, etc. Also, they briefly explain the tech in Need For Speed.

# Answer
> 1 votes
---

Live for speed I think records the cylinder ignition sound for one stroke and then programmatically adds more cylinders depending on car engine (ex. v12) and produces sound that way...

# Answer
> 0 votes
Here is it : http://www.youtube.com/watch?v=T7c89\_YSZZQ Audiomotors by Audiogaming

---
Tags: sound, simulations
---


# Question
Title: Is a HashTable the best way to store replay data in C#?
I'm looking to make a deterministic replay in my **2D game**. I want to follow a similar approach to braid in **storing the relevant information every frame** (at 60 frames per second).

I wanted to know what the best way to store this information is. My friend suggested using a **hashtable** and being new to C# I'm sort of leaning towards just using an **array**, but I wanted to see if there were other schools of thought.

I've read posts like this How to design a replay system and this "Super meatboy"-ish replay which were very informative, but not very specific to C# and XNA.

My game is 2D and does not have all that many moving parts. At any given time there is probably less than 50 bodies I would need to track the position/rotation of.

Curious to hear your thoughts.

# Answer
> 2 votes
Do you need to index things with anything other than an integer? If all you need to do is something like:

```
a[1] = ...

```

Then there's no reason to use hash table. In this case arrays will be more efficient than hash table in all cases assuming you don't delete stuff in the middle and shift.

Assuming what you want is store last X frames, make an array of size X.

Assume initially a\[0\] is most recent frame, a\[X-1\] is least recent frame.

Make a counter c that points the least recent frame. c = X -1 initially

For each new frame to add,

```
a[c] = curFrame //replace least recent frame with most recent
c-- //update counter
if(c < 0) //need to wrap c around if it goes negative
  c = X-1

```

To iterate from most recent to least recent:

```
for(int i = 1; i <= X ; i ++) //starts at c + 1, the most recent frame
    a[(c + i)%X] ... // % (modulo) wraps it around

```

If you need to do something like:

```
h["lol"] = ....

```

Then yea, you might need to use a hash table.

---
Tags: xna, c#, xna-4.0, memory-efficiency, replays
---


title: are most 2D games tille based?

text:
# Question
Title: are most 2D games tille based?
So I'm beginning the planing phase for a 2D game that I hope to deploy for iPhone, Android, and maybe windows phone, and I am writing it in Cocos2DX and I'm looking around for map editors that I could use... and I keep seeing that most if not all of them seem to be for tiled games.. which leads me to my question.. are most 2D games tile based? for example is angry birds, or tini wings, or the silent age? if not what are the other alternitives? and what would the drawbacks or advantages be to either technologies?

One thing that I probably should add... I used to write Flash games, and most of them where not tile based, and it seemed to be much more flexible that way.

any help with this would be greatly appreciated.

# Answer
> 4 votes
It depends what you mean by tile-based.

Most 2D games that involve a level that you view from the top-down are tile based. In this way different tiles usually have different properties, and pathfinding such as A\* is easy to implement.

A lot of level editors use a tile-based sprite-sheet to define all of the aspects of a level, but then use them in a tiled way to construct a platformer. (See Tile Studio)

Games that involve real physics, like Angry Birds, generally are not tile-based in that sense. Most of the characters are created as sprites and then their bounding boxes are used as physical objects to perform collision detection and response.

It is hard to discuss the merits of "tiles" without knowing exactly what the game you're trying to develop is. You should start developing the game and see whether or not a tile-based approach makes sense for *you*.

---
Tags: 2d, tilemap, cocos2d-x, map-editor
---


# Question
Title: How can I export Blender game logic for controlling actor actions?
How does one export game logic ("Sensors") that Unity references for controlling actions from Blender's "Action Editor" or "Dope Sheet?"

I have a Blender model that has game logic sensors that respond to complex input. These actions are defined in Blender's "Action Editor" or "Dope Sheet". What is the easiest way to export the game logic so that I have access to its input that causes the actions? There are many exporters that focus on the mesh/skeleton, is there a solution for exporting these sensors?

Here is a list with screen shots of Blender's sensors to give a better idea of what I want exported.

For each character made, I want their sensors exported to a file that is easy to read (some kind of XML). This way I don't need to hard-code character behavior or action triggers/sensors. Each modeled Blender actor can have its sensors programmed in Blender with its nice GUI and later exported to my game engine.

This question has been asked before and it seems the asker ended up scripting a very limited exporter (for one variable) but didn't fully explain his approach: Link

Again, this was asked with no apparent solution: Link

Looks like someone has already tried using Collada but this was only for exporting actions (not sensors that trigger them): Blender multiple animations and Collada export

Someone here wrote their own exporter. I don't think they are exporting sensors though: exporting bind and keyframe bone poses from blender to use in OpenGL

Any ideas?

# Answer
> 1 votes
As for the mesh/skeleton export. You can do using the simple Wavefront (.obj) exporter. This file is readable by most physic/3d engines. Or the Blender to FBX exporter :)

I am not exactly sure how does the action import work in the engines you noted. But many game engines have their own systems when it comes logic mechanics. UnityScript, HeroScript, UnrealScript and so on. You might have to export just the rigs, meshes, skelets and animations seperately. To set it up one by one inside the other engine using the internal game engine language.

# Answer
> 1 votes
I am using the InterQuake model exporter (.iqm/.iqe files) for my projects. You can find the exporter here. It's a lightweight format which doesn't get as bloated as Collada and supports Skeletal Animation, basic texturing, etc.

It does not, however, support exporting Dope Sheets. The reason I am recommending the format is because the provided exporter itself is also rather lightweight, so you can easily edit it to suit your needs.

# Answer
> 0 votes
If you don't need some more advanced engine features then alternative approach would be to use Blender's own game engine. Some games using it: Dead Cyborg, Yo Frankie!.

---
Tags: input, blender, logic, blender-game-engine
---


# Question
Title: How to check if a numerical value is equal to a whole number in c++?
So been working on this mathematical algorithm of checking if a numerical value is equal to a whole number **1,2,3,4,5** not a non-whole number **1.5,2.3,4.6**.

I researched around and found out that one way to do this would be to :

```
if(numerical_value == static_cast<int>(numerical value))
{
    //DO SOMETHING
}

```

Which I don't understand how that represents a whole number but still.

Another problem :

When using this code my video game starts running on really low FPS my question is why?.

If that code is being repeated every iteration of the loop and that is the main cause of the video game running on slow FPS then my more fascinating question would be what is a more efficient way to check if a numerical value is a whole number?.

By the way I am using integer values not floating point or double point precision.

Maybe the answer is right in my face and I don't see it?.

# Answer
> 1 votes
if you are using integers only then they are always whole numbers.

As for how the cast works. `static_cast<int>` interprets the value of the argument as an integer. Since integers represent only whole numbers a float or double value of 1.9535 will be interpreted as the integer 1 (note that there is no rounding, the part after the separator will just be ignored). If a variable is already a whole number the integer will represent the same number as the orignal value. Do note that floating point variables can not precisely represent each number (so that goes for doubles and floats) so this check might not always work since the floating point variable can not represent each whole number.

If you're only doing this once each loop it should not cause a lower frame rate. A static cast is very cheap.

---
Tags: c++
---


# Question
Title: Gravity/collision problems: models jumping
I'm pretty new to Unity3D game engine and game development, so don't judge me strictly. I import a model of the rail track, add rigid body component (with mass 1 and use gravity flag) and box collider component. Then I add train engine with rigid body (mass == 1, use gravity) and box collider and put it on the track. When I'm running simulation, train engine starts jumping like a ball (despite material for tracks and train is Metal (built-in Unity material)).

There is an important note that rail tracks are fixed (freeze position set in rigid body options). It seems to be natural. Anyway, if I turn off freeze position option then train engine does not jump, but tracks fly apart.

So I'm in trouble here. Can you please suggest what is the problem?

Thanks in advance.

# Answer
> 1 votes
First, if you've set freeze position on the rail tracks, why do you have them set to react to gravity?

Second, make sure that your train and tracks are not positioned so that they are initially colliding. The way you can do this is to keep moving the train up until it simply falls to the tracks.

Third, I'm not sure that metal is the material that you want here. I would suggest making your own physics material and experimenting with the properties. In general, your objects should have a very high coefficient of static friction, and a not so high coefficient of dynamic friction. Play around with the settings to see what feels right.

---
Tags: collision-detection, physics, unity, models
---


# Question
Title: Draw 60,000 cubic with DrawUserPrimitives on xna with only 20 fps-buffer problem?
I'm working on a minecraft style games on xna. I know it is not easy to draw a lot of cube with a good ratio of fps. I use the method "DrawUserPrimitive" with a buffer to draw a floor 250X250 cubes. But my game displays **20 fps for only 62,500** cubic drawn! I do not understand.

2,250,000 vertexPositionTexture is to lot ?

Here is my code explained on how I proceed-

**Initialize Buffer:**

```
//Initialize the vertex buffer 1 times before drawing

public void RenderToDevice()
{
    int nbrVertexPositionTexture = vertexPositionStructureCube.Length; //2'250'000 ! to lot ?
    //Declare and initialize a buffer
    vertexBufferCube = new VertexBuffer(
    Game.GraphicsDevice,
    VertexPositionTexture.VertexDeclaration,
    nbrVertexPositionTexture,//2'250'000
    BufferUsage.WriteOnly);

    vertexBufferCube.SetData<VertexPositionTexture>(
    vertexPositionStructureCube);
    //Set buffer to graphic card
    Game.GraphicsDevice.SetVertexBuffer(vertexBufferCube);
}

```

**Draw**

```
// Draw all cube (10,000)
    public void drawWorld(GameTime gameTime)
    {
            effet.LightingEnabled = false;
            effet.VertexColorEnabled = false;
            effet.TextureEnabled = true;
            effet.FogEnabled = true;
            effet.FogStart = arcadia.camera.NearPlane;
            effet.FogEnd = arcadia.camera.FarPlane;
            effet.FogColor = new Vector3(1, 1, 1);
            effet.View = arcadia.camera.View;
            effet.Projection = arcadia.camera.Projection;
            effet.Texture = textureInstancedModel;

            foreach (EffectPass pass in effet.CurrentTechnique.Passes)
            {
                pass.Apply();
                //Draw
                Game.GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, vertexPositionStructureCube, 0, vertexBufferCube.VertexCount / 4);

            }
            needToDraw = true;

    }

```

# Answer
> 6 votes
**Yes.**

`VertexPositionTexture` is a 20 byte structure. With over 2 million of them, they take up around **43MB** of memory. Which gets copied around a bit on the CPU, and then transferred to the GPU. *Each frame!*

There are almost certainly going to be other optimisations you can pursue. I see, in the comments, merging adjacent faces is suggested. I think Minecraft might do some occlusion culling. One that I recommend is not including always-invisible faces (between adjacent cubes) in your buffer.

But, for now, the simplest fix you can do is put your data in a `VertexBuffer` \- which you then transfer to the GPU once at startup. Or a `DynamicVertexBuffer`, if you want to occasionally modify it (or sub-sections of it).

Additionally, an `IndexBuffer` or `DynamicIndexBuffer` should also drastically improve both memory usage and vertex performance by allowing you to remove all the duplicate vertices you have.

---

Edit: I see that you're actually creating a `VertexBuffer`. But you're not using it correctly. `DrawUserPrimitives` will transfer an array of vertices to the GPU each frame. You want `DrawPrimitives` to draw the vertex buffer you set with `SetVertexBuffer` (which you should be setting right before drawing, *not* at startup). Or, better yet, use `DrawIndexedPrimitives` with that index buffer I suggested.

# Answer
> 2 votes
It's not a buffer problem - it's a "your code" problem.

First of all, user primitives are slow. They're not horribly slow, but they are slower than using pure vertex buffers. (For info: user primitives are emulated behind-the-scenes with a dynamic vertex buffer, so you're not only redundantly transmitting a large amount of data to the GPU each frame, but you're also incurring the cost of extra memory copies).

Secondly, and you don't confirm or deny this in your question, but if you're making 60,000 draw calls per-frame, then poor performance is to be expected. That's normal behaviour; a high number of draw calls each sending a small amount of data will perform *much* worse than a low number of draw calls each sending a large amount of data.

You code, and the thinking behind it, is also slightly messed-up. First of all you're setting a vertex buffer, then you're calling DrawUserPrimitives which won't actually use that buffer!

In order to get good performance from this kind of drawing you need to look at alternate strategies - just trying to brute-force it CPU-side is not good enough here. Instancing is a typical solution used, and will give you good performance (for reference, I can easily handle 1 *million* cubes at playable framerates on low-end mobile devices using instancing).

However, my knowledge is in D3D itself rather than XNA, so I can't give you any further help with this.

---
Tags: xna, graphics, voxels, vertex, index-buffer
---


# Question
Title: Drawing multiple sprites with clear screen for every frame
I googled with best of my skills, but I cannot find any relevant answer to my problem. I'm making a game with an isometric view. I need to draw multiple sprites on the screen and before switching to next frame of the sprite, it is needed to clear the last frame of the sprite by doing a `clearScreen` of the window. If I do `clearScreen`, all of the other sprites get cleared, since the program cannot remember the last state of the screen. How can I overcome this problem?

Here is my code (I'm writing in pseudo-code, so that the solution can become implementation independent)

```
main.cpp
{
  //gameloop

 Animation playerAnimation;

  while(window.isopen())
  {
    window.draw(game_map);

   if(certain_condition_is_met)
   playerAnimation.update(window)

    window.clear()
    window.display();
  }
}

   Animation.cpp

   class Animation
   {
     void update(&window)
      {
        for(available_frames frame)
         window.draw(frame);
       //inside the above for loop ,i need to do a clearscreen to avoid overlap of
       //frames,but this will make other sprites to be lost
       }
   }

```

I'm using C++ SFML, in which there is no way to update a particular sprite without `clearScreen`.

# Answer
In case you needed a code example

```
class Animation
{
    void update()
    {
        if (condition)
        {
            advanceFrame();
        }
        frame.draw();
    }
}

Animation animation;

int main()
{
    while (window.isOpen())
    {
        window.clear();
        animation.update();
        window.display();
    }
}

```

The condition is most likely a timer, to update the animation every few milliseconds. This way, the animation is drawn once per update.
> 0 votes

---
Tags: 2d, animation, sprites, game-loop, sfml
---


# Question
Title: Are there any good UI widget toolkits for Pygame?
Are there any good, modern widget toolkits for Pygame? I've looked at PGU, but it's apparently unmaintained.

# Answer
No. Every year someone makes a new Pygame UI library and then abandons it after a few versions, probably once they realize that writing button layouts is easy but writing a complete UI library is real work. The `gui` tag on the Pygame site chronicles some of these.
> 11 votes

# Answer
Back in January, 2011, I looked at five GUI toolkits for pygame, and tried to get all of them working with Python 3. The five were: Albow, GooeyPy, PGU, pqGUI, and sgc.

I didn't succeed with GooeyPy, but I did get the other four to work with Python 3. (I wanted to also try poutine, by Shandy Brown, but I couldn't find it, and I entirely overlooked Ocemp.)

Unfortunately, Albow and Ocemp seem pretty much dead. Albow was last updated in 2009, and Ocemp was last updated in 2008. (Note that the version of Albow at pygame.org is not the latest one.)

PGU (Phil's Pygame Utilities) has been taken over and maintained by Peter Rogers, and Victor Kam converted most of it to Python 3. It was last updated January 2012, and is presumably improved since I examined it. (Note that the version of PGU at pygame.org is not the latest one.)

sgc was new and still very incomplete when I looked at it. However, it is being actively developed, and might be much improved, by now. (Note that the version of sgc at pygame.org is not the latest one.)

I ran each of the five through a simple Lines-Of-Code counter to gauge their sizes:

These were the results (in January, 2011):

```
    Albow code        min=2810, max=4551    (max = 162% of min)
    Albow\demo        min= 453, max= 649

    GooeyPy\gooeypy   min=2034, max=3941    (max = 194% of min)
    GooeyPy\examples  min= 178, max= 351

    pgu\pgu           min=2910, max=7047    (max = 242% of min)
    incl. pgu\pgu\gui min=1678, max=4638    (max = 276% of min)
    pgu\examples      min= 822, max=2527

    pqGUI.py          min=1586, max=1834    (max = 116% of min)
    Example.py        min= 178, max= 225

    sgc (incomplete)  min= 889, max=1243    (max = 140% of min)

```

In each case, the "min" number is more representative of the "size" of the toolkit, since it doesn't count whitespace and comments. When the "max" number is very close to the min number, it means that there's not much whitespace and not many comments in the code. pqGUI exemplifies that, because it has almost no comments at all (and no docstrings, either), which is too bad, because (IMO) it made the nicest-looking GUI elements.

*Major caveat: docstrings are not counted as comments!* That makes PGU, sgc & GooeyPy, which have docstrings, look fatter and less well-documented than they really are, compared to Albow and pqGUI, which lack docstrings.

I liked pqGUI because I liked the look of the widgets it makes, but it is unsupported and undocumented, and I couldn't find the author.

Of the five, as of January 2011, PGU was the clear leader. But I was dissatisfied with all five, so I wrote my own. (Note: PGU & sgc have both been updated, and presumably improved, since I looked at them.)

Per Joe Wreschnig's wry observation (above), my GUI toolkit is incomplete, like all the others. But it does have a few things going for it.

* It works with Python 2.6, 2.7, 3.1, 3.2, & presumably 3.3.
* It is sprite-based, and uses pygame events for communication, so that it can easily be dropped into an existing pygame program, without taking over the event loop. Widgets are subclassed from pygame.sprite.Sprite.
* It supports forms, buttons, check-boxes, modal & non-modal message boxes & dialog boxes, vertical menus, text-entry boxes, and sliders (scroll bars).
* It smoothly handles overlapping controls/widgets, moving & resizing widgets, and forms within forms.

However, it lacks some important controls you're likely to want, like file-open/combo-box dialogs, and tables. The controls that do exist look nice, but features like title-bars & scroll bars are fixed numbers of pixels in width, rather than adjustable-width. The code is well-commented, and there's a demo app with usage examples, but there's no proper how-to-use documentation. Also, it's pre-beta, so everything is subject to change.

The line-of-code counter results for it are:

```
    DavesGUI (w/ demo code)        min=2267, max=3055  (max = 135% of min)
     (w/o demo code)               min=2018, max=2644  (max = 131% of min)
     (w/ docstrings commented-out) min=1442, max=2644  (max = 183% of min)

```

If, in spite of those limitations, someone wants to try it out, then contact me by email. Ask about "DavesGUI." My email address is here: http://www.burtonsys.com/email/
> 8 votes

# Answer
I have recently seen pygtk used with pygame and it works really well. Just ensure you use the expose event with the gtk drawing area widget and update pygame data on each pass through the gtk main loop. If you want a full fledged gui toolkit to work within pygame it wont happen, but if you want a full gui toolkit to use with pygame then your in luck, pygtk is it. You can even use gtk using the C programming language and still import pygame as a widget onto the drawing area and update pygame in python if that floats your boat and you want turbocharged speed. Why the fuss, just use google and find the answer then implement it, not hard and no biggy. By the way pygame is really cool. Those guys have put so much work into it, and it works so efficiently its amazing. Those pygame guys deserve kudos for the work and time put into making pygame into a super game development kit.
> 1 votes

# Answer
I've added very basic GUI elements to my GameEngine library: http://aharrisbooks.net/pythonGame/ch10/ (Included in a book on game development in Python)

I built very simple GUI elements based on the standard sprite: a label, button, multi-line label, and mini-scroll-bar.

These tools are quite basic, but they are adequate for many uses. Of course, the library is completely open-source, so feel free to modify them if you wish. The one user interface element I didn't add (yet) was a text input widget. That's because the event model is much more complex for this than the other models, and I was running into a deadline.

Feel free to play with that (whether you use the book or not) and let me know if you run into any troubles. I'll try to help.

I've got videos of my course available at http://synapse.cs.iupui.edu/Mediasite/Catalog/

Look at the N451 course. That's the one on game development.
> 0 votes

# Answer
Google summer of code added a new GUI: http://blog.sambull.org/pygame-gui-0-2
> 0 votes

---
Tags: software-engineering, gui, pygame
---


title: Unity game onto Windows 8 store

text:
# Question
Title: Unity game onto Windows 8 store
I've been searching around the web to see if it is possible to submit a unity game onto the windows 8 store. All I have found so far are articles months old saying it is coming soon, can anyone give me an update if this is yet possible and how would i go about doing this?

# Answer
> 1 votes
Just to keep this updated, the Unity Blog has details on the Windows Store early access program, Unity 4.2, and some Unity-based games already in the Windows Store:

http://blogs.unity3d.com/2013/03/07/unity-4-early-access-for-windows-store-apps

# Answer
> 1 votes
I think this is as updated as you are going to get

http://answers.unity3d.com/questions/350071/windows-phone-8-support.html

---
Tags: unity, windows, windows-8
---


# Question
Title: Best way to learn iphone game development?
I know php and some python, but not much c. Where should I start to learn iphone game development? Is there some recommended books/tutorials for beginners? I'm looking at using cocos2d but I'm open to anything that isn't too limited.

# Answer
> 3 votes
I also just recently started developing for iOS. I found the documentation over at cocos2d-iphone.org quite helpful, but sadly it isn't very in-depth. That's why I also bought the "Learn iPhone and iPad Cocos2D Game Development Book" (written by Steffen Itterheim who is also an active community member here on gamedev SE).

Objective-C was also new to me, but thankfully the documentation over at developer.apple.com is really good. Be sure to also read the introduction to Objective-C.

I've got some C++ experience, so the whole memory-management stuff wasn't totally new to me (well, actually everybody should know about that stuff, even if you don't have to manage things yourself). Since Objective-C doesn't come with a garbage-collector (at least not when you develop for iOS), you should also read the memory-management guide. XCode also comes with a handy tool called "Leaks" which allows you to profile memory-usage and detect leaks. This makes spotting memory-leaks much easier and you should definitely run your app through it (make sure to always run on the device, since the simulator apparently produces leaks where there aren't any).

Umm, I went a bit off-topic in the last paragraph I guess, but it's always good to know about this stuff beforehand :-)

**Update:** Since you're open to other options, you might also consider Unity3D, UDK or even Ogre3D (although it's not a game-engine but "just" a graphics-engine).

# Answer
> 0 votes
I've been very favorably impressed by O'Reilly's *iPhone Game Development*. For my taste it's a bit deep in the mindset where "game" means "screen-oriented pixels-moving-around exercise", but since that mindset is dominant in the industry that's not too surprising. It'll definitely get you a good start, in any event.

# Answer
> 0 votes
try this as a starter to learn or refresh your language skills:

http://www.stanford.edu/class/cs193p/cgi-bin/drupal/downloads-2010-winter

# Answer
> 0 votes
iPhone game development is incredibly fast using Cocos2d.

Since you already know some programming, I'd recommend you to first take a look at the basic concepts in Cocoa development here.

Now that you know how Objective-C thinks, you may want to pay a visit to Raywenderlich's blog. Many of his posts are about Cocos2d, like this one.

It is not necessary you understand the whole tutorial. You simply copy and paste the code he provides you and take your time to see what it does.

Cocos2d has all kinds of useful tools for making development fast. It has great iPhone retina display support, great bitmap font labels performance, process lots of sprites with ease, create tilemaps, schedule functions, stack scenes, create menu and buttons, box2d and chipmunk physic engine support, export to Mac feature, particle effects, great sound engine and a nice array of "actions" you can apply to your objects, like move, jump, rotate, fade etc.

Since Cocos2d is just a framework on Objective-C, you have full freedom to do lots of things game engines usually lack. You can quickly implement leaderboards and achievements for your games with OpenFeint, for example. You can use iAds too.

This is nice to read as well.

Cocos2d is well supported. The community forums are good, you shouldn't have problems asking what you need there. And there are starting to appear lots of ports, like Cocos2d implemented with javascript and html5 for web development, or with Ruby, etc.

So here's my opinion: Cocos2d has potential and is worth giving it a go.

# Answer
> 0 votes
I'm reading "Beginning iOS Game Development" by Patrick Alessi it's not a bad book, I actually knew how to program in Objective-C before I picked it up, because I'm old.

---
Tags: iphone, cocos2d-iphone
---


# Question
Title: What data structure to use to implement ocean currents and trade-winds
I'm creating an RPG/simulation game which is similar to the Uncharted Waters Series. The game allows the player to control a fleet to explore and navigate the world on the world map. My Game stores the world map as a tiled map into a 2158 * 1080 2D array.

The problem I'm facing is I want to simulate the ocean currents and trade winds on the world map so when the player is sailing on the map, the speed of the fleet will be affected by the current and the wind. It does not have to be a really accurate simulation because this is not a high-detailed simulation game but it should resonably simulate the ocean currents and the wind.

---

Requirements:

* Need to come up with a data structre to represent the ocean currents
* For each point (x,y) on the map, the data structure should provide a fast way to look up what is the strengh and direction of the current at that particular point
* The current can have 8 directions (N W S E NW NE SW SE).
* The strengh of the current is represented as an Int
* Same requirements for trade wind so I think the solution should be the same

---

My thoughts:

I'm thinking about dividing the world into several regions and each region can be subdivided into smaller regions like a quad tree. For look up I can do a contains(x,y) and find out which region the point is in and then for sub-regions to the same thing until it arrives a leave of the tree which stores the strengh and direction of the current.

Is that a reasonable solution or there are better ways to do this? What are the gotchas for implementing it?

Thank you for you answers!

# Answer
> 1 votes
What I would do is copy Minecraft's habit of adding metadata. Basically, metadata is a method of adding additional data to your tiles (or blocks, continuing the Minecraft explanation) which confers non-essential information (essential information being things like tile type and location). What this would mean is that in the XML file where I presume you are storing your tile data, you would also store the direction (1-8) of your wind and current, and its strength, or possibly aggregate both for a lower memory footprint. You would then load this information at runtime and store it in a 2D array akin to your tile map. As a C++ struct this translates to:

```
struct MovementMetadata
{
    int oceanCurrentStrength;
    int tradeWindStrength;
    char oceanCurrentDirection;
    char tradeWindDirection;
}

```

Notice that (at least if in C++), your struct or equivalent should have the strengths first, then the directions - this is due to memory alignment issues (data is most efficiently read at boundaries divisible by its size).

---
Tags: data-structure, simulations
---


# Question
Title: GameTimer too fast, Objects staying intersected and rand not returning value in between min and max
I'm developing a game called PongBreakout in C++ using a game engine I got from university.

I've got a few problems with my game that I'm struggling to fix and need some help to figure out how to do so.

The first bug is that the countdown is far to fast and I don't know how to slow it down - I've been told to use a scalar \<- ball.cpp (Update())

The code for this is below, I've debugged the value for `.mdframetime` and it keeps varying between 0.016 and 0.015 however it remains to countdown far to fast.

```
double frametime = g_theTimer.mdFrameTime; // Update frametime
if (reset == true) // If the ball needs reseting.
{
    countdown -= frametime; // Reduce countdown - This needs fixing its far to fast.
    if(countdown > 2)
    {
        pTheDrawEngine->WriteText(512,384,"3");
    }
    else if(countdown > 1)
    {
        pTheDrawEngine->WriteText(512,384,"2");
    }
    else if(countdown > 0)
    {
        pTheDrawEngine->WriteText(512,384,"1");
    }
    if(countdown <= 0)
    {
        countdown = 3;
        reset = false;
        position.set(512, 384);
    }
}

```

The second bug is that the ball sometimes gets stuck at the side of the screen if the paddle is there (play it and you'll eventually notice it.) \<- ball.ccp (ProcessCollisons())

```
void Ball::PanelCollision(Rectangle2D Panel1, Rectangle2D Panel2, Rectangle2D Panel3)
{
if (BallOutline.Intersects(Panel1))
{
    velocity.XValue *= -1;
    velocity.YValue = 5 * ((position.YValue -  Panel1.GetCentre().YValue) / 25);
}
else if (BallOutline.Intersects(Panel2))
{
    velocity.XValue *= -1;
    velocity.YValue = 5 * ((position.YValue -  Panel2.GetCentre().YValue) / 25);
}
else if (BallOutline.Intersects(Panel3))
{
    velocity.XValue *= -1;
    velocity.YValue = 5 * ((position.YValue -  Panel3.GetCentre().YValue) / 25);
}
}

```

I'm not to sure about what's wrong with this function, as it works until the panels are at position 0 or 768 it causes the ball to stick and in some cases go of the screen but still be drawn in the same place.

Do you think it's possibly best to make a counter that will increase, after x amount of times it's increased, the ball is obviously stuck so get the position of the panel and the position of the ball, take them away to get the value of how close the ball is stuck towards the center of the panel and minus it away to unstick it?

The third bug is that the `rand()` function doesn't seem to be working for getting a value between 8 and 5. \<- ball.cpp

```
srand (time(NULL)); // Seed the random
switch(rand() % 4 + 1) // Which way should the ball shoot off?
{
    case 1: velocity.set(rand()%4 + 5 ,-rand() % 5 + 1); // Rand is broken. Why? - Needs to be between 5 and 7. for X
    break;
    case 2: velocity.set(-rand()%4 + 5 ,rand() % 5 + 1);
    break;
    case 3: velocity.set(rand()%4 + 5 ,rand() % 5 + 1);
    break;
    case 4: velocity.set(-rand()%4 + 5 ,-rand() % 5 + 1);
    break;
}

```

The `rand()` function needs to return a value between 5 and 7 but it's returning values less than 5 in some cases and I can't figure out why. I've tried the max - min + min method and that didn't work either.

# Answer
> 2 votes
**First problem:** You'll have to either created fixed timesteps for your updates or reduce the countdown based on your delta time (i.e. the time passed). For example, if 1 second passed, you'll have to reduce the countdown by 1. if only 50 ms passed, you'll have to reduce the countdown by 0.05.

**Second problem:** You not only have to adjust the ball's velocity or making it bounce on collisions. You also have to ensure to move it out of collideables (because sometimes it's just stuck too deep to get out the next Iteration).

**Third problem:** Although I haven't tried to run the code, I'd say your Problem might be operator precedence. For example, the `-` in `-rand()` will negate the return value first. Try to use brackets to group the operations the way you want them to work (e.g. `-((rand() % 4) + 5)`). Also make sure to not set your seed every Iteration. The return value of `time()` won't necessarily change every Iteration, as such you might start with the same seed over and over again (depending on the actual timing). Call `srand()` only once on application startup (or when you really want to set a seed, e.g. when doing replays).

**General advice:** As mentioned in the comments. Feel free to split such questions and create one post per question. Noone will call you "spammer" here, if all your questions are real questions.

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


# Question
Title: Using buttons on Smartphone shooter games
Just a simple and probably stupid question.

I noticed that many iOS and Android shooter games tend to avoid using traditional buttons in favour to autofire.

The very first reason to do so is to have more space in the screen available for graphics. However this takes away some satisfaction to the user when "pressing the virtual button". I understand that the fact that smartphone buttons would be only "virtual" is a good design reason to remove them and add autofire, but I was wondering which sort of comments your users (if u are one of those developers) have given you about this choice.

In short:

* Does autofire add to the gameplay?
* Does a game without autofire (and hence buttons) result inadequate for a smartphone and/or become less fun to play?

# Answer
> 1 votes
I don't think this is something you can answerin general. In my opinion this really depends on the actual gameplay. I'd split games into two categories:

* **Games where you essentially shoot most of the time:** This are classic shoot-em-up games, like R-Type, Solar Striker, Gradius, Parodius, etc. In these games most people will want to permanently shoot anyway, with the occassional priming/charging up of shots. These games are perfect for including an autofire Option (maybe even forcing it).
* **Games where you don't want to shoot all the time:** This are usually platformers and other games where precision is more important than just shooting everything appearing on screen. Reasons for this could be anything, from limited ammunition to limited number of projectiles on screen, etc. Classic games for this group would be all the Metroidvania games (like Metroid, Castlevania, Contra,...). Contra might actually be a game where autofire would work. But others, especially Mega Man or Metroid won't work that way. These games use ammunition and with autofire you'd just waste like 99% of it.

So what should you do? Think about the generic gameplay in your game. Do you want the players to shoot all the time? Do you want them to think before shooting? Are you providing unlimited ammo or any incentives to not shoot all the time (like weapons overheating)? Once that's decided, pick what you think fits best. Or even better: Just add a toggleable option or let the Player play a simple/short introduction/tutorial stage and ask them whether they'd like autofire turned on or off.

---
Tags: android, game-design, ios, shooter
---


title: How does streaming of games work?

text:
# Question
Title: How does streaming of games work?
In the last few years, lots of companies (such as OnLive or Gaikai) have begun providing games "from the cloud" as an online stream, which doesn't require the full game to ever be downloaded.

How does streaming of a gameplay session *work*? I have only basic knowledge about internet protocols, so I'd appreciate a good description of the technical aspects.

# Answer
from my understanding, you send their servers your input, which is then processed by their machines. The whole action is processed, then the output is pushed to your screen, reducing the processing power by your computer a ton.

i cant really get more technical than that, but from my understanding its pretty simple.

Please correct me if i am wrong, i would love to know more also.
> 4 votes

# Answer
There are some services that implement streaming like described previously: User input is uploaded to the server, rendered frames and sound-data is downloaded to the browser. This reduces processing load on your local machine, but you need a *really* good internet connection for this to be fun.

The way the company I work for handles it works like this: You download a little bit of data, say the assets and code for the start menu. Input-handling, processing and rendering and takes place in your browser via HTML5 canvas (or a native plugin for older browsers) and while you are busy setting up your profile, clicking start etc the assets for the first room in the first level are being downloaded and so on. The next time you play, the data is already in your browser-cache. It's up to the game-designer to only download as much data as you need (eg: only when the player approaches a corner do you download the mesh-data for whatever is behind it, only when the player picks up the plasma-gun do you download the sound-files for plasma shots).

I know, strictly speaking this isn't 'streaming' but it's the same result: You don't download *everything* at once.

In regards to the technical aspect, there's nothing magical going on. Game-assets are being stored in shared collections on Amazon, accessed via their SHA1-hash and we use AJAX requests to get them.

The only data that is constantly being send back and forth is for multiplayer games. (We're using websockets)
> 2 votes

---
Tags: online, streaming, cloud-computing
---


title: games logic based on closed shapes

text:
# Question
Title: games logic based on closed shapes
I would like to know the math concepts behind shape based games like http://www.miniclip.com/games/fat-slice/en/

To be specific, I would like to know on

* how to model shapes programmatically
* finding areas of shapes
* intersection of areas
* curvy shapes instead of polygons

I searched for tutorials / guides to the best of my knowledge, but couldn't find anything appropriate.

Edit: I am looking at C++ libraries, that would support iOS / Android.

# Answer
You might be interested in shapes.

It is an c# with XNA library to work with shapes of every kind. I dont know what language / platform you are targeting but with the source code provided by codeplex you should get an idea of how to handle shape creation, collision and picking.

Slicing is a problem for itself, you need either to composit your shapes of smaller shapes and split them after slice, which would be the easier approach, but also limit the player. Or you regenerate your new shapes with your algorithm after the users sliced the old one.

Depending on your desired shapes you may want to have a look at metaballs, which handle composition of bodies (and therefore shapes in 2D) from particles.
> 1 votes

# Answer
> * how to model shapes programmatically
> * finding areas of shapes
> * intersection of areas
> * curvy shapes instead of polygons

1) If you mean how to modify the shapes programmatically just add 2 new vertices at the intersection points. 2) Find areas using the good old Divide and Conquer. It all looks to me like a set of linked rectangles and triangles. It's easy to compute the area using basic shapes 3) What do you mean by that? I can see any areas intersecting. 4) If you wan to get curvy I'd suggest approximating curves with triangles. Other approaches will require more power and coding.
> 1 votes

---
Tags: c++, mathematics
---