# Question
Title: I would really like to write a script for a game, but do I have a chance?
I'm 18 and am very good a reading writing and storytelling. I would like to write out the concept script and scenes for a vdeogame. I have a High School diploma but at the moment no other formal schooling. I would like my dream to become a reality, a game I wrote that gets created by a big name developer and published for everyone to enjoy. Before I start writing though I want to know is this achievable from the position I stand in now?

# Answer
This question will eventually get closed but I can leave a few notes behind before then.

Bear with me, I am in love with writing using colons and lists today.

Everyone in games has both: A) a million ideas and B) sure knowledge that they would be a great writer. Be prepared for blatant skepticism and much eye-rolling when you present yourself as a writer with great story telling skills.

No, you do not necessarily need a college degree but the experience is not something to be scoffed at. Even a community college can introduce you to ideas and modes of expression you might not have known to look for otherwise.

You have three avenues of approach: the first being to create a body of literary work to highlight your talents, preferably published and with many examples clearly designed to drive a game; the second avenue is to enter as a designer or producer and let your work become your example of your writing skills; finally, start your own company and you can do whatever you want. Any path will be a ton of work but to have an entire team trust you with 1-3 years of their blood, sweat and tears you need to earn your stripes.

Be prepared for a lot of work, re-work and rejection, just like in the real world of trying to get published =) If writing is what you love, and the game designers I know who write all absolutely love what they do, don't give up and never stop learning new things and stretching your skills.

In summation, yes you can reach your goal from where you stand now. Your path there will take time, effort, *proofreading* and unless you already have a best selling series of books published it won't happen right away. But it can happen if you do the work and build your talents.
> 7 votes

# Answer
I'm not a recruiter so I can't speak officially, but here's my take on it, coming from a programmer with at least 1 years experience.

With just a high school diploma, it's going to be very hard for you to break into the industry. You need to try to get a college degree and/or get some experience by lending your support to indie games. Your best bet if you want to get in at this point without the college degree, is to see if you can get an internship at a small studio, if you're good enough already. Now, even if you aren't good enough as it is, it doesn't mean you're not going to achieve your dream, you just have more work ahead of you to get where you want, which is normal.

Now, since writing isn't as important as it should be at some studios, you might not be able to get hired at first as a writer, you might have to break your way in as a tester in QA or something. Don't be shy, express your passion and it should be much easier to find a job, and this helps when trying to get into college too. Since you have a specific focus on what you want to do, you might find it easier to get into college than if you just wanted to be a writer, not sure what field you wanted to go into.

So, keep your head up, don't forget what you love to do and let others see it. Good luck to you sir!
> 1 votes

# Answer
I will not downplay the knowledge you would earn in college earning a degree even as a general developer/storyteller/etc.., but it depends on more then just these specific things many even small studios might not be to kind to a person who only wants to write stories for games they typically want someone who can follow the development process from story to gold, but this is more the job of the producer (many companies don't hand this out), but I would suggest maybe picking up some programming experience (game make can be a good jumping off point), or maybe some level design work (UDK can be a good tool for someone just learning)

that being said I would say still right up a brief/treatment/script (sometimes when lumped together are called just the GameDoc, or script) for your game idea, and then send it in to companies (remembering to express confidentiality, and ownership of the idea). another possible rout is sites like http://forums.epicgames.com/forum.php have a place where you can post game ideas, and if you follow through with it then you might be able to get a team together, and get it made, and even sent to retail (at least steam). but the first question that anyone is going to ask is "have you written the documents that define your game" (brief/treatment/script)

you should be able to find the information that belongs in these documents, but if asked I could provide an outline (keep in mind it would be like an outline to a book which is unique to each book)
> 0 votes

# Answer
I would direct you to an answer I gave to a similar question: How do I turn a game idea, into a game?

To summarise, there are 3 routes:

1. have a concrete game-making skill (programming, 3d or 2d art, level design, scripting) and join a team;
2. spend money to pay people to make it for you;
3. join an existing company, again with a game-making skill, and work up to a decision making position.

The game industry doesn't run a 'slush pile' in general so the hope of submitting a script or a design to a company to have it made is almost certainly futile.
> 0 votes

# Answer
I remember being in your shoes, and figured I'd encourage you, as the industry is branching out in so many different directions. I have a personal philosophy that any goal is attainable, with proper planning, discipline, and research. If you set your mind to it ANYTHING is possible, which is why videogames in general are unbelievable. Now to answer your question (though as the first answer states we shouldn't get into it on this forum so I'll be brief).. Your current position tells me cracking into the big leagues without degrees and and portfolio is not something that will happen now. My advice is to break into the mobile scene (iOS, Android), by researching and contacting some smaller startups (like myself!) Your a lot more likely to get a chance and if your work is good, you have your first project in your portfolio. Mobile gaming is getting big and indie developers are on the rise, get out your surfboard and surf the dream man.
> 0 votes

---
Tags: game-industry
---


title: XNA: weird collision behaviour

text:
# Question
Title: XNA: weird collision behaviour
I'm reading the book "Learining XNA 4.0", and I'm in the object oriented disgn part. I'm having a weird problem with the collision of 2 rectangles.

I have a list of automateSprite and a Player class both derived from the class Sprite. in the update method im checking if player and the aotomatedSprite rectangles are touching each other, now when I go over the list I have a string called touching that represent the collision.

My problem is the variable `touching` only changes if the player Sprite touches the last automateSprite in the list.

The code that the book offers for testing is to do `Game.Exit()` if any collision was found. that work on every automatedSprite in the list, but when I change it to my simple test, it acts like I only check the last item from a list of 4 automatedSprite.

Here is the code:

```
string touching = "";
public override void Update(GameTime gameTime)
{
    // TODO: Add your update code here
    player.Update(gameTime, Game.Window.ClientBounds);

    foreach (Sprite sprite in spriteList)
    {
        sprite.Update(gameTime, Game.Window.ClientBounds);
        if (sprite.collisionRect.Intersects(player.collisionRect))
            touching = "touching";
        else
            touching = "not touching";
    }

    base.Update(gameTime);
}

public override void Draw(GameTime gameTime)
{
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

    spriteBatch.DrawString(font, touching, Vector2.Zero, Color.Red);

    player.Draw(gameTime, spriteBatch);
    foreach (Sprite sprite in spriteList)
    {
        sprite.Draw(gameTime, spriteBatch);

    }

    spriteBatch.End();
    base.Draw(gameTime);
}

```

(sorry for my English)

# Answer
> 2 votes
Even if a collision is detected, you continue to iterate through your list of sprite. This way, your variable touching will be set to "touching" only if your player collides with your last sprite.

Put a break to exit your loop when a collision occurs, like this

```
foreach (Sprite sprite in spriteList)
{
    sprite.Update(gameTime, Game.Window.ClientBounds);
    if (sprite.collisionRect.Intersects(player.collisionRect))
    {
        touching = "touching";
        break;
    }
    else
        touching = "not touching";
}

```

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


# Question
Title: How to display a tile map from a 2D array in JavaScript?
I have stored my map, but the problem I am having is displaying it. My map is 100x100 tiles which are 40x40px.

I have my loop running through the array but I'm having difficulty selecting the portion of the map image to relate to the tiles. This is the code which selects the portion of the image on each iteration:

```
var sx = Math.floor(tileId % 8 * tileWidth); //source x
var sy = Math.floor(tileId / 8 * tileHeight); //source y

```

I'm using Canvas and keep getting this error message:

```
INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.

```

I'm guessing the remainder or division by 8 is wrong, this is something I picked up from the net, but what exactly does that integer need to be?

Thanks

# Answer
> 1 votes
If you're using `sx` and `sy` to index into your array then they indeed will be out of bounds rather quickly. Since the `tileWidth` and `tileHeight` have nothing to do with how the tiles are indexed.

You can index into your array with the following:

```
var sx = Math.floor(tileId % 8); //source x -- don't actually need floor here
var sy = Math.floor(tileId / 8); //source y -- this is really just cast to int

```

I'm assuming that your tileID is a number from 0 to 9,999 (one for each tile in a 100x100 grid).

**EDIT**

I fixed the image above to correct the TileStartX column.

If you want 16x12 tiles you won't be able to do it with an index ranging from 1 to 100. You need 1 to 192 (i.e. `16*12=192`). Additionally, for the xIndex you need to mod the tileID by 16, not 8. Likewise you need to divide the tileID by 16 to get the yIndex. So indexing tile 60 in a 16 by 12 grid would be:

```
60%16 = 12
60/16 = 3

```

So in your array you'd get tile `tiles[12][3]` Or the tile in column 12 of row 3. Then if you wanted to draw that tile you'd draw it at `X=12*40=480 Y=3*40=120` So you'd draw tile `tiles[12][3]` at `x=480,y=120`.

---
Tags: javascript, html-canvas
---


title: Public format for 2D animations

text:
# Question
Title: Public format for 2D animations
What public animation file formats are there available for 2D games? I'd like to know about both formats for procedural/skeletal animation, as well as traditional animation.

# Answer
I'm looking forward for the Spriter project, a 2d skeletal animation editor. I uses an XML format called SCML, here is the beta format.
> 5 votes

# Answer
I have never seen an animation file format (animation meta data, etc) that was public. I made my own from scratch. It's based on XML and I load it using tinyXML. It pretty much says where bones move to from where, at which time, over what time. Honestly not much more than that, and yet it's plenty powerful. This is for as far as skeletal goes. But for something that's not, I would go with a sprite sheet and have a meta data file about the bounds for each frame, and how many frames in total, etc.

EDIT: PS, the actual animations of my game are mostly procedural, so that data is almost all an animation file is, and then it's animated in game.

Honestly this is a question that could have lots of broad answers. But here's mine.
> 2 votes

# Answer
There is PNG variant called MNG that supports frame-based animation. As for skeleton animations, I'm afraid you have to develop your own file format and encoder. The wise approach would be to prepare data in your games engine format, so loading skeletons would require no pre-processing.
> 2 votes

# Answer
.gif files seem to be what you are looking for. Figure out a way to decompile those and you're golden.
> -1 votes

---
Tags: 2d, animation, file-format
---


title: 3D Collision help

text:
# Question
Title: 3D Collision help
I'm having difficulties with my project. I'm quite new in XNA. Anyway, I'm trying to make 3D game and I'm already stuck on one basic thing. I have terrain made from a heightmap, and an avatar model. I want to set up some collisions for game so the player won't go through the ground. But I just don't know how to detect collisions for so complex an object. I could just make a simple box collision for my avatar, but what about the ground?

I already implemented the JigLibX physics engine in my project and I know that I can make a collision map with heightmap, but I can't find any tutorials or help with this. So how can I set proper collision for complex objects? How can I detect heightmap collisions in JigLibX? Just some links to tutorials would be enough.

Thanks in advance!

# Answer
> 1 votes
I suggest you take a look at the official JigLibX wiki, located over here.

Specifically, you may want to take a look at the quickstart guide from the wiki, located here.

There are plenty of articles on the wiki that should help you out. Otherwise, you might want to check out their forums for related posts.

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


title: Infinite 2D Terrain

text:
# Question
Title: Infinite 2D Terrain
I was wondering how to create infinite 2D platform terrain. I've read about perlin noise and I have an idea I'd like to illustrate below.

However, I have no idea how to achieve this. Are there any common practices in the game industry or any techniques you can share?

On a side note, I was wondering if it is possible to "influence" the perlin noise function in some way. For instance, say i'd like to make sure at some point that a large tunnel that goes down for **_ many meters. Or, I'd like to make a mountain right here _**.

Since I am very ignorant to this topic, I can only speak in theory, but I really appreciate any advice or direction. I am working in C# w/ XNA.

# Answer
> 6 votes
Your basic idea and illustrations of it are good. You may wish to look at "Simplex Noise," it avoids some of the artifacts of Perlin's noise and runs a wee bit faster.

**Noise is just one step** to generating terrain. You can certainly modify the output for tunnels or mountains as a step after the noise; and that's how noise is most used, as one stage of a chain of composited output. You don't influence the noise generator, you just keep adding more stuff afterwards.

In your case, you'd **make the baseline** silhouette with noise like your picture shows. Then a **tunnel marker is added** where you want, that guides digging down into the ground. This would be a tube **broken up with some fractal noise** to make the edges look natural.

An example from planet building which I just recently did: Noise generates big blobs that become continent and ocean. Only on the continent area a different kind of noise (Ridge Fractal) is added to make mountains. Only in the ocean is yet another kind of noise (Billow) is subtracted to make deep sea fissures. Only in shallow ocean the bottom is flattened out to make continental shelves. And so on, more and more layers of different noise and fractals composited like an automated photoshop job.

http://pcg.wikidot.com/ is a good place to read more.

---
Tags: xna, c#, 2d, terrain
---


title: Recommended book for cocos2d?

text:
# Question
Title: Recommended book for cocos2d?
I'm an experienced programmer that recently got into iOS development by working through the big nerd ranch book by Aaron Hillegass and Joe Conway. I loved the way the book was structured in terms of typing in the code and doing the challenges.

I'm interested in learning more about iOS gaming and cocos2d, but am a complete newbie in terms of game development/design. There are a number of books on amazon on cocos2d, can anyone recommend one in particular?

# Answer
> 1 votes
I recommend this book :

http://apress.com/book/view/1430233036

check it out

# Answer
> 1 votes
I would recommend wandering down to your local Large Chain Bookstore (Borders, Barnes & Noble, et cetera) and see if they have a copy of any of the books you are interested in. That way you can peruse them for yourself and hopefully get a better idea of whether or not a particular book would be good for you and your particular learning style. Amazon's "Look Inside" feature, if available for the books in question, may also allow you to do this to some extent.

Personally, I'd be very cautious about buying a book that focuses on a specific API, largely because such books tend to go out of date relatively quickly and thus I don't see them to be as strong of an investment. I would thus suggest that you take a good look at all the freely-available online reference and educational material for cocos2d and game development in general (if you have not already, of course) and see if that is suitable enough for you.

All of that having been said, I'm generally a fan of the O'Rielly books, however both of their iPhone books seem relatively old at this point. The Apress books have looked promising when I browsed them in stores, so that would be my secondary suggestion (the caveat being that I have not reviewed any of those books in detail and am basing this recommendation on my experience with the quality of the publisher's other material and quick flip-throughs of the books).

# Answer
> 0 votes
There are only 2 books available on cocos2d, i think

https://www.packtpub.com/cocos2d-games-for-iphone-0-99-beginners-guide/book http://apress.com/book/view/1430233036

from which i recommend the second one "Learn iPhone and iPad Cocos2D Game Development". its very well written and a nice introduction to the topic. Autor has described very useful insights using his experience with tools and tips to make a iphone games.

# Answer
> 0 votes
I haven't seen many books on Cocos2d, so I'm curious about the statement that there are "quite a few". Please share your list.

The book "Learn iPhone and iPad cocos2d Game Development" is available on Safari Books Online, if you happen to be a member, but I don't recommend it. As previously said, the book is easy to read and includes the author's best practices. On the downside, the writing style is perhaps too casual, the book is already dated with respect to the current version of cocos2d and it's I found it difficult to apply supplied code directly into my projects. I've been more successful using the tutorials on the Cocos2d website than with the book. The book also glosses over some topics, such as sound.

But since there are so few books on Cocos2d and there are at least two recommendations for this book, I suggest you try out the book in combination with tutorials on the product websites (Cocos2d, SneakyInput, etc), googling for specific information and of course asking questions here on Game Development - Stack Exchange. The book will give you a good idea on how things are supposed to work and you can use the web as a supplement.

# Answer
> 0 votes
I would **highly** recommend you read Ray Wenderlich's excellent book on Cocos2d, "Learning Cocos2D". I've just finished reading it cover to cover, completely worth the price. In particular, Rod and Ray introduce you to game concepts in a very gentle way through incremental level design. They cover menus, level changes, sprites, sprite sheets, behaviors, AI, physics, etc. In particular, the introduction to Box2D makes the book worthwhile, IMHO.

You can get a flavor of the book by reading some of the excellent tutorials and articles on Ray's site: http://www.raywenderlich.com/.

I'm a more experienced iOS developer, so reading the code samples was constructive (I didn't compile any of the example code, nor the final game "Space Viking"). I did enjoy that all the game code and assets are available for download, so you can build it yourself along the way.

# Answer
> 0 votes
Direct links to useful presentations (especially for Tetrad moderator):

intro to cocos2d

about performance

And my translation of the first presentation in Russian:

intro to cocos2d на русском

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


title: 3d js map rendering

text:
# Question
Title: 3d js map rendering
In the past I've done a 2D tile map using HTML, CSS and Javascript. Now I have the task of creating a 3D version using the same technologies - think of it like a space map where all planets have x/y/z positions.

Currently, I have no idea to do this. Is there an existing library or something I can modify to do my job? If not, what method of rendering the map should I use?

It needs to be as browser independent as possible, so I can't use webgl, flash or canvas. I'm considering plain JS & HTML or SVG (using Raphael for compatibility).

# Answer
> 1 votes
If you've got planets in space, in a realistic way, this probably means that:

* Planets are extremely large
* There is a lot of space in between them

This means that orthographic projections (like you might use for a 2d tile game) are very unhelpful. So you will have to use some kind of perspective view.

Which is fine, you just need to determine what transformations are necessary to have the camera facing the right direction and showing objects the appropriate size for their distance. Obviously, a realistic view of e.g. planet Mars from earth would typically be very small (e.g. a small dot), as it appears in the sky. But depending on the simulation, you might be standing on, say, Ganymeade looking at Jupiter, where it would take up half the sky (or something). There are plenty of applications which already do this kind of simulation.

I would really recommend the use of canvas. I suspect that SVG is usefully supported by fewer browsers than canvas (particularly on mobile platforms, where you can't use any kind of plugin to fix it).

It is possible to do many things using HTML and css e.g. image scaling, and perhaps rotation (depending on CSS version).

I really prefer canvas to CSS, because there are a lot fewer differences between browsers, and the feature set and behaviour is much better defined. Plus, you can't draw shapes very easily (or maybe, at all) using CSS. Drawing shapes using CSS is a big horrible hack if it's even possible.

---
Tags: javascript, html5, tilemap, svg
---


# Question
Title: XNA Entity Component Design: Lost on how to include Sprite Animation
I've been reading about Entity Component design and thought it's pretty neat. I've been trying to write a quick 2D engine in XNA.

I think I've laid the proper groundwork for registering and updating entities, since I've created some "PositionComponents" that seem to work with my Camera Entity (an Entity that simply owns ZoomableComponent, PositionComponent, MouseInputComponent).

All the tutorials seem to however seem to *end* at this stage of design. I'm pretty lose now on how I would like to design my animation/sprite components.

* I know I want some sort of 'RenderableComponent' which you assign it a Texture
* I need some sort of FSM (Finite State Machine) to hold Entity States
* I need some sort of Animation Manager.

Does anyone have any tips?

# Answer
Ok, this is just a quick End of Week brain dump

```
// IRenderable is the interface for your renderable components
public class CmpAnimation : IRenderable
{
  // Updates the animation, Inherited from IRenderable
  public bool Update(float ElapsedTime);
  // Dumps your data into a render stream or whatever you do to render, Inherited from IRenderable
  public bool Render();

  // Called from Update when our current frames is
  public bool OnAnimationComplete();> our End Frame value

  // Some way to load the animation data, either the sprite sheet or a keyframe data file
  public bool LoadAnimation(string AnimationName);

  // The animation to go to once we are done with this one
  public CmpAnimation NextLinkedAnimation { get; set; }

  // Loaded values that you may want to change or access at run time
  // The rate at which the animation plays
  public float Rate { get; set; }
  // The frame the animation starts on
  public int BeginFrame { get; set; }
  // The fame the animation ends on
  public int EndFrame { get; set; }
  // Does this animation loop until stopped by some external thing?
  public bool CanLoop { get; set; }

  // Informational values for internal or external use
  public bool IsAtEnd { get; }
  public bool IsAtStart { get; }
  public bool IsPlaying { get; }
}

```

Basically Update() updates its internal state so advance the animation to where it should be for its time stamp, if it reaches the end it should then go to the next animation (mark it as active, deactivate this one.. however you want to do that part based on your component systems flow).

This lets you put your FSM in to data, the animations know where they exist within the data they have loaded (Good for having a single 'Jump' animation but where you want the jump to have 'Jump', 'Jumping', 'Falling' and 'Landing' at different key frame indexes within that data).

Again, end of the week brain dump to help get you going in the direction you want to go in :)

I hope this helps.
> 1 votes

# Answer
Let me stop you there before going any further with your implementation and suggest you look at the awesome Artemis library. I recently discovered this and I think I have found the light! :P

There is a port for C# which I use for my XNA game, and there are examples there to clear many things.

Definitely have a look at it!

Basically, in Artemis, Components are plain data and you use Systems to manipulate the data (which make it also easy to have your game data-driven).

So, for example, a TextureComponent would have an array of Texture2Ds, and then you would have a TextureSystem that will render them to screen.
> 6 votes

# Answer
Artemis uses Components to store data and EntitySystems to manipulate them but C# already comes interfaces so like James said use a IRenderable interface for entities that you want to have rendered, IPositionable interface for entities that need to be moved, IColorable interface for coloring entities, etc etc. How about a IConfigurable interface that lets you set a Dictionary of properties/variables for a entity?

The only downside to this method, that I found, is that if you wanted to extend functionality on to an Entity you would have to create a new class inheriting IRenderable or IPositionable. Hopefully in C# 5 they will make available anonymous classes. Wouldn't recommend using NET 4.0 Dynamic because it is costly.

The upside is that you could store Entity references by their interface like list of IRenderables and then write a system that processes all IRenderables in your EntityManager. In a MovementSystem process all IPositionable based on their distance from the player. I think this method would outperform Artemis.

It is also a lot easier to write a de/serializer using this method then it is for Artemis.
> 1 votes

---
Tags: xna, architecture, xna-4.0, component-based, entity-system
---


title: How to set sprite source coordinates?

text:
# Question
Title: How to set sprite source coordinates?
I am creating own sprite drawer with DX11 on C++. Works fine but I dont know how to apply source rectangle to texture coordinates of rendering surface(for animation sprite sheets)

```
            //source = (0,0,32,64); //RECT

            D3DXVECTOR2 t0 = D3DXVECTOR2( 1.0f, 0.0f);
    D3DXVECTOR2 t1 = D3DXVECTOR2( 1.0f, 1.0f);
    D3DXVECTOR2 t2 = D3DXVECTOR2( 0.0f, 1.0f);
    D3DXVECTOR2 t3 = D3DXVECTOR2( 0.0f, 1.0f);
    D3DXVECTOR2 t4 = D3DXVECTOR2( 0.0f, 0.0f);
    D3DXVECTOR2 t5 = D3DXVECTOR2( 1.0f, 0.0f);

    VertexPositionColorTexture vertices[] =
    {
        { D3DXVECTOR3( dest.left+dest.right,  dest.top,              z),D3DXVECTOR4(1,1,1,1), t0},
        { D3DXVECTOR3( dest.left+dest.right,  dest.top+dest.bottom,  z),D3DXVECTOR4(1,1,1,1), t1},
        { D3DXVECTOR3( dest.left,             dest.top+dest.bottom,  z),D3DXVECTOR4(1,1,1,1), t2},
        { D3DXVECTOR3( dest.left,             dest.top+dest.bottom,  z),D3DXVECTOR4(1,1,1,1), t3},
        { D3DXVECTOR3( dest.left ,            dest.top,              z),D3DXVECTOR4(1,1,1,1), t4},
        { D3DXVECTOR3( dest.left+dest.right,  dest.top,              z),D3DXVECTOR4(1,1,1,1), t5},
    };

```

# Answer
Since you say you want this for animation, I assume you want to modify the cropping at runtime to display different parts of your texture.

One way would be to keep your geometry the same, and adjust the texture coordinates in the shader.

Say you want to to crop your texture to 1/4 the area, on the top left, that would be as simple as multiplying your texture coordinate by 0.5.

for the quarter on the top right, multiply by 0.5, add (0.5, 0). bottom left: multiply by 0.5, add (0, 0.5) bottom right: multiply by 0.5, add (0.5, 0.5)

the vertex shader could look like this for example:

```
cbuffer inputs {
    float4x4 worldviewprojection;
    int tiles_x; // number of frames in x (and y) direction
    int tile; // which frame is to be displayed
};

struct vs_in {
    float3 pos : POSITION;
    float3 col : COLOR;
    float2 uv : TEXCOORD;
};

struct ps_in {
    float3 pos: SV_POSITION;
    float3 col : COLOR;
    float2 uv : TEXCOORD;
};

ps_in vertexshader(vs_in input) {

    ps_in output;

    output.pos = mul(worldviewprojection, input.pos);
    output.col = input.col;

    float offset = 1.0 / tiles_x;
    output.uv = input.uv * offset  // "zoom"
    output.uv += float2(offset * (tile % tiles_x), offset * floor(tile / tiles_x) ); // offset

    return output;

}

```

this is just a simple example, which assumes your texture is of the same x and y dimension and contains 2^n animation frames.
> 1 votes

---
Tags: directx11, spritesheet
---


# Question
Title: Minimap Around Perimeter of Screen, Code Provided
What I'm essentially trying to do is what a lot of FPS's nowadays do in regards to their HUD. When an objective is off-screen, a small icon / symbol is shown on the perimeter of the screen, basically pointing towards the objective.

I'm working in 2D and I'm trying to get offscreen enemies (top-down) to show their positions via small points around the perimeter of the screen (a rectangle view, pretty standard).

Simply put, I'm trying to find the value of the red point when everything else is known:

Here's my code, and while it seems to be half functioning, sometimes it'll do funny things.

```
// Scan through enemiesRef list, and update dots to draw.
// ------------------------------------------------------
Enemy enemyRef;
float a, b, x, y;
float screenRatio = frustumWidth / frustumHeight;
float minX = topLeft.x;
float maxX = topLeft.x + frustumWidth;
float minY = topLeft.y;
float maxY = topLeft.y + frustumHeight;

// Loop through each enemy.
// ------------------------
for (int i = enemiesRef.size() - 1; i >= 0; --i)
{
    enemyRef = enemiesRef.get(i);

    // Get x and y distance to the enemy.
    // ----------------------------------
    x = enemyRef.position.x - center.x;
    y = enemyRef.position.y - center.y;

    // Check if the enemy is on-screen and skip.
    // -----------------------------------------
    if (Math.abs(x) < halfFrustumWidth && Math.abs(y) < halfFrustumHeight)
        continue;

    // Determine the known variable and derive the unknown.
    // ----------------------------------------------------
    float ratio = Math.abs(x) / Math.abs(y);
    if (ratio >= screenRatio)
    {
        // The a is known, the dot is on either the left or right.
        // -------------------------------------------------------
        if (enemyRef.position.x < center.x)
            a = minX;
        else
            a = maxX;

        // Calculate b.
        // ------------
        b = a * (enemyRef.position.y / enemyRef.position.x);
    }
    else
    {
        // The b is known, the dot is either on the top or bottom.
        // -------------------------------------------------------
        if (enemyRef.position.y < center.y)
            b = minY;
        else
            b = maxY;

        // Calculate a.
        // ------------
        a = b / (enemyRef.position.y / enemyRef.position.x);
    }
}

```

It seems the code accurately detects whether the point should be on the top / left / bottom / right, but if the object is far enough off screen (as in, it's both past the upper boundary of the view and the left boundary view at the same time, for example), the dot on the map just flies off the screen (for example, to the left, it's x coordinates going into negatives).

**I believe the error lies somewhere in calculating a or b:**

```
a = b / (enemyRef.position.y / enemyRef.position.x);
b = a * (enemyRef.position.y / enemyRef.position.x);

```

Whether it be with the signs of the values, or if the values I'm calculating are just wrong, etc, I don't know.

# Answer
> 1 votes
Nevermind, I got it working by using the equation of a line rather than this pseudo-trig stuff. Thanks anyway.

---
Tags: java, mathematics, geometry, trigonometry
---


title: Can adversarial agents flip coins?

text:
# Question
Title: Can adversarial agents flip coins?
I was thinking about peer-to-peer games by considering a simple coin tossing game.

> You open up your version of P2PCoinFlipping Beta 2.3 and it displays a list of player name servers. After choosing the closest server a scoreboard of the luckiest players appears. You choose the highest ranking player and the game begins. Since you started the battle the opposing player chooses the coin side, heads, and you are assigned tails. A nice little graphic appears displaying a tumbling coin eventually landing on heads. Too bad, you lose.

But how do you know the outcome is fair?

If the outcome is chosen on your computer you can edit the program to choose to win and the same applies to the opponent. The game isn't deterministic so you can't seem to validate the outcome.

Is it possible to have multiple independent adversarial agents agree on a non deterministic event?

# Answer
> 6 votes
This procedure will do the job:

1. each of the two peers generates a random number.
2. each peer creates a salted hash of its number and sends it to the other peer.
3. either peer rejects the request if it got the same hash that it sent.
4. once both peers confirm reception of each other's hashes, each then sends the other its actual random number.
5. each peer verifies that the hash sent by the other is actually a hash of the random number. reject the exchange.
6. the result of the coin flip is the XOR of the least significant bit of each number, i.e.

`(a & 1) ^ (b & 1)`

An alternative solution:

1. Each of the two peers decides between them to decide who should go first. Let's call them A and B, just to be original.
2. Peer A generates its random number, creates a salted hash from it and sends the hash to peer B.
3. B generates its random number and sends it to A.
4. A sends its random number to B.
5. B verifies that the salted hash is the hash of the number it has received.
6. the result of the coin flip is the XOR of the least significant bit of each number, as above.

I have asked this question on the cryptography site and have established that it is pretty secure. Apparently this is a variation on the Commitment scheme.

# Answer
> 2 votes
It turns out that not only can adversarial agents flip coins, but adversarial agents can play *poker*.

That said, it tends to be extremely computationally expensive, and quite difficult to get right. It's probably not worth the implementation effort. Look at how many multiplayer protocols are hilariously vulnerable to a malicious server (namely: all of them that I'm aware of), and how popular they still are, and it simply doesn't seem like a practical use of time.

StarCraft II is a good example. It's a game where scouting is critical, and knowing what the enemy is doing can give a phenomenal advantage, and five-figure or greater prizes regularly rest on the outcomes . . . and yet both computers have the entire game state stored at all times! It's trivial to write a program that lets you watch the opponent directly and get a huge leg up on them.

Turns out, none of the serious competitors use these programs. It's too easy to detect ("hey, Jim, how do you always know what I'm building the instant I'm building it?") and just not worth the trouble.

That said, if you want more info, you'll want to look into cryptography in detail - this isn't really in the realm of game development.

---
Tags: random, peer-to-peer
---


# Question
Title: Are 3D textures used for ground tiles in 2.5D games?
In an isometric system, each tile can be painted with texture. Normally, (if I recalled the technical term) the fastest method to paint these ground tiles with appropiate texture is to use something like UV mapping. However, that is not what I have seen on most of isometric tile-based game (such as final fantasy tactics). For example, if I map the texture onto each grid, then the texture would appears to be flat. Now, in modern day game, each tile may have some part sprouting out (for example, grass). What I want to ask is how should I implements the isometric system such that this feature is supported?

The next problem is, if I implement such feature, then I have to make change to the art process too--- UV texture mapping will not work anymore. My question is, what change would I have to make to the art process? How would an artist color a 3D isometric tile?

Basically, I just want to know how this isometric system will work out for both programmer and artists. The grid system seems to require high degree of coordination between programmer and artist.

EDIT: Rephrase the question

# Answer
I think you need to research 3D textures a bit more. 3D textures do not create visible 3D objects, like grass, they are applied to existing geometry. It's possible that 3D textures are used, but it's not likely. I've checked out screen shots of Final Fantasy Tactics. It appears to use 2D textures throughout.

See the image above. It's clear that the grass in this screen shot are textured quads set perpendicular to the ground. Also, check out the creature center screen. You can see that it's shadow and feet look very much like a 2D sprite over a 2D landscape.

**EDIT to address your EDIT**

You can implement the feature as I said, with the textured quad. The texturing of your ground tile is not affected with this addition. You will texture your ground tile the same as before. The quad for grass is exactly the same as you would use for one of your characters, except it's position is locked to the grid it's on.
> 1 votes

---
Tags: sprites, isometric
---


# Question
Title: Is using the applet class in a Java game a wise thing to do?
I am making an 2D multiplayer game in Java project, by using Java sockets and simple `java.applet.*`

Our teacher told us to use J2EE concepts in the project. Do I have to use JSP? Is it better or more employable in game development?

Am I doing the correct thing?

# Answer
Java applets are used for embedding Java applications in web pages. You should create an applet if, and only if, you are intending to do that — to provide your users a GUI written in Java which requires them to have a JRE installed on their computer.

From your other descriptions, it sounds like you are supposed to be making a web app — the game logic resides on your web server, and the interface is implemented in HTML and JavaScript. There are no applets involved here. This generally results in a more widely compatible and faster-loading interface. However, the HTTP request/response model means that it is more complex to build simple interactive interfaces robustly.

Personally, I would recommend reading up on the architecture of web applications before attempting to write one which is a game.
> 1 votes

---
Tags: java, eclipse
---


# Question
Title: How do I implement a field of vision for AI entities?
I am considering how to implement a field of vision system for my AI entities, but am not sure on the order of steps to take. The thought process that I had was to use a combination of radial distance and dot product.

Keeping in mind that this is a 3D environment (meaning that all vectors have 3 components), and I will be using quaternions for the orientation of all entities.

What order should I do these in? and is my logic accurate?

**Dot product**: Taking the position of the `playerObject`, and the position of the `AIEntity` create a vector, and then take the orientation quaternion, and convert that to a vector of fixed length, and perform the dot product between them (testing for a specific range of values) to see if it is within a given arc.

**Radius test**: Simple 3D radius to determine distance.

I know for sure that a dot product test should be quite simple (*3 subtractions, 3 multiplications, 2 additions, and however many operation to turn a quaternion into a vector*), but arriving at the orientation vector I have no direct idea (*if this process could be explained it would be of great help, I know I would have to multiply by the needed magnitude after normalizing*), and radius test is also simple (*3 subtractions, 3 additions, and 4 multiplications*) both of these would still include a boolean tests, but which order would reduce faster?

My first guess would be to be the dot product, and then the radius test; As the dot product would be outside of bounds if the player is outside of the arc or to far away, and the radius test would only fail if the object is to far away. I understand that both tests can give false positives, but for some reason I feel that the dot product test would give fewer.

# Answer
A few things that come to mind:

1. For the first test you shouldn't really (directly) need any quaternions; you have your AI's heading as a vector (and if you don't, you can quickly derive it from their orientation quaternion by transforming one of the axes), and so as you note your cone-of-vision test is just comparing the dot product of the normalized heading vector for your AI with the normalized vector-to-player.
2. While you would still need a distance check, the best way to perform that cull for most AI entities might be 'up-front' and implicit: use your spatial partitioning scheme to avoid ever doing the checks in the first place for AIs that are far enough from the player! In other words, rather than iterating over all AI Entities in the world for the field-of-vision tests, iterate over just a list of the entities that are in cells close enough to the player that you know the distance-based culling has some chance of passing.
3. Most importantly: both of these culling operations are fast enough already that it simply doesn't matter what order you do them in; you could do them both for every AI and it still shouldn't have any measurable impact on your performance. From that perspective, this smacks strongly of premature optimization. I *really* wouldn't worry about which cull will be more efficient/more effective at this point; unless you have literally thousands of AIs performing this check every frame, it Just Won't Matter.
> 1 votes

# Answer
One method is simply to add a view frustum to the A.I. and do frustum collision detection as you would for object culling in the rendering system. This will allow you to reuse some more code and you can test it out by adding an initial view frustum to the A.I. by reusing a camera object.
> 3 votes

---
Tags: c++, algorithm, ai
---


# Question
Title: Is there any advantage in using  DX10/11 for a 2D game?
I'm not entirely familiar with the feature set introduced by DX10/11 class hardware. I'm vaguely familiar with the new stages added to the programmable graphics pipeline, such as the geometry shader, the compute shader, and the new tessellation stages. I don't see how any of these make much of a difference for a 2D game though.

Is there any compelling reason to make the switch to DX10/11 (or the OpenGL equivalents) for a 2D game, or would it be wiser to stick with DX9 considering that that a significant share of the market still runs on older technologies (e.g. the February 2012 Steam surveys lists around 17% of users as still using Windows XP)?

# Answer
It depends on what you're doing. If you're using Direct3D, the *only* reason to switch is to gain access to hardware features that you can't get otherwise.

For a 2D game, it is theoretically possible that certain features might interest you. For example, OpenCL or DirectCompute. Civilization V gets some use out of DirectCompute for decompressing textures. This dramatically reduces load time, because it only has to load compressed data. And 2D games often have a lot of images. If load time is an issue, this might help.

OpneCL should be available on all GeForce 8xxx hardware and above. On ATI, it's available on HD 4xxx and better hardware.

I'd say the biggest feature you might use in DX11 is the ability to more arbitrarily read and write images in shaders. That could be useful for certain specialized effects. I can't think of any right now... which should tell you how likely this is to be important.

In general, I would say that if you're using D3D, you probably won't gain much. And if you don't already understand what the new features are and want to use them in your game, you almost certainly won't gain much. Most of them are going to be more complex.

OpenGL is different for one major reason. OpenGL 2.1 (the more-or-less equivalent to D3D9) *sucks* as an API. OpenGL 3.3 (plus some more recent extensions that run on 3.3 hardware) improves the API a lot. Explicit attribute location, separation of shader programs, everything in shading language pack 420, and so on.

Some of these work well enough in extension form against 2.1. Some of them... don't. I'm still not sure if it's OK to use explicit attribute locations with `attribute` declarations (before the current `in` syntax). Shading language pack 420 specifically says that it doesn't work with GLSL versions before 1.30 (aka: OpenGL 3.0).

That's not to say that GL 2.1 is unusable. It's certainly functional and serviceable, just not enjoyable. Though some drivers that you'll find that implement it *aren't* serviceable. ATI's DX9 hardware is no longer being supported, so those drivers are really buggy. And Intel *never* cared about OpenGL, so using shaders on their hardware is pot-luck.

But personally, if your intended user-base allows it, I would push to GL 3.3 if you're using OpenGL. If not, you'll just have to deal with the 2.1 issues.
> 5 votes

# Answer
There's a few things I think you should consider:

* If you have a well tested D3D9 engine, it's probably not worth porting to D3D11, if you won't make use of the new features. When starting from scratch D3D11 is much more tempting.
* How soon is your game's release date going to be? XP will be out of support in just over two years, and if you look at the historical data that XP install base is dropping quite quickly (~1% / month on Steam).
* Consider what proportion of the 17% of XP users would have a PC that meets the minimum spec for your game under D3D9. The higher that is the more worthwhile it is supporting them.
* DX10 is mostly pointless to use for new development. DX11 runs on the same operating systems and hardware (via feature levels).
* DX11 supports a software renderer (WARP) as a fallback device, which can be quick enough to run a game with low GPU requirements.
* Native DX9 supports more features than D3D11 does when it's using any of the D3D9 feature levels. Thankfully DX9 hardware in DX10 capable PCs is rare.
* DX10/11 hardware has much less varied capabilities so, if you make DX9 hardware use WARP, you don't need to worry about awkward limitations with things like non-power-of-two textures or awkward texel-pixel mapping.
* If your game is going to be hardware intensive DX11 has a few extra tricks available to boost performance. Multi-threading the draw code for example.
> 5 votes

# Answer
Geometry shaders alone are a reason to use D3D10/11, if you plan on having a large number of particles or sprites.

DirectCompute can also be used for some nice speed benefits.

Personally, simply having the far cleaner and nicer API of D3D10/11 is enough reason to never touch D3D9 or OpenGL again for any modern-Windows-only projects. Realistically, though, the need to target mobile devices with GL|ES and the still sizable WinXP crowd necessitates avoiding D3D10/11 and sticking to either D3D9 or OpenGL.

Note that going the OpenGL route lets you get geometry shaders, OpenCL, and other newer hardware features even on WinXP.
> 1 votes

---
Tags: 2d, graphics, directx
---


# Question
Title: Tips on combining the right Art Assets with a 2D Skeleton and making it flexible
I am on my first attempt to build a skeletal animation system for 2D side-scrollers, so I don't really have experience of what may appear in later stages. So i ask advice from anyone that been there and done that!

My approach:

I built a Tree structure, the root node is like the center-of-mass of the skeleton, allowing to apply global transformations to the skeleton. Then, i make the hierarchy of the bones, so when moving a leg, the foot also moves. (I also make a Joint, which connects two bones, for utility).

I load animations to it from a simple key frame lerp, so it does smooth movement.

I map the animation hierarchy to the skeleton, or a part of it, to see if the structure is alike, otherwise the animation doesnt start.

I think this is pretty much a standard implementation for such a thing, even if i want to convert it to a Rag Doll on the fly..

Now to my question:

Imagine a game like prototype, there is a skeleton animation of the main character, which can animate all meshes in the game that are rigged the same way.. That way the character can transform into anything without any extra code.

That is pretty much what i want to do for a side-scroller, in theory it sounds easy, but I want to know if that will work well. If the different people will be decently animated when using the same skeleton-animation pair. I can see this working well with a Stickman, but what about actual humans? Will the perspective look right, or i will need to dynamically change the sprites attached to bones?

What do you recommend for such a system?

# Answer
If I understand it right, you have the following situation:

* 1 Skeleton
* User-animations for that skeleton (player presses jump, the skeleton jumps)
* A set of sprites which you attach to the joints of that skeleton

What you need:

* AI-animations for the NPCs/enemies.
* A set of sprites characterizing the individual NPC

As long as you **don't change the skeleton**, you can simply "take-over" any NPC/enemy by dynamically switching from AI-animations to User-animations and setting the chosen character as user-controlled.

NOTE: Since you always have the same skeleton, all characters have the same hight, arm length etc. You might want to create and animate multiple skeletons to provide some variety.
> 1 votes

# Answer
Depending on art style, you will need to be able to animate the sprites attached to the bones.

Think of different attacks, where the hands might need to open or close. Or drawing "action lines" to make a punch look super fast or powerful. Or changing facial expressions.

If you're going for a more realistic art style, you're also going to find it difficult to make the seems/joints look natural, too. Drawing/rendering an entire sprite can produce much more visually appealing results, at the expense of less flexibility and possibly more work for the artists.

I would suggest looking into some of the Flash character animation packages. They provide the same features you have, plus vector art capabilities which can be handy, plus IK solver support which is necessary for some types of games.

A lot of 2D games actually just use Flash as their animation tool and import "characters" from SWF files.
> 1 votes

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


# Question
Title: Prototyping a puzzle game for solvability of levels
I am in the prototyping phase of making a puzzle game for iOS. The basic premise of what the player has to do is get from point A to point B by navigating through a maze like setup, while moving blocks out of the way, and avoiding enemies. This is my first approach to a game like this so I am wondering how others have made sure that the levels they create are solvable.

For example take the classic Unblock game where you have to move the red block off the game board by moving the other non red block pieces out of the way. It gets difficult because they are all in a tight space with not much movement to be had.

Has does the creator know that the arrangement of puzzle pieces are placed in a way that makes it possible to solve the puzzle? Do they start with paper prototypes and work from a solvable end state backwards to make the initial game board layouts?

# Answer
You seem to be making a Sokoban-style game. You have at least 3 options:

* Working from a solved end state. My gut feeling says this is not the optimal solution, because a) there are usually many end states and b) the puzzle does not only have to be solvable, but also interesting. So you should probably rather pursue one or both of the other 2 options:
* Automatic testing. Unless you are making huge levels, there are actually few actions a player can take, most of which will quickly lead to an unsolvable game state. That makes this perfect for a bot to exhaust all possible moves. If there is at least 1 path that leads to a solution, then the bot will find it.
* My preferred method would be manual testing. So you come up with a general idea for a level and lay out the board, you place obstacles and movable blocks, etc. Then you try to solve it as if you were a player, and you must consciously observe yourself. First of all, of course, is he level solvable? An automated test can help you very much with this, that will save you a lot of time. Second, **is the level fun to play, is it interesting enough so that the player wants to solve another?** That, apart from mere solvability, is the prime question if you want to make your game good. Next, you have to judge whether the level is easy or difficult, and you probably want to present them in that order: easy to difficult.

**TL;DR:** Implement a bot that can quickly check whether or not a given level is solvable at all, preferably in your level editor. Then design levels that could be fun to solve. Then manually playtest for the actual fun factor and difficulty.
> 10 votes

# Answer
This was also my question for a long time, I'm not sure If it's the best practice to create puzzles but I've got an answer now. To make the story short just imagine a simple valid end game situation, then move step by step backward and get to an start point.

Now to give more details: you want the puzzle to always be solvable, from gamers point of view it's not important if the puzzle has two or three solutions but to have at least one! Keeping that in mind you can start your design by making reverse valid moves. You said it's a game that you need to somehow move all the blocks off the gameboard. So for the first step imagine playing being at the edge of map, and there is no red blocks anywhere on the board. From that situation you start making reverse moves which are normal moves (reverse of another normal move), or pulling a block (which is reverse of pushing block) and pulling a block into the gameboard (which is obviously reverse for pushing that block out of scene). By this approach you know there is always at least one method to solve the puzzle, you can do undo all those steps you took to create the puzzle for solving it.

As Hackworth suggested creating puzzles this way might generate very simple or non creative puzzles at first, but after making some puzzles you will little by little learn what type of moves will result in a good puzzle. It's exactly the same way a player would gain experience to solve harder puzzles after solving simple ones.
> 3 votes

# Answer
This is a really interesting question. The best answer is that when designing your game mechanics, you should be considering how you want to be building your puzzles. Creating a puzzle that is fun to play is sometimes different from creating a puzzle system within which you can create the proper (large) number of fun puzzles - this is one of the important distinctions between Developer and Player.

But you already have some rules in place, so let's see how quickly we can get you to a good, repeatable puzzle creation method. We need to start with goals. (You can't win without goals!) Here are some possible goals for you:

1. The levels should be aesthetically beautiful.
2. The solution to the levels should be elegant.
3. Each level should have a unique solution.
4. Each level should have a well-defined difficulty (so you can order them properly)
5. Each level should be very different from every other level.
6. You need 1,000 levels.
7. Level creation should be simple enough for users to do it.

Come up with a goal that is right for you, and then work backwards from there. If you want beautiful levels - then you need a system within which you can make any arrangement solvable with limited tweaking - so that aesthetic considerations can dominate. If you need X levels, then you need a process you can automate - or have a big team working for you. ;) You goals should drive your solution.
> 1 votes

---
Tags: game-design, ios, puzzle
---


# Question
Title: VBO triangle not rendered using Freeglut Opengl 3.x, not understanding the weird fixes
I've just started to learn OpenGL 3 and I'm using freeglut for the context. I ask for a 3.3 context using:

```
glutInitContextVersion(3,3);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);

```

I then query the version I'm using with:

```
int glVersion[2] = {0,0};
glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]);
glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]);

```

Furthermore in my simple program, I create a triangle using a VBO. When I compile and run, the triangle is not rendered.

There are three ways that fix the problem and I don't understand why. The first method is to uncomment the first two lines of code I posted. In this case, the 3 next lines I posted, still report that I'm using OpenGL 3.3.

The second method it to wrap the VBO in a VAO.

The third one is to ask for a 2.1 context but in this case a version 3.3 is being reported again.

Could you help me understand this behaviour? Is it specified somewhere in the OpenGL specification that a VBO needs to be wrapped in a VAO in versions 3.x?

# Answer
```
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);

```

Never, ever, *ever*, ***EVER*** use FORWARD\_COMPATIBLE for ***ANYTHING***.

If you want a core OpenGL context in FreeGLUT, ask for it with the right function:

```
glutInitContextProfile(GLUT_CORE_PROFILE);

```

You never need the FORWARD\_COMPATIBLE bit set. I know that a lot of code does it, and if I could, I would scour the Internet and blacklist every webpage that says to use this flag.

The FORWARD\_COMPATIBLE flag should never mean anything to a compatibility context. FOWARD\_COMPATIBLE means that features marked deprecated aren't available; nothing is marked deprecated in a compatibility context, so therefore it should have no effect.

When used with a core context, it will remove the few features that have been marked deprecated but were never actually removed (wide lines and a couple of other things). But there's no point in doing that; if the ARB were going to remove them, they'd have done so already.

Therefore, the flag no longer serves a purpose. It meant something in 3.0, before core contexts. But it means nothing now.

In any event, the lack of the VAO is the problem. Once you have a core context (which I think you get by default when asking for a specific version number), you *must* use a VAO to store your vertex array bindings.
> 3 votes

# Answer
Since OpenGL 3.1 there are actually different types of contexts (called profiles):

* There is the compatibility profile, which is completely backward compatible down to OpenGL 1.0 and thus includes all deprecated functionality (like `glBegin/glEnd` or the fixed function pipeline).
* Then there is the core profile, which has all deprecated functionality removed and concentrates on modern features only (like VBOs, VAOs and shaders). You can use all those from the compatibility profile, too, but in the core profile you have to use them over their deprecated counterparts.

Now your actual problem is, that the core profile indeed requires you to wrap your vertex array state in a VAO. When you don't take any specific measures (like in your two code lines) you usually get the highest available OpenGL version (3.3 in your case) with a compatibility profile (which would allow non-VAO arrays). But in your second line you are actually requesting a forward-compatible context. This is a special kind of core profile context, which is even further restricted and doesn't even support features that are just planned to be deprecated in the future (only `glLineWidth` at the moment, I think).

So when commenting those lines you get a compatibility context and are allowed to use VBOs (or even client arrays) without VAOs. Requesting a 2.1 context seems in this case to be equal to just requesting an as high as possible context (3.3) with compatibility profile, as this is a superset of 2.1, anyway.

But to overcome this I suggest you to use VAOs and stay with the forward-compatible core context, as it is in general a good idea to concentrate on modern and future-ready OpenGL without deprecated features.
> 1 votes

---
Tags: opengl, vbo, glut
---


# Question
Title: How do I program a custom FPS overlay in Ogre3D?
I want to make a frames per second and debugging info overlay, similar to the one in the bottom of the following image, but without using SDKTrays or OIS.

I also want to be able customize its look, by changing its font and background color. How do I program something like this, in C++?

# Answer
> 5 votes
http://www.ogre3d.org/tikiwiki/Simple+Text+Output&structure=Cookbook

Simple as adding the 40 lines class file to your project loading a font of your choice and calling `TextRenderer::getSingleton().printf("text", "Last FPS: %f", renderwindow->getLastFPS());` from your update method body.

Don't forget to initialize and remove the text overlay!

EDIT:

You can change it color on the initialization of the overlay: `TextRenderer::getSingleton().addTextBox("text", "Last FPS:", 10, 10, 100, 20, Ogre::ColourValue(redValue, greenValue, blueValue, alphaValue);`

And the font on the fontdef file.

Not sure about the background, but you can easily add another overlay behind the text modifying the addTextBox method.

---
Tags: ogre
---


title: Make objects follow a strict path (Xna)

text:
# Question
Title: Make objects follow a strict path (Xna)
I am making a defence game. Naturally, this means that there needs to be objects following a path on the screen. I want to make it a strict path from one point to another to another. I could use an array of vertices, but i need some help. Can someone please show me some code that could help me with this? Thanks.

# Answer
> 6 votes
Okay, I gave it a quick test run and it seems to be working on my end. Here's my solution. Imagine your entity has the following members, and you'd like to make the entity follow whatever path is currently set to the `path` member variable:

```
class Entity
{
    Vector2 position;
    float speed;
    List<Vector2> path;
    void Update(float elapsed);
}

```

I started by adding an helper method inside the class that moves the entity towards some *goal*, and returns true if that goal was reached:

```
private bool MoveTowardsPoint(Vector2 goal, float elapsed)
{
    // If we're already at the goal return immediatly
    if(position == goal) return true;

    // Find direction from current position to goal
    Vector2 direction = Vector2.Normalize(goal - position);

    // Move in that direction
    position += direction * speed * elapsed;

    // If we moved PAST the goal, move it back to the goal
    if (Math.Abs(Vector2.Dot(direction, Vector2.Normalize(goal - position)) + 1) < 0.1f)
        position = goal;

    // Return whether we've reached the goal or not
    return position == goal;
}

```

Using this helper method, following the path is as simple as doing:

```
public void Update(float elapsed)
{
    if(path.Count > 0 && MoveTowardsPoint(path[0], elapsed))
        path.RemoveAt(0);
}

```

**Notes**

I think the only line that isn't really clear is the following:

```
Math.Abs(Vector2.Dot(direction, Vector2.Normalize(goal - position)) + 1) < 0.1f

```

What I'm doing here is checking if the direction before the move, and the direction after the move are opposite. I do this by checking if the dot product between both directions is close to -1 using an epsilon comparison. Another solution that seems to work is replacing the same check by:

```
Vector2.Distance(direction, Vector2.Normalize(position - goal)) < 0.1f

```

When I tried it the result was the same. As for the update loop:

```
if(path.Count > 0 && MoveTowardsPoint(path[0], elapsed))
       path.RemoveAt(0);

```

It's relying on the && operator not bothering to run the second portion of the operation unless the first one is true. So if there's no path, nothing else happens. If there's a path, then `MoveTowardsPoint` is called, and its return value is what decides whether we should remove the point from the path list or not.

---
Tags: xna, game-design, vector
---


# Question
Title: Calculating a quaternion so a bone points in a specified direction
In an attempt to solve this question, I decided to figure out the absolute (world space) directions of each joint in the source pose (as normalized unit vectors), and then rotate the joints of the target to match that direction. The problem is, how do I calculate the rotation quaternion such that the bone (the vector from the joint to its child) is in the specified direction in world-space.

**UPDATE:** Here's my current thinking. For each bone, the transformation matrix will be:

```
(1) absolute transform = local rotation * relative transform to parent in bind pose * parent absolute trasform

```

So, say we have 3 joints: Shoulder -\> Elbow -\> Wrist. We already have an absolute transform for Shoulder, and are trying to calculate the rotation for Elbow such that Elbow -\> Wrist will go in the same direction it is in the source animation. From (1), the absolute transformations will be:

```
(2) ELBOW absolute = ELBOW local * SHOULDER to ELBOW relative * SHOULDER absolute

(3) WRIST absolute = WRIST local * ELBOW to WRIST relative * ELBOW absolute

```

By substitution we get:

```
(4) WRIST absolute = WRIST local * ELBOW to WRIST relative * ELBOW local *
                     SHOULDER to ELBOW relative * SHOULDER absolute

```

Our constants are: `ELBOW to WRIST relative`, `SHOULDER to ELBOW relative`, and `SHOULDER absolute`. `WRIST local` will consist only of rotation, no translation/scale. The problem is to find a value for `ELBOW local` such that...

```
(5) normalize(position(ELBOW absolute) - position(WRIST absolute)) = desired direction

(6) ELBOW local consists only of rotations (no translation/scale)

```

Now since we know the length of the bone and the desired direction it's possible to estimate the ***position*** part of of `WRIST absolute`, but the rotation will be unknown (and this problem seems impossible to do recursively, AFAICT).

My initial thought was that because `WRIST local` is rotation-only and I will solve for it in the next iteration of the loop, I could completely ignore it in the calculation of `ELBOW local`. Steven Stadnicki's answer below suggested it might not be that easy, since the orientation of the bone is important for skinning. However, if I can get this working on a stick figure I can cross that bridge later.

# Answer
> 3 votes
From your description of your problem, it sounds like the heart of the matter might be that your representation is currently missing data. A bone isn't simply the vector from one joint to the next — it's a full transformation matrix representing the orientation of the local frame, either with respect to world space or with respect to the local frame of the next bone 'up the chain'. For instance, imagine a character with a scar on their forearm; having the vector from the character's elbow to their wrist will tell you where their hand will be positioned, but it doesn't carry enough information to let you know where the scar would be — for instance, whether it's pointing up or pointing down. This orientation information should be part of your source skeleton.

Once you have things represented in terms of full local orientation frames and not simply directional vectors, the rest of the information should fall out easily; exactly as you suggested in your post, you'd use matrix inverses to 'peel off' the layers of your transformations and get at the juicy matrix M in the middle. For instance, if you have childAbs = childRel * M * selfRel * parentAbs, then multiply by childRel-1 on the left of both sides, and then parentAbs-1 * selfRel-1 on the right of both sides to get M = childRel-1 * childAbs * parentAbs-1 * selfRel-1. Note that inverting a product of matrices changes the order their inverses are multiplied in, so that order matters here — (A * B)-1 isn't (in general) equal to A-1 * B-1, but instead to B-1 * A-1.

Once you've got your matrix M, there should be plenty of information on the web on how to convert it to a quaternion; if you're looking for help with that particular step, then let me know and I can flesh this out with a couple of links, but it seems like there are several other issues you'll have to tackle right now before you even need to consider it.

**EDIT:** After a few days to think about it, I've written up this rough description of the process for going from worldspace to local information; hopefully this will shed a bit more light.

I'm going to work in terms of a decoupled scheme where each bone consists of a rotation matrix and a displacement; the rotation matrix is applied at the root of the bone, and the displacement is given in bone-local coordinates. This does two important things:

1. It allows for multiple bones to be attached to the same socket, making a proper skeletal tree a bit easier- for instance, collarbones can be easily attached to a central point between the shoulderblades, or finger bones to a central point on the wrist.
2. It means that most animation of a bone can be done by just changing the rotation associated with that bone; for instance, a bicep can be moved by changing its orientation, causing the location of the elbow to be shifted around. In fact, bones will often have a displacement of (0, 0, L), where L is the length of the bone - the far end of the bone is directly along the local-Z axis from the bone's attach point.

This isn't necessarily the approach I'd recommend for implementation, but it's the most straightforward for *talking* about how to do it; while the precise results won't be directly applicable to your situation, IMHO that's actually for the best: it gives you better chances of understanding how the derivation works and how to derive the precise formulas that will apply to your own version of the problem.

A few quick definitions of the quantities we're working with: A superscript of 'w' designates a worldspace value, while 'l' denotes a local value. We'll use P for position, and R for rotation; for instance, Pwbone would be the worldspace target position of a bone, (as opposed to its base position, which of course is the target position of its parent), while Rlbone would be the local orientation of the bone - that is, how it's rotated with respect to its parent's frame.

Now, given this we can derive the target position and orientation of any given joint - as some of the comments suggest, the relationship is recursive. In particular, we have

Rwchild = Rwparent * Rlchild

and

Pwchild = Pwparent \+ Rwchild * Plchild

(These say, respectively, 'The world orientation of the child is its local orientation composed with the world orientation of its parent' and 'The world position of the child is its parent's world position offset by its local displacement (as translated into the appropriate worldspace coordinates)'.)

Given this, we can now solve these equations to find the bone's parameters - that is, Rl and Pl \- in terms of the worldspace data we're given. This also gives another reason why we need not just the position but also the worldspace orientation of all the joints; it's an essential component to the solve.

Finding the local orientation is straightforward; we can just multiply both sides of our orientation equation by the inverse of the parent's worldspace orientation, getting

Rlchild = Rwparent-1 * Rwchild

The local displacement is also relatively easy to figure, since we know the displacement in worldspace and the transformation matrix to get from local space to worldspace (which means we know the matrix to go the other way) :

Plchild = Rwchild-1 * (Pwchild \- Pwparent)

Notice one thing, too: none of these equations depend on the local position or orientation of the parent bone, just the worldspace values for the parent and the child - so while they *feel* recursive (and the calculation to find the worldspace values for the bones needs to go from the root of the skeleton out to its leaves because of dependencies on results) they can actually be done in any order.

Hopefully this gives you a better sense for what's going on - it's easy to get bogged down in all the transformations flying around. Let me know if this helps!

# Answer
> 2 votes
If I got this right, you are storing the whole skeleton bones vertexes into a matrix. I think your problem is more related to the way you are storing the Bones than to quaternions themselves.

I'll try to explain what I mean:

Since you basically have the result of the rotation (a rotated bone to use as a model), and you want to know the quaternion that would generate that result for other bones, why can't you store the bones as vectors, instead of generating a matrix?

You could a bone stored as a vector made of 2 points (Head,Tail). Since you are rotating it, Head will be the fulcrum and Tail will rotate around an arbitrary axis. That's a quaternion's job.

Now, since you have Bone A a 'rested' position, and you want to match Bone B direction you need to know the amount of rotation Alpha and the Axis. Right?

Getting the angle between the 2 Bone Vectors A and B you will find Alpha, and the normalized result of the cross product of AxB will get you the Axis.

The only thing that is getting this more complicated for you is that you need to extrapolate the Bone Vector from the matrix you're using beforehand so maybe you could just store the bones as vectors (pair of points) instead of creating a matrix.

Also, since you are basically rotating a bone in relation to how its parent was rotated (that's what I got from your code) then you *probably* could simply ignore all that.

Since you want to match another bone's position, you already know that position to be legit, so all the relative-rotation stuff shouldn't be necessary.

---
Tags: c#, rotation, slimdx, quaternion, skeletal-animation
---


# Question
Title: Check collision between instantiated objects?
I am using a script to instantiate multiple objects having rigidbody with different velocities at different positions. I want to destroy two or more objects when they collide, but I'm not getting anything inside:

```
void OnCollisionEnter(Collision collision){}

```

The details of the object I'm instantiating. https://i.stack.imgur.com/dKhgm.png

The script is attached to an empty GameObject and Instantiated GameObject is stored in a array of GameObjects:

```
 Block[0] = Instantiate(boxPiece) as GameObject;

```

where boxPiece is the Object I want to instantiate. And I'm checking for collisions in this very same script.

# Answer
After reading this Unity collision question I created a new script with `void OnCollisionEnter(Collision collision){}` and attached it to all the new Objects I'm creating in my script using `AddComponent("NewScriptName")` now it does detect collisions but I still feel that it's not the right way to do it.
> 0 votes

# Answer
1. Check that the instantiated objects have a collider.
2. Are your objects moving at very high speeds? If they are they might jump over each other when they move faster than the length of the opposing collider.
> 2 votes

---
Tags: c#, unity
---


# Question
Title: How do I create modular/replaceable game/engine code interfaces with C++?
I've spent some time when I can spare it experimenting with c++ and at the same time learning a bit about game programming. I like most thought I'd start with creating a simple game engine but with some experimenting and plenty of advice along the lines of create a game, not an engine I forgot about the engine and just experimented with building a game.

Suffice to say in the process of doing that I hacked together rendering code (ogre3d) and physics (bullet) and input/output (OIS) and a couple of times over experimented with basic game ideas to the point of loading a map and being able to walk around it. Nothing special I know but it's an achievement for me.

Moving on from that now I would like to learn more about creating reusable code that falls more under engine programming than just a game. I'm sure the skills will be transferable to more than just games.

Basically I'd like to move from having everything intertwined to being able to separate and replace the individual parts. For example, build a 3d renderer dll/so in OpenGL and another with DirectX (as a dll). Or the same for other aspects such as Physics, sound, input, networking.

I'm learning about general dll programming and shared libraries on Linux but would like some more information with regards to game specific interfaces. I am also aware that Ogre3d which I previously mentioned is already cross platform and capable of both opengl and direct-x... I'm not saying I want to replace a library like that, more make it able to be unplugged and have something else plugged in instead.

So you are aware. My programming experience has been C with some more recent exposure to C++. Mostly recently I have been doing web development with both PHP and C#.NET (mostly php). I've also got average experience with c#, python, perl, etc. I'm a bit of a jack of all trades and I pick up things pretty quickly. What I'm hoping for is not to be spoon fed the code but rather some good places to research the concepts etc. (Although I won't turn down code if you're offering) ;)

# Answer
> 2 votes
You are answering pretty much to you own question. You write to, or create your own interfaces. And then implement them using different methods.

For exmaple:

```
interface IDraw
{
  public void DrawPoint(int x, int y);
}

class DirectXDraw : IDraw
{
  public void DrawPoint(int x, int y)
  {
    // direct x code
  }
}

class OpenGLDraw : IDraw
{
  public void DrawPoint(int x, int y)
  {
    // open gl code
  }
}

class Game
{
  private IDraw drawEngine;

  public Game(IDraw drawEngine)
  {
    this.drawEngine = drawEngine;
  }

  public void Draw()
  {
    // use drawEngine here
  }
}

```

basically this is not much different from any other area, this is a common approach in object-oriented programming. In C++ AFAIK abstract classes with pure virtual functions are used in place of interfaces.

---
Tags: opengl, c++, 3d, directx
---


# Question
Title: Debugging a custom content pipeline processor in XNA?
I'm working with a custom made content pipeline designed to work with the program Tiled (using the TiledLibrary found here). I am running into trouble with the MapProcessor class in the custom content pipeline, and would like to be able to debug it to find out what exactly is going on.

However, when I try to use lines such as `Console.WriteLine(...)` or breakpoints, these lines are ignored by the debugger built into Visual Studio. Is the content pipeline barred from access to things like console writing and breakpoints? If so, is there a way to fix this?

I'm a bit new to C#, XNA, and Visual Studio, so bear with me if this is a dumb question. I tried googling my problem (as well as searching this stackexchange) but was unable to find any answers. Thanks!

# Answer
You can launch a external debugger...

You only have to add the line `System.Diagnostics.Debugger.Launch()` and you will can debug it.

I think that you maybe need Visual Studio Professional or the .Net Framework SDK to use this solution... it was needed with the old XNA frameworks, now I'm not sure.

More info on debugging the content pipeline

Other interesting point, when you are debugging this way a processor, is that shouldn't assign the processor to more than one asset, because if it has not been changed, I remember be asked for debug every asset it's not funny when you have assigned the processor to 500+ assets.

If you want to launch warnings you have a `Logger` interface in your `ContentProcessor` context variable to let do it: ContentProcessorContext.Logger Property.
> 4 votes

# Answer
Check out the project template made by Stephen Styrchak.
> 1 votes

# Answer
Make sure your game solution is selected and then go to:

Project -\> Properties -\> Application

Set the output type to Console application. This will show the console when you run your game so your Console.WriteLine() will appear.
> 0 votes

---
Tags: xna, xna-content-pipeline, debugging
---


title: Tessellating/Subdividing a quad

text:
# Question
Title: Tessellating/Subdividing a quad
I am creating a quad that starts as a single quad, then divides itself multiple times (from 1 to 4 to 16 to 64 to 256 and so forth) but I have encountered an issue. When I get to 64 sub divisions only 16 quads are shown.

Here is my `Quad` class:

```
class Quad {
        GraphicsDevice device;

        private int rows = 1;
        private int columns = 1;

        private int width = 64;
        private int height = 64;

        private Quad[,] quads;
        private Quad parent;

        private List<VertexPositionColor> vertices;
        private List<int> indices;

        private Vector2 index;

        public List<VertexPositionColor> Vertices {
            get { return vertices; }
            set { }
        }

        public List<int> Indices {
            get { return indices; }
            set { }
        }

        public Vector2 Index {
            get { return index; }
            set { index = value; }
        }

        public int Width {
            get { return width; }
            set { }

        }

        public int Height {
            get { return height; }
            set { }
        }

        public void SetSize(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public void SetParent(Quad parent) {
            this.parent = parent;
        }

        public List<Quad> GetChildren() {
            List<Quad> quadList = new List<Quad>();

            if (quads != null) {
                for (int x = 0; x < this.quads.GetLength(0); x++) {
                    for (int y = 0; y < this.quads.GetLength(1); y++) {
                        quadList.AddRange(quads[x, y].GetChildren());

                        OutputBuffer.STRING_BUFFER.Clear();
                    }
                }

                OutputBuffer.Add("Children Count: " + quadList.Count);

                return quadList;
            }

            quadList.Add(this);
            return quadList;
        }

        public Quad(ref GraphicsDevice device) {
            this.device = device;
        }

        public void Construct() {
            ConstructVertices();
            ConstructIndices();
        }

        private void ConstructVertices() {
            vertices = new List<VertexPositionColor>();

            Vector3 parentPosition = parent != null ? new Vector3(parent.Index.X * parent.Width, 0, parent.Index.Y * parent.Height) : Vector3.Zero;

            Vector3 backLeft = new Vector3(index.X * width, 0, index.Y * height + height) + parentPosition;
            Vector3 backRight = new Vector3(index.X * width + width, 0, index.Y * height + height) + parentPosition;
            Vector3 frontLeft = new Vector3(index.X * width, 0, index.Y * height) + parentPosition;
            Vector3 frontRight = new Vector3(index.X * width + width, 0, index.Y * height) + parentPosition;

            vertices.Add(new VertexPositionColor(frontLeft, Color.White));
            vertices.Add(new VertexPositionColor(frontRight, Color.White));
            vertices.Add(new VertexPositionColor(backLeft, Color.White));
            vertices.Add(new VertexPositionColor(backRight, Color.White));
        }

        private void ConstructIndices() {
            indices = new List<int>();

            indices.AddRange(new int[] { 0, 2, 3, 3, 1, 0 }.ToList());
        }

        public void ConstructChildren() {
            if (quads == null) {
                quads = new Quad[2, 2];

                for (int x = 0; x < quads.GetLength(0); x++) {
                    for (int y = 0; y < quads.GetLength(1); y++) {
                        quads[x, y] = new Quad(ref device);
                        quads[x, y].Index = new Vector2(x, y);
                        quads[x, y].SetSize(width / 2, height / 2);
                        quads[x, y].SetParent(this);
                        quads[x, y].Construct();
                    }
                }

                this.vertices = null;
                this.indices = null;
            } else {
                for (int x = 0; x < quads.GetLength(0); x++) {
                    for (int y = 0; y < quads.GetLength(1); y++) {
                        quads[x, y].ConstructChildren();
                    }
                }
            }
        }
    }

```

I think the problem is when the vertices are being constructed. I think those four sets of 16 quads are being drawn on top of each other. And I definitely think it's doing the subdivision.

Here's the `QuadRenderer` class (note that I just hacked to together to test the above, so don't expect quality code):

```
class QuadRenderer {
    GraphicsDevice device;

    Quad quad;

    Matrix view;
    Matrix projection;
    Matrix world;

    Effect effect;

    Vector2 position = new Vector2(16, 16);

    int columns = 2;
    int rows = 2;

    KeyboardState previousKbState;

    public QuadRenderer(GraphicsDevice device) {
        this.device = device;

        this.quad = new Quad(ref device);
        this.quad.Construct();
    }

    public void LoadContent(ContentManager content) {
        this.effect = content.Load<Effect>("Effects\\Effects");
    }

    public void Update() {
        ProcessInput();

        view = Matrix.CreateLookAt(new Vector3(position.X, 80, position.Y), new Vector3(position.X, 0, 16 + position.Y), new Vector3(0, 1, 0));
        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 300.0f);
    }

    public void ProcessInput() {
        KeyboardState kbState = Keyboard.GetState();

        if (kbState.IsKeyDown(Keys.W)) {
            position.Y += 2;
        }
        if (kbState.IsKeyDown(Keys.S)) {
            position.Y -= 2;
        }
        if (kbState.IsKeyDown(Keys.A)) {
            position.X += 2;
        }
        if (kbState.IsKeyDown(Keys.D)) {
            position.X -= 2;
        }

        if (kbState.IsKeyDown(Keys.Space) &&
            !previousKbState.IsKeyDown(Keys.Space)) {
                this.quad.ConstructChildren();
        }

        this.previousKbState = kbState;
    }

    public void Draw() {
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        RasterizerState rs = new RasterizerState();
        rs.CullMode = CullMode.None;
        rs.FillMode = FillMode.WireFrame;
        device.RasterizerState = rs;

        Matrix world = Matrix.Identity * Matrix.CreateTranslation(new Vector3(64 / 2, 0, 64 / 2));
        effect.CurrentTechnique = effect.Techniques["Coloured"];
        effect.Parameters["View"].SetValue(view);
        effect.Parameters["Projection"].SetValue(projection);
        effect.Parameters["World"].SetValue(world);

        foreach (EffectPass pass in effect.CurrentTechnique.Passes) {
            pass.Apply();

            foreach (Quad quad in this.quad.GetChildren()) {
                //world *= Matrix.CreateTranslation(new Vector3(quad.Index.X * quad.Width, 0, quad.Index.Y * quad.Height));

                device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, quad.Vertices.ToArray(), 0, quad.Vertices.Count, quad.Indices.ToArray(), 0, quad.Indices.Count / 3);
            }
        }
    }

```

# Answer
I found the problem, I was not taking the parent index and adding it to the child's index, I changed the following line:

```
quads[x, y].Index = new Vector2(x + index.X * 2, y + index.Y * 2);

```

and removed the following (and all references to it):

```
Vector3 parentPosition = parent != null ? new Vector3(parent.Index.X * parent.Width, 0, parent.Index.Y * parent.Height) : Vector3.Zero;

```
> 1 votes

# Answer
You are not showing all the code but I suggest making `width` and `height` floating point values. You are dividing them by 2 at each subdivision, meaning they'll eventually reach zero.
> 2 votes

---
Tags: c#, xna, mathematics, recursion
---


title: Camera rotation not working right?

text:
# Question
Title: Camera rotation not working right?
I'm new to game programming but I've read a lot of tutorials. I was just trying to make my own camera class but instead of the scene rotating around the camera, the camera stays stationary while everything else rotates! I triple checked the tutorials but can't find anything else to explain what's going wrong. Here's the code for my rotation methods:

```
void camera::rotate(float angle1,float angle2)
{
    glRotatef(angle1,1.0f,0.0f,0.0f);
    glRotatef(angle2,0.0f,1.0f,0.0f);
}
void camera::rotate(float angle1,float angle2,float angle3)
{
    glRotatef(angle1,1.0f,0.0f,0.0f);
    glRotatef(angle2,0.0f,1.0f,0.0f);
    glRotatef(angle3,0.0f,0.0f,1.0f);
}

```

# Answer
One of the more tricky aspects of 3D programming is getting complex transformations right.

In OpenGL, every point is transformed with the model/view matrix and then with the projection matrix.

the model view matrix takes each point and translates it to where it should be from the point of view of the camera. The projection matrix converts the point's coordinates so that the X and Y coordinates can be mapped to the window easily.

To get the model/view matrix right, you have to start with an identity matrix (one that doesn't change the vertices), then apply the transforms for the camera's position and orientation *in forward order*, then for the object's position and orientation *in reverse order*. The reason for the ordering is that you're using the same operation for both kind of transforms - camera and object - but transforming an object into the proper camera position/orientation is the inverse of transforming the camera into the proper position/orientation.

Another thing you need to keep in mind is, rotations are *always* about an axis that is centered on the origin (0,0,0). So when you apply a rotate transform for the camera, whether you are *turning* it (as you would turn your head) or *orbiting* it around the origin (as the Earth orbits the Sun) depends on whether you have previously applied a translation transform.

So if you want to both rotate and orbit the camera, you need to:

1. Apply the rotation(s) to orient the camera
2. Apply translation(s) to position it
3. Apply rotation(s) to orbit the camera round the origin
4. (optionally) apply translation(s) to move the camera in its set orientation to move it to orbit around a point other than (0,0,0).

Things can get more complex if you, say, want to point the camera at a point that is not (0,0,0) and also orbit that point at a set distance, while also being able to pitch or yaw the camera. See here for an example in WebGL. Look for `GLViewerBase.prototype.display`.

The Red Book covers transforms in much more detail.

Also note gluLookAt, which you can use to point the camera *at* something, without having to use rotations.
> 1 votes

---
Tags: c++, opengl, camera
---


# Question
Title: Database structure for level packs, levels and level information
I have a game which shall consist of several level packs (and also be extended by additional level packs). Each level pack should contain some levels. Each level will have its own level information. How do I store this information? Do I use one big database, or should I split the information into several databases? (one database for one levelpack, or even one database for one level?)

EDIT: To be more precise, I want to store the following level information:

* Several simple key-value pairs
* Some (primitive type) arrays
* An array-list (with informations like: x-, y-coordinates and an Integer)

This information should be stored for each level. I am planning for creating 10-20 levels. These levels shall be located in level packs. I need to get access to them dynamically (printing a level list with the level information an the display).

# Answer
Unless you're making an MMO or something so huge that you need it (and no, 10,000 elements doesn't cut it), you should not be using a relational database of any kind. Especially not for something as trivial as a list of stuff that goes in a level or series of levels. That's tremendous overkill.

Just use a file. An XML file if you must. It contains a list of files that are associated with each level. Or group of levels.

There is no need to go to the level of a relational DB.
> 1 votes

---
Tags: data-structure, databases, levels
---