# Question
Title: What should I know to start in game development?
I know this is asked very often here and probably my question will get closed, but I am clueless in this direction.

I want to start creating my own PC games. I know C++ and a bit of C#. I created a little game in Html5 using plain javascript so I know I can do this kind of stuff.

But I need some guidance:

1- Is enough to know only C++/C# to get started?

2- What program should i use for its development?

3- What is actually a game engine and how can i use it? Should i use it?

You can add whatever you think it's useful for a starter.

Thanks!

# Answer
> 4 votes
There are plenty roles in Gamedev. business, each role splits at least into a dozen, if you want to work at some company as a game developer here are some roles you can pick:

> Artists: http://en.wikipedia.org/wiki/Game\_art\_design

GUI Artists, concept artists, general 2d artists, 3d artists, 3d sculpters, 3d animators, pixel artists..

> Game designers: http://en.wikipedia.org/wiki/Game\_design

game designers, writers, sound designers, testers, UX (User Experience) designers

> Game programmers: http://en.wikipedia.org/wiki/Game\_programmer

Artificial intelligence programmer, Sound programmer, Gameplay programmer, Scripter, UI programmer, Input programmer, Network programmer, Game tools programmer, Porting programmer, Technology programmer, Generalist, Lead game programmer

Those are just a few general roles, that split into smaller bits, such as the combat programmer who is a specialised gameplay programmer.

> Directors, art director, main director, lead game designer etc. They are the guys who have to know how everything works, to maintain a stable workflow between the game design teams.

Look at careers section at EA, it is the best reference when it comes to game development jobs.

> https://careers.ea.com/

If you want to go **"solo/indie"** you will have to know a bit of everything; kind off like the game director who needs to know the role of every team member. Here are a few tips.

If you would like to create 3D games you have to know about 3d modelling: You must know how to use 3d creation tools, what formats are there etc. For start I'd recommend Blender, due to the fact that it is light (120mb~~) and opensource. Or simply get the Autodesk 3d Studio Max or MAya. Those weight a bit more (3.2gb~) but have all the functions a 3d artist needs, they are supported by most game engines when it comes to 3d asset pipeline. You can download a free student version from www.students.autodesk.com . When it comes to learning I'd advice you to use the cg tutorials that are avaiable over the internet, for Blender Blendercookie.org , For anything else Digitaltutors.com - I used to learn on that website, they have thousands of hours of video tutorials on 3ds MAx/Maya/Zbrush/PhotoShop. I don't think that there is a better website, the only con I found about it is the fact that it costs $45 a month.

//Keep in mind that if you would like to use Autodesk student software for commercial purposes you are not allowed to do that, and you will have to get a copy for about $4000 to be "legit".

> http://www.blender.org
>
> http://www.students.autodesk.com

As for the indie game engine, depending on the enviroment you will be working with you got many options. XNA, Unity, Blender Game Engine, Unreal Engine, HeroEngine.

> http://en.wikipedia.org/wiki/Microsoft\_XNA
>
> It is a crossplatform 3d engine, which can be perfect for those who know only Javascript or C#. The game engine is free for commercial use for indie studios, while the bigger studios with at least $100,000 yearly revenue are required to get the Full/Pro version. You keep all income, no revenue splits. You can make mobile games, online games, MMo games that can be crossplatform, distributed on Linux, Windows, Mac, Android, IOS. Games like the Temple Run use it. It is the game engine behind the SlenderMan game.

You need to know C#, Javascript, or UnityScript in order to make games with it.

> \- Perfect FPS game engine

You can use it Commercialy, you keep any money you earn below ~$52,000. After that you are supposed to split 25% of the revenue. Fair if you consider the ammount of work they have done in the engine creation process, tens of AAA game titles used the Unreal Engine, Mass Effect 3, Bioschock Infinite, Unreal Tournaments (...) and more.

This engine gives you a complete Game Development kit with terrain editors, built in AI and so on.

It utilises its own script language called the UnrealScript, which is a C++ based language

> http://Heroengine.com \- Perfect solution for the MMO Development. "Minecraft world editor"

It is the perfect engine when it comes to MMO Develpment. You do not have to handle the server architecture; everything is done in the Herocloud. In order to work with it, you have to buy a work station for at least ($100/year) or 25 CCU workstation for ($400/life time).

www.heroengine.com/heroengine/why-heroengine/

If the game starts and you start making money, they will charge yo 30% of the revenue with no additional costs and they will handle the servers. If you pay $75,000 for the source code license you will only have to pay 7% of the revenue + you will gain the ability to host your game yourself in your own cloud.

It uses HeroScript, based on C++, for the 3d graphic pipeline you must use Autodesk 3DSMax/Maya as nothing else is supported.

The HeroEngine gives you many built in features, such as the facegen, speedtree (used in Avatar movie)

> Sound

For a start I'd tinker around the Audacity, which is basic sound editor. Free GNU

> http://en.wikipedia.org/wiki/Audacity\_(audio\_editor)
>
> 2d art If you can afford one, get an Adobe Photoshop as it is fairly the best 2d edition tool 2d graphic edition.

You can also use the Gimp, which is an opensource program that has probably everything you might need to make your game.

> http://www.adobe.com/products/photoshop.html
>
> http://www.gimp.org

I posted the overall stuff you might need to know to find yourself around the game creation process. There are more engines as the Tourque 2d, more software to use like the Allegorythmic Substance creator for smart textures, or the 2d Illustrator. But I hardly believe that anyone would be able to master everything at once, so check out what suits you most and then go deeper into the rabbits hole. Whether it is the gamedesign, story/code writing or art design - You have to choose

# Answer
> 3 votes
1.

For a very simple game where you don't make a whole engine but just program the game as you please, this is enough, ***if*** you are able to learn things as you go along and the required math too (linear algebra comes to mind). For more complex games you either need to collaborate with artists and other content producers (3d-modelling if it's a 3d game), or if you are multi-talented learn that yourself as well.

2.

What are you talking about here? Programming IDE or game IDE? Unity or UDK are popular. They are also their own game engines. If you program a simple game like I'm talking about in (1) maybe you shouldn't bother with a full game engine IDE yet.

3.

I'm quoting wikipedia on this: `The core functionality typically provided by a game engine includes a rendering engine (“renderer”) for 2D or 3D graphics, a physics engine or collision detection (and collision response), sound, scripting, animation, artificial intelligence, networking, streaming, memory management, threading, localization support, and a scene graph.`

# Answer
> 2 votes
You should know that this is hard coding, which you already know.

1- It's not enough just knowing how to code. There are mathematical subjects like trigonometry and algebra that are really useful and necessary when developing games (specially 3D ones). A little background on elementary physics is a good plus. In case you need guidance, there are books like: "3d math primer for graphics and game development" and "Physics for Game Developers". However, you don't need to know everything to start. Start making games and learn by doing. The keyword here is research.

2- It's your choice depending on the language and platform you're aiming. Use the editor and compiler you're already used to and try to install and import the libraries with that in mind (or learn the most used IDE for that language/platform). I advise to use APIs, frameworks or engines instead of making a whole game from scratch.

3- A game engine is a cohesive set of tools (editors, libraries, APIs) to make games given a fixed pipeline. The best way to use it is reading/watching tutorials and books. You should use it in order to speed-up the development process and not reinventing the wheel. Start by learning GameMaker, for example. It's one of the simplest game engines out there. It'll help you understand an engine pipeline and philosophy. After having a little mastery you can move onto Unity3D or UDK.

Well, there is no perfect path or something. There are several paths you can take in order to make your own PC games. If you already know C++ and a little C# the best is to leverage on APIs and frameworks. Clanlib is an excellent choice for C++ coders and MonoGame for the ones who prefer C#. However, given the mobile revolution and the fact that you already know Javascript, I advise to learn Cocos2D-html5 or Enchant.js instead.

---
Tags: c#, c++
---


# Question
Title: When using MVC, what is the proper way to handle a view refresh when the model isn't ready?
I'm about to start building a game and am having trouble understanding the proper course of action when it's time to refresh the screen, but the model hasn't finished its calculations. I assume this isn't a huge problem for my little 2d platformer, but with many complex games there must be some hefty calculations that don't render in 1/30th of a second - I see these games stutter, but what's going on? Is the view just skipping this cycle? Is it an observer that's waiting for the model and will hang until the model is ready? Or will it display the models current state without regard to the computations ongoing? What's the correct way to handle this situation?

# Answer
The correct way is to skip that frame and wait until the model is ready. If you find that the model update is taking too long, causing frames to be skipped too often, it's a better solution to optimize that instead of overcomplicating the code trying to be smart on the view side.

A popular alternative is to use frame interpolation in the view, but it's not a good solution. When the update is fast enough, the difference isn't visible: it turns out that interpolation was not necessary after all and it comes with the development cost of having to implement it. When the update is slow enough, you start perceiving weird rendering artifacts. These artifacts come from the fact that the formulas used by the view for the interpolation step are just an approximation of what the model is doing, with big steps come big approximation errors. E.g. you won't be implementing a parallel collision detection system in the view, because that's the job of the model to start with.

So, with interpolation, you basically replaced one problem by another. Just skip the frames and optimize the update code.
> 4 votes

---
Tags: frame-rate, lag, mvc
---


title: Where to put input detector?

text:
# Question
Title: Where to put input detector?
So below is the usual XNA Game Component override method. If I want to add a touch input detector (lets say, I want to draw a rectangle under touched screen area), where do I put it and how? Googled it, but I found no satisfying solutions.

```
public override void Initialize()
{
    base.Initialize();
}

protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
    base.LoadContent();
}

protected override void UnloadContent()
{
    base.UnloadContent();
}

public override void Update(GameTime gameTime)
{
    base.Update(gameTime);
}

public override void Draw(GameTime gameTime)
{
    base.Draw(gameTime);
}

```

Thanks

# Answer
> 4 votes
You check for input in your `Update` method.

* `Update` is where you'll respond to input, move entities around, do collision detection, update counters, **update** and data that needs updating.
* `Draw` is where you draw everything...
* `Initialize` is where you set initialize whatever data structures you're using.
* `LoadContent` is where you load save states, load textures/models/sounds, etc.
* `UnloadContent` is where you unload all the stuff you loaded in `LoadContent`.

As for **how**, you can get the touch state:

```
//inside update at the start of the function
TouchCollection touchState = TouchPanel.GetState();

```

Then you can perform actions based off the touch locations:

```
//inside update
foreach (TouchLocation t in touchState)
{
    //do something with t.Position
}

```

Or, if you wanted to check for gestures and perform an action based off that:

```
//inside update
if(touchState.IsGestureAvailable()) {
    GestureSample gesture = touchState.ReadGesture();
    //do something with gesture
}

```

The `GestureSample` (doc) will hold information about position, deltas and gesture type. These values will help you decide what type of action to perform and how to perform it.

Try following a small tutorial like this one to get you started. The code is very similar to what I wrote:

```
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
    if ((tl.State == TouchLocationState.Pressed)
            || (tl.State == TouchLocationState.Moved))
    {

        // add sparkles based on the touch location
        sparkles.Add(new Sparkle(tl.Position.X,
                 tl.Position.Y, ttms));

    }
}

```

---
Tags: xna-4.0, monogame, touch, windows-phone-8
---


# Question
Title: When to detect and respond to collisions?
I've usually implemented collision detection like this in the past:

1. Move entity
2. Check if it collides with anything
3. Resolve the collision by moving it back

That's also the approach employed by most tutorials on the topic I've seen, so it seems popular. But isn't the following cleaner?

1. Calculate entity's velocity based on its acceleration
2. Check if it would collide with anything
3. Resolve the collision by adjusting its velocity
4. Move entity based on its velocity

The former approach has always been buggy for me, with objects getting stuck in walls or sometimes moving right through them.

One issue I see with the latter approach is with the time step. All of my entities have an `void update(int ticks)` method which updates their position. Now, I'd have to calculate the position twice: Once to anticipate a collision and once to actually move the object. Also, can I accurately resolve the collision by just updating the velocity?

# Answer
There are many ways to handle collisions in your game.

One *possible* solution is to revert to the position before the collision happened, like the first method you mentioned. I would advise against this solution. It gives a weird feeling when you are playing and prevents you from "sliding across a wall". I used to handle collisions like that. I wish I hadn't.

Instead, I would recommend doing it in a more "realistic" way. Depending on your game environment, you could use a physics engine if your game uses a lot of physics. I think this may be the most complete way to go. There are many engines out there depending on your programming language and framework. Find one that fits your needs and is well documented.

However, you can program it yourself if your game is simple enough and you want to do it yourself out of curiosity. If you are making a game where your environment is made up of squares (a grid, such as a platformer game or a top-down tower defense, etc.), then you can do it yourself. When a collision happens, push the entity across the shallow axis (in order to make the collision response less apparent). This way, you'll be able to move while walking into a wall, and you'll simply slide against it. It should feel natural. You can take a look at this article for a tutorial about it. You can find a lot of other resources online to do this as well.

The general algorithm for this method is the following:

1. Find how far the entity is pushed inside an object of the environment on each axis (by comparing their rectangles).
2. Find which is the shallow axis (`abs(x) < abs(y)` or the other way around).
3. Push against this axis to undo the collision
4. Adjust velocities if needed (this depends on your game, you could apply a bounce effect in a physics-based game, stop a jump in a platformer when you jump under a wall)

I wish you the best of luck to find a solution that fits your needs.

Happy coding!
> 0 votes

# Answer
The topic is too broad to benefit from a single answer on this site.. but some better things to do can be covered nonetheless:

* investigate continuous collision detection/simulation strategies
* use ray casts and/or shape casts to detect collisions AND the TOI (time-of-impact)
* once the time of impact is computed, it gives you the time the object will travel until it will collide with the first object in the scene. You can use this estimate to advance your simulation until you have a hit. From that hit you must compute a response and modify your velocity accordingly (apply impulses, reaction forces, friction or whatever your dynamics engine can add). *After* this impact, you are reduced to using whatever simulation time is left from the engine time-step. Use that remaining time to advance your simulation with *the updated* dynamics.

This strategy is simple and intuitive, but the details are math/physics heavy. Perhaps some simple introduction can be found here: http://www.wildbunny.co.uk/blog/2011/03/25/speculative-contacts-an-continuous-collision-engine-approach-part-1/

**UPDATE**: Richard Tonge of Nvidia PhysX has explained their solver implementation for collision handling (in parallel!) for multiple objects. It does answer and explains a lot of issues: http://www.essentialmath.com/GDC2012/Richard\_Tonge\_solvingRigidBodyContacts.pdf
> 2 votes

---
Tags: collision-detection, physics, collision-resolution
---


title: Grids and vertices

text:
# Question
Title: Grids and vertices
I have no idea what this is even called or even to start searching how to solve this problem. So figured I would post here for any information at all. Specially looking for already known solutions to this.

Say for example I have a grid - Aka one huge square which is easy to draw. If I punch holes in the grid how is it possible to find the biggest possible squares to fit within this grid. See the below picture:

Red is the punched out hole, and the squares is the squares that should be made.

As I said looking for any advice/solutions at all :)

# Answer
> 3 votes
First of all, you probably meant to subdivide into rectangles, not squares. The problem is generally not solvable with squares.

Now, if you want to split your region into rectangles given an arbitrary number of rectangular holes, then I have a strong feeling it's an NP-hard problem. Which means you probably don't want to solve the problem in the best possible manner, as long as you have a solution which is "good enough".

For example, for a single-hole shape the solution that you drawn in the picture looks to be optimal. You can similarly hand-draw the solutions to the cases when the hole is at the edge or in the corner.

Now, the simplest way to solve the multi-hole problem is the following:

1. Select one hole at random, and "solve" the tiling problem assuming that there are no other gaps.
2. Pick another hole. It belongs to one or more of the rectangles you constructed in step 1. So solve the tiling problem recursively for each of those rectangles.
3. Repeat steps 1 and 2 until all holes are accounted for.
4. If you want, as a final step you may want to see if any of the adjacent rectangles can be merged into a bigger rectangle.

See the illustration:

# Answer
> 0 votes
I don't know any c++ or opengl, but this is the basic concept you'd need:

x = minimum area you are calculating with

y = block

get area of all blocks

sequentially divide each block by x, like this (y/x, y2/x, y3/x, etc)

place the above in an array

Tell whatever's processing the code to print the largest number in the array

Done :)

---
Tags: c++, opengl, voxels, grid
---


# Question
Title: Scrambling word into least recognizable form
My goal is to present the player with a scrambled word that should be reordered back into the original form:

OELHL --\> HELLO

I want a scrambling algorithm that takes any given word(\>3or4 letters, may contain spaces) and turns it into the least recognizable form.

While randomly moving every letter around certainly works, I noticed that not all shuffles are equal, some are more recognizable than others. I am posting this question in case someone knows of a better algorithm (maybe based on linguistics) that ~~guarantees least recognizable form.

# Answer
> 26 votes
Wihle the plpuoar "Cmairbgde Uirenvtisy" sduty was lkiely a haox, trehe has been smoe resaerch itno tihs tpoic.

Tihs sduty sohws taht arpapent lteter szie pyals a rloe. The use of wpckelgraihs attmepts to debcrise the relationship beewten stes of letrets to undtrseand the pniot at wihch a wrod is undersootd.

So how to dlveeop tihs itno an aglorithm? I tnihk trehe are smoe baisc stspe:

1. Asisgn a szie vlaue to ecah leettr
2. For a gievn wdro:
    1. Rembmeer the szie vaule for ecah leettr posioitn.
    2. Raniomdze the letters wtih the folwoling resrtictions:
    3. Don't aollw the frist and lsat leettr to remian in tehir retpecsive potision
    4. Attempt to aiovd planicg lertets itno the "solt" of thier smae szie.

Tehre are otehr sttaregies you can emlpoy, thuogh I hvae no raseerch to bcak up the foollwing, jsut my tsoughth:

* Aptemtt to maxzmiie the Leveishtenn ditsance between the oiigrnal and modefiid wrod. Tihs colud maxiimze the diuficflty for reczgnioing the wrod. (Pehraps use Seeuqnce Alimngent)
* Reverse the odrer of the ltteers berofe scramilbng, tehn mvoe ecah ltteer jsut a few sapces form its onigiral position. (Mbyae slhgitly sclambred bacwkards wrod is mroe diffucilt?)

---

Need a translation?

---

While the popular "Cmabrigde Uinervtisy" study was likely a hoax, there has been some research into this topic.

This study shows that apparent letter size plays a role. The use of wickelgraphs attempts to describe the relationship between sets of letters to understand the point at which a word is understood.

So how to develop this into an algorithm? I think there are some basic steps:

1. Assign a size value to each letter
2. For a given word:
    1. Remember the size value for each letter position.
    2. Randomize the letters with the following restrictions:
    3. Don't allow the first and last letter to remain in their respective position
    4. Attempt to avoid placing letters into the "slot" of their same size.

There are other strategies you can employ, though I have no research to back up the following, just my thoughts:

* Attempt to maximize the Levenshtein distance between the original and modified word. This could maximize the difficulty for recognizing the word. (Perhaps use Sequence Alignment)
* Reverse the order of the letters before scrambling, then move each letter just a few spaces from its original position. (Maybe slightly scrambled backwards word is more difficult?)

# Answer
> 2 votes
This is not a universal solution but often if there is a word that is an anagram rather than a scramble this makes finding the original word harder. Once your brain is locked onto the original word it's hard to get that word out of your head.

i.e. decree -\> recede might be harder than ecdeer -\> recede.

One further point (though I'm not sure how to implement it) is to remove common pairs of letters. If an anagram has 'q' and 'u' in the answer, you want to separate them in the question. other examples might include 'th', 'ing' etc. Conversely if the letters 't' and 'h' are in the answer but not next each other, putting them together in the question makes it harder; your brain automatically thinks of words with 'th' in them.

---
Tags: game-design, algorithm
---


title: SpriteBatch memory leak

text:
# Question
Title: SpriteBatch memory leak
I have a strange problem with XNA 4. I'm constructing a `SpriteBatch` using `this.spriteBatch = new SpriteBatch( GraphicsDevice );`. This leads to a memory leak up to 600 MB memory consumption.

This problem didn't exist two days ago.

I have a static class called `Resources`:

```
public static GraphicsDeviceManager gdm;

```

This gets set in the `Game`-constructor

```
public class Game : Microsoft.Xna.Framework.Game {
    public Game() {
        Resources.gdm = new GraphicsDeviceManager( this );
        Content.RootDirectory = "Content";
    }
}

```

In the `Initialize`-Method I'm creating a SpriteBatch in the `Resources`

```
protected override void Initialize() {
    base.Initialize();
    Resources.Game = this;
    Resources.spriteBatch = new SpriteBatch( GraphicsDevice );
}

```

At the point `Resources.spriteBatch = new SpriteBatch( GraphicsDevice );` it allocates up to 600 MB memory.

Why is XNA allocating so much after I created a `SpriteBatch`? How can I fix it? (It worked two days ago and I didn't change anything that could cause this problem.)

# Answer
> 1 votes
It's not the fault of `SpriteBatch`. It's much more likely to be the fault of your `Resources` object. By the way, keeping track of resources is the job of the `Game` class. I would be skeptical that you have good reason to also assign a `GraphicsDevice` into your custom object. Afterall, `Game` already has one, and it ought to be a singleton.

Do you call `Game.Initialize()` in your `Resources` object? I once had similar symptoms because I called `base.Initialize();` in my game's `LoadContent` method. (Infinite allocations until stack overflow.) You might try stepping into your code from `Main` by simply hitting F11. See if the execution does anything that it shouldn't be doing, and see if it is doing it over and over and over.

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


# Question
Title: Computing uv coordinates on a sphere approximated from an octahedron
Right now I'm texturing the octahedron with the formular from wikipedia(Finding UV on a sphere): UV Coordinates Wikipedia

That unfortunately leads to heavy distortion right at the beginning, which of course leads to a lot of distortion when splitting up the triangles when approximating it to a sphere.

The upper and lower triangles are okay, the left and right ones are distorted. Now I'm looking for different formulars to calculate the uv's. Are there any other easy formulars? Or would another approach be much more complicated?

# Answer
The Wikipedia entry you cite is correct - your image shows the characteristic pattern (the stripes) that indicates one of your calculations that is supposed to vary isn't, it's remaining constant - (the human mapping analog to this is the notion many people have that Greenland is the size of a continent, but that's another issue :-) )

Without seeing your code it's difficult to guess the exact error, but my guess is that you may not have paid attention to the fact that d hat is a unit vector. Try this and see if it helps

1) compute the center of your approximation of a sphere 2) For each point that is a vertex of your approximation, compute |TheCenter - YourVertex|, i.e. subtract the vertex from the center and normalize the result - this gives you the unit vector you need 3) Use the unit vector x,y, and z coordinates in the equation you got from Wikipedia

Also note the comment about the sphere's poles being on the y axis - if this isn't what you want you will still get a uniform texture mapping, it just may not be oriented the way you want it to be

You should work at making sure you understand this before you move on to more complex UV generation - this is one of the simplest uv problems, and more complex ones can really be furballs :-)
> 1 votes

---
Tags: textures, terrain, uv-mapping, planet
---


# Question
Title: XNA SpriteBatch.Draw with rotation, scaling and origin?
I use a 1x1 pixel 2d texture as source for `SpriteBatch.Draw`. The texture is scaled and rotated around an origin. The left image is only scaling. The right one scaling + rotation around the origin at the bottom center. I need the right image as result. i.e. scaled to 5x10 and rotated around 2.5x10

The problem is with the 1x1 texture the draw starts to act strange if the origin parameter is outside the source texture. And as long as the origin is limited to a max of 1x1 its not possible to rotate around the bottom center of the scaled texture.

Why does the origin behave strangely if it is outside the source texture? With strange I mean the texture moves much more then the origin value set. i.e. if its origin x=10 the texture moves much more then 10 pixels.

# Answer
I think you are misinterpretting the result of setting the origin to `(0.5f, 1)`. I did the same thing, and I got the expected results. Here's a modified version of the code I ran at this answer:

```
Color[] colors = new Color[] { Color.White };
texture = new Texture2D(GraphicsDevice, 1, 1);
texture.SetData<Color>(colors);

spriteBatch.Draw(texture, new Rectangle(100, 50, 100, 100), null, Color.Green);
spriteBatch.Draw(texture, new Rectangle(100, 225, 100, 100), null, Color.Yellow, 0, new Vector2(0, 0), SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Rectangle(100, 400, 100, 100), null, Color.Pink, 0, new Vector2(0.5f, 1f), SpriteEffects.None, 0);

spriteBatch.Draw(texture, new Rectangle(400, 50, 100, 100), null, Color.Red, MathHelper.PiOver4, Vector2.Zero, SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Rectangle(400, 225, 100, 100), null, Color.Orange, MathHelper.PiOver4, new Vector2(0, 0), SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Rectangle(400, 400, 100, 100), null, Color.Blue, MathHelper.PiOver4, new Vector2(0.5f, 1f), SpriteEffects.None, 0);

```

And as you can see, the blue square rotates around the bottom-center, exactly as intended. The other squares rotate around (0,0).
> 5 votes

# Answer
Set origin in relation to source rectangle. If your rectangle is 0:0:1:1, set 0.5:1 origin (for bottom center).
> 1 votes

# Answer
I think you should divide origin by the scale...

because spritebatch apply origin translation before the scale operation, so you have to invert the scale operation to avoid origin being scaled
> 1 votes

---
Tags: xna, textures, rotation, spritebatch
---


title: Developing games in Go?

text:
# Question
Title: Developing games in Go?
Google's new Go language is still in its infancy, and it has yet to find widespread real-world use or support. Even so, it seems like a promising experiment, and I wonder if it could have a future in game development. I haven't been able to find much game-specific discussion of Go elsewhere, and figured a CW discussion may be appropriate.

Some thoughts:

* According to golang.org, Go programs "run nearly as quickly as comparable C or C++ code"--quick enough?
* Is Go's garbage collection well suited for games?
* How much mental re-tooling is necessary to create games in the land of concurrent goroutines?
* Go is frequently called a "systems"-level language, with server software given as an example. It's hard not to think of multiplayer game servers when hearing this.

Your thoughts?

# Answer
> 36 votes
My take on your questions:

* The language is plenty quick enough. The slower Java language is used for game development. Even Python (pygame) is used for game development, and it's significantly slower than Java. It all depends on the type of game and how processor-intensive it is.
* Garbage collection in general is not very good for games. However, Go has a particularly bad garbage collection system (mark-and-sweep) which stops the world while it cleans up stuff. It'll be difficult to cope with and will cause something of a stop-and-go framerate.
* A decent amount of mental retooling is necessary to create games with goroutines. Graphics and logic can't be concurrent in the traditional sense; but at a smaller level, parts of the logic are great candidates for concurrent goroutines (e.g. parallel processing of AI decisions, particle systems, etc.)
* A multiplayer game server may indeed be a great candidate for the Go language.

In my opinion, if you have a strong enough urge to try writing games with a language, go for it. Obviously if you're considering it then you have a passion to do so, and why not follow that passion instead of forcing yourself to conform to the norm? I could say a lot more but I've already said a lot in my answer the question, "Is Ruby a suitable language for game development?"

# Answer
> 18 votes
I've written a small engine in Go for OSX (using OpenGl for the graphics window). I have some experience with C++ game engines (http://morganjeff.weebly.com/) and decided to try out Go after reading about some of the features it offers.

As of the Go 1.1 release go has support for most of the features I needed to write a game engine (really a game core as an engine suggests editors and what not) including:

* Member function binding (for the messaging system)
* Reflection is built-in (useful for serialization, external tool support, etc)
* Interfaces (for implement polymorphic behavior for systems, components, etc)

Some of the benefits to using Go (for a large project):

* Testing is built into the language (this includes benchmark tests and some assertions)
* Examples are easy to add to the language (and they are compiled for correctness)
* Architecture specific code is easy to add (through file naming conventions)
* Profiling is built in to the language
* built-in versioning of imports (allows for adding large binaries to a separate repository from the source, while keeping it versioned and up to date)

Some benefits of using Go in general:

* Easy to refactor code
* Go supports threading (unlike C++ which layered it on top)
* super fast compilation speed reduces the need for scripting language support
* static typing system (interfaces are satisfied via duck typing aka implicitly)
* multiple return values, named parameters, tagged struct attributes
* great built-in tools and documentation
* managed language

Some downsides of using Go:

* No macros or templates
* Doesn't have the library support of more mature languages
* managed language (listed twice on purpose)
* NO IDE

There are ways to get raw memory in go (import "unsafe") and I'll link an article that shows how a go program can be profiled for memory and speed. All in all, Go's claim that it's a modern C seems very true. I think it's "smartly" designed (for a lot more reasons than I mentioned) and, more importantly, it's well documented. An engine designed in Go is going to be a little different than an engine designed in C++ (something I'm still getting used to), but the Go engine solves a lot of problems that aren't really solved in C++ (namely parallelism, the complexity of C++s language, and the mis-use of inheritance).

Here's the article I promised: http://blog.golang.org/2011/06/profiling-go-programs.html

-Jeff

# Answer
> 4 votes
Something else to think about is that since Go is still relatively new, there may not be bindings for a lot of the common libraries used in game development yet.

# Answer
> 0 votes
Do not use Go to develop a game, it will just be an albatross around your neck. The toolchain for game development extends so much deeper than just the language that you write things in that you're going to find obstacles at every turn that just won't be there if you just go with something established.

Don't get me wrong, I love playing with new languages, but if you are trying to make games pick a language that has a community and support and you will be much better off.

---
Tags: go
---


# Question
Title: Matrix represents same rotation with different euler angles
I have Transform component storing it's rotation as Quaternion. Transform has set/getEulerAngles (rotation order oy, ox, oz). I want to rotate object in any direction but while testing I get jumping(glitch) objects stop rotating at specific angles.

Euler angles in problem frames:

**1)** *oy* 0 *ox* -90 *oz* 0 - previous frame.

**2)** *oy* 180 *ox* -90 *oz* 180 - next frame after incrementing angle of the object.

my increment looks like:

```
tr->setEulerAngles(tr->eulerAngles()+Vector3(5,0,0));//rotate around ox by 5 degrees

```

visually this rotations are **equal**, but when I get angles **2)** from quaternion and increment them it starts rotating in oposite direction, next frame rotation is again as **1)**, so there is infinite loop at this rotation (some kind of black hole;-)). What can it be? Something wrong with math?

# Answer
> 0 votes
Gimbal lock is the answer, avoid using euler angles even converting to and from quaternion, use multiplication by quaternion created from angle axis.

Unity3d has same problem when rotating around ox axis:

```
transform.eulerAngles += new Vector3(5,0,0); //problem

```

---
Tags: 3d, rotation, mathematics
---


title: 2D Water Shader

text:
# Question
Title: 2D Water Shader
I am trying to build a 2D Water shader and I am using Unity but the plateform isn't a problem.
Here is an example of what I am trying to reproduce :
Limbo water shader
Are there any good tutorial or whitepaper about creating such effect blur and displacement ? I am not talking about waves or something but only the depth of the water.
Is it a Camera shader or an object shader ?

Thanks a lot !

# Answer
> 3 votes
Except the spluttering / water jets (seems to be done with particles) it looks like a displacement shader.

Check out this http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter19.html

It is in 3D but the theory behind it should provide helpful if it is that kind of water effect you look for.

# Answer
> 0 votes
I have Unity Pro. I saw that the best way to achieve such effect is to use Grabpass in the shader. But there are two problems with this system :

* It seems that Grabpass is quite heavy for mobile as said here Using Grabpass & IOS/Android devices . But as I am learning shader, I don't know any other system to create refraction.
* There is an issue with foreground objects, they are refracted too. There is a solution here GPU Gems - Refractions posted by Valmond.

Another interesting link : Unite 11 - Shadowgun The fluid part is at about 30:00.

---
Tags: unity, shaders, water
---


title: Why is my label not updating properly?

text:
# Question
Title: Why is my label not updating properly?
I am using the following code to handle experience points gains:

```
reqXP = (Level ^ 2 + Level + 3) * 4

    If (currXP >= reqXP) Then

        Level = Level + 1
        expPoints = expPoints + 3

        excessXP = currXP - reqXP

        currXP = excessXP

        excessXP = 0

    End If

lbl_XP.Text = "Experience : " & currXP & " / " & reqXP

```

However, whenever I level up, it won't update the `reqExp` Label until I get my next batch of experience points.

What do I need to change to make this work?

# Answer
Just add the "reqXP = (Level ^ 2 + Level + 3) * 4" if the player levels up. Actually you should only calculate it once the player levels up and keep the variable instead of calculating it every frame (if that's what you are doing)
> 2 votes

---
Tags: vb.net
---


# Question
Title: Why does exporting to FBX in 3dmax loses simulated animation
I made a cloth simulation (wind blowing a cloth). When I export it to FXB and the animation box is ticked on export menu it seems ok (no error in longs). When I reload it to Unity. or 3DMAX again. The wind animation is lost. How can I fix that?

Thanks

# Answer
> 1 votes
The wind is calculated differently differing on the engine. So unless it is a raw, baked animation you will have to set it up again inside of Unity using the wind settings provided by Unity engine. As for the 3D Studio Max. I have no idea what can be going on there.

# Answer
> 0 votes
If ya wanna keep the wind sim you need to bake it http://docs.autodesk.com/3DSMAX/15/ENU/3ds-Max-Help/index.html?url=files/GUID-F122A886-941D-4E40-822C-F57D90049BD5.htm,topicNumber=d30e269398

otherwise use unity to re-simulate it. Hope this helps

# Answer
> 0 votes
If you read the conversation, you'll see that my helpers were right. But to handle the problem easily we bought an extension to Unity, which did what we needed. I'm sure that the problem can also be solved with the following methods:

* Workaround: Bone animation (Remake the whole thing with bones)
* Simulation in Unity: Use cloth simulation in Unity with Unity forces.

Or buy the stuff we did (Megafiers)... as we are lazy.

---
Tags: animation, 3dsmax, simulations, export
---


# Question
Title: make a sphere rolling on a roulette mesh stop at predetermined place
I have a roulette and a ball(sphere) placed on it. When the game begins the roulette spins. The spinning of the roulette and gravitational forces on the ball makes it roll along the 3d roulette mesh.

Now , in this roulette game of mine I have slots from 00 to 36. I want to make sure that after the roulette stops spinning the ball comes and stops rolling at my predetermined slot.

For example : if i set the target slot as 25 in the game, every time the roulette spins, the ball moves realistically along with it BUT comes slowly to a stop at slot no: 25.

I have tried 'slerp' the ball to its target position, but the realism is lost. The ball moves **through** the mesh. Which i don't want. I want the ball to roll like in real life.

# Answer
Script one (or two or three) bouncing paths for the ball to follow. Adjust the rotation of your wheel model to cause the correct slot to land underneath the ball's final destination.

*A bouncing path*: construct complex animations made from many small movements of the ball over time, such that it appears to be natural physical motion around the structure of the wheel. Eventually, that animation will end with the ball settling into a slot and rotating at the same speed as the wheel. That location does not need to be changed, because the wheel can be rotated such that the correct slot is underneath the ball. One method for scripting these paths is to follow keyframes based on a spline.
> 11 votes

# Answer
Calculate the path in background, and then change the numbers when you render it.

Calculate a path based on random parameters, but do this invisible to the player. You now know on which field the ball will land. Then you render it visible, but before you do that you rotate the texture of the roulette wheel so that the field where the ball will land shows the number you want.
> 3 votes

---
Tags: mathematics, ai, simulations
---


# Question
Title: Get distance between the edge of screen and a moving sprite
How to get the distance between the edge of the screen and a vector moving sprite? I want to get the distance between my moving sprite and the edge of the screen so that when my sprite touches the edge it will bounce of. I am using LIBGDX to develop a game. It uses java language.

# Answer
> 1 votes
This can easily be done just with the bounds of the screen and the position of the sprite. The screen bounds can be stored in two variables, `screenMin` and `screenMax`, where `screenMin` contains the minimum X position of the screen and the minimum Y position of the screen, `screenMax` does likewise with the maximums.

```
leftDistance = spritePos.x - screenMin.x;
rightDistance = screenMax.x - spritePos.x;
topDistance = spritePos.y - screenMin.y;
bottomDistance = screenMax.y - spritePos.y;

```

So you can find out if it's touching an edge like this (this is not copy/paste code, find the appropriate methods/members for your environment):

```
if(Math.min(leftDistance,rightDistance) < sprite.width/2)
    //sprite is touching left or right side

if(Math.min(topDistance,bottomDistance) < sprite.height/2)
    //sprite is touching top or bottom

```

---
Tags: java, game-design, game-mechanics, libgdx, game-loop
---


# Question
Title: How to draw a circle with WebGL using GL_POINTS
I'm trying to draw a circle using simple vertices points and a big gl\_PointSize value. I found this example and try to reproduce it on WebGL with no success.

# Answer
> 4 votes
This is just using regular old sine and cosine to step around the circumference of a circle and place points. You just need to know the center of the circle, the radius and how many points you want. The following pseudo code will output a set of points that make up the positions of dots you need to make a circle of points:

```
circleXY(Vector3f center, float radius, int dots) {
    float stepSize = ((2*Math.PI)/dots);
    for (float d = 0; d <= (2*Math.PI)-stepSize; d += stepSize) {
      addPoint(((sin(d) * radius) + center.x),
                (cos(d) * radius) + center.y));
    }
    return result;
}

```

You will have to modify it to fit your language and APIs. But, if you know how to draw a point, you can easily utilize this to know where to draw them.

---
Tags: glsl, webgl
---


# Question
Title: How to animate a destruction of a model?
I have a model (see image) and I am trying to animate a destruction.

But it doesn't seem possible, since XNA is using only bones to animate. So my question is:

**Which workflow should I use, to animate 4 independent objects (being one big model), which lie on top of each other?**

Regarding this model:

# Answer
Each object should have its own bone. Each bone should be unconnected to the others and able to move freely. This allows you to animate each bone, with position and rotation, while still keeping the model as one. Each bone is really just a matrix to apply to the vertices under it's control. It's simple to imagine applying a translation and rotation to each group of vertices that make up each portion of the complete object above. Allowing them to separate and move independently of each other.

You should use the 3D modeling/animation program you're most familiar with. If your program allows for simulations with physics, you can utilize it to physically simulate the collapse. Alternatively, you can do the animation by hand, using key frames. Animating by hand will be challenging, but should be simple enough with the right approach. I would start by moving the top and having the near bottom one collapse, moving the other parts to follow. But, really, that's an artistic question and there are many different ways to do it.
> 4 votes

---
Tags: xna, animation
---


# Question
Title: Tips on building a real time multi player web platform + framework and/or tookit
I'm trying to develop a multi player game web app which basically should be able to achieve the following goals:

* Provide a game engine + framework/toolkit to let third party corporation integrate their own developed games.
* Games must run realtime and multiplayer.

So the idea is to develop some kind of framework or toolkit to easily accomplish above goals.

As long as I don't want to reinvent the wheel and I need to validate each client action, and while following the premises below, I would like to know your opinion:

* Web app is going to be developed using PHP language.
* Clients connections are going to be managed through socket.io.js
* Server validations will run on Node.js
* I need to adopt a game engine that can run on top in order to let third party develop their custom games, which one?

As I'm no expert I'm looking some kind of advice or feedback based on your experience and also to let me know if I'm going in the right direction.

# Answer
> 1 votes
Currently I've been developing a game, which is an implementation of my application state management system - similar to how a game would be developed in C++.

Basically. The entire game is run through index.php - and the Program class sets and changes the program state. Each state is its own abstract class with two primary functions.

```
      /* State Keys: List of States */
      class States
      {
          const MyState = 0;
      }

      /* A custom program state. */
      class MyState extends State
      {
          public function Permissions()
          {
                global $User;

                /* User Required to be logged in to view state. */
                if ( !$User->LoggedIn ) return false;

                /* Permissions Okay! */
                return true;
          }

          public function Run()
          {
                printf( "MyState is Running." );
          }
      } $MyState = new MyState;

      /* Add State to Stack - assigned to Key States::MyState */
      /* Now this state can be called by... */
      /* $Program->ChangeState( States::MyState ); */
      $Program->AddState( States::MyState, $MyState );

```

Now the program sets the DefaultActiveState to something like a login page, then login calls...

```
      /* After login... */
      $Program->ChangeState( States::MyState );

```

Now when index.php is loaded, the program determines what state to run by bassing ActiveState off of a session - this way we don't lose what state is currently supposed to be running.

```
      /* index.php : Main Program */
      include "template header";

      /* This function... */
      $Program->Run();

      /* ... Calls $Program[$_SESSION["ActiveStateKey"]]->Run(); */

      include "template footer";

```

When ChangeState is called, it simply sets the ActiveState function and then redirects page (reloads index) and Runs ActiveState-\>Permissions, and if returns true, runs ActiveState-\>Run.

Just an idea.

---
Tags: javascript, browser-based-games, node.js, websocket
---


# Question
Title: How do "community patches" for commercial games work?
For a lot of games, mostly role-playing games (Gothic 3, Oblivion, Skyrim, Titan Quest to name a few), there exist community patches. So, patches that are made by the communities, not by the developers.

How does this work? Most commercial games are not open source.

**How can someone without source code access provide a patch?**

# Answer
A "community patch" could mean one of two things (or some combination thereof):

* A mod of the game, using the games official or unofficial modding tools, that addresses bugs and balance issues as opposed to introducing new functionality, art or content like most mods do. For example, consider the unofficial patches to the Baldur's Gate games.
* An official patch issued by the developer, that content of which has been sourced from the community. This is rarer, and I've only ever really seen it applied in the context of community localization projects.

You don't need the source code to patch a game; game's that are reasonably well-engineered tend to be driven by data that is stored independently of the source, which makes it much easier to patch. Even if a game did not keep source and data distinct, or did require a code patch, you could also accomplish this by reverse-engineering the compiled executable and building a patch for that.
> 7 votes

# Answer
The easiest way for the developers (who tend to make games for commercial purpose) to make community patches is to give the players an SDK/API or whatever has been created strictly for the game. Of course a normal player will not have access to the 3D Studio Max, but the developer can provide something else, like the 3d item prospector, 3d world builder etc.

Bethesda Softworks has provided the Skyrim community with the Skyrim Creation Kit which is a combinatin of all tools that were used to assamble the game, by level designers, game designers.

http://www.creationkit.com/

It has complete solutions for the AI system along with a complex NPC talk-action dialogue system. That way the players can do anything to the game, no source code is needed. As the matter of fact the Skyrim uses Havok Physics engine, and I am sure that distributing the expensive Havok Engine soucecode would make the Intel corporation rather unhappy.

The community creates various patches that are shared over the net. Even though the company has no money from the additional player-made patches, it encourages players who play on a pirate game version, to buy one because it gives you access to the community mod patches along with the Creation Kit. Bethesda used some of the ideas/solutions provided by players in mod packages upon creation of the official game patch, which was free. And later they have used some of the mods in creating the official Skyrim expansions such as the "Dawnguard" or "Dragonborn" which cost about $15 each.

It doesn't have to be opensource to encourage players to create using the SDK (Software Development Kit) you provide. Thus delivering source code isn't mandatory to create the game fully "modable". The best proof of that is Skyrim - 4+ large official patches and 15,000+ community made patches with 16+ patch combo's with major bug fixes done by enthusiasts.
> 1 votes

---
Tags: patching, community-management
---


# Question
Title: What are some strategies for handling a zoomed out grid of sprites?
I'm writing a grid-based 2D game in Unity3D that would ideally use grid sizes of around 200x200 or so, with multiple zoom levels, including all the way out. When I tried render a 200x200 grid at the most zoomed-out level where everything is visible, Unity crapped out saying that there were too many vertices to attempt to draw. This makes sense, as it's trying to render 40,000 sprites.

I was wondering, how do games like Dwarf Fortress and OpenTTD manage so many sprites at once on the screen when the map is zoomed out all the way? Are there any general strategies for handling the rendering of a large number of sprites such as this?

# Answer
> 2 votes
I don't know about OpenTTD, but I'm pretty certain Dwarf Fortress is strictly 2D and doesn't utilize the now common method of drawing sprites to quads.

Granted, the following solution is Unity Pro only, but I can't think of a good solution for the free version.

Essentially, as you zoomed out, you would break up the rendering of the map into chunks and render each chunk to a texture. Then take those textures and render them to the screen. Each chunk would wind up being a single quad, and so you'd be fine on the vertex issue.

---
Tags: unity
---


title: Simplex noise 3d map generation

text:
# Question
Title: Simplex noise 3d map generation
I've just started learning 3d stuff and want to make minecraft clone, cause cubes are easy ( I hope ) :) Arleady wrote chunk creation, menagement and displaying and want to generate nice terrain, but I dont know how. I found simplex noise and perlin noise c++ ports, but I dont know how to use these functions to generate heightmap. I tried it but terrain is mostly "jumpy". I want it more smooth/real.

Should I use 2d or 3d version and what octaves, persistance, and scale settings should I use? Should x y z be my array index values or time or what? I just need explaination how to use these noise fuction to generate map. I know there's a lot of stuff about this, but I really run through tons of it and still don't get it, so any explaination or links are welcome. Thanks in advance!

# Answer
Start here: Really nice noise library because using noise in a meaningful way takes a little work.

Most of your "what octaves, persistence... etc..." questions are answered by trying values and sticking with what works for you, there is no universal truth otherwise all maps in all games would look the same. In fact, the best way to get up to speed is to build a quick tool that lets you change these values and generate new data dynamically so you can see what these different numbers do to real data.

The basic concept is that you have a variety of noise types at your disposal and the art of creating usable maps comes from layering these noises much like a photoshop artist layers graphics to get the final picture.
> 1 votes

---
Tags: 3d, minecraft-modding, heightmap, perlin-noise
---


# Question
Title: Android game loop's effect on cpu/battery usage - unexpected results
I will try to keep this question as concise and as readable as I can.

I recently came across an odd problem with my Android game that I'm developing.

It's an openGL ES 2.0 game and initially I was using RENDERMODE\_CONTINUOUSLY, my gameloop was running on the OpenGL provided rendering thread and I was basically limiting the logic updates (to say, 30 times per second), while letting the rendering run as fast as the device could handle.

**Please note that I'm not using thread.sleep() and do not want to as I've read various articles advising against it**

Everything works well, but when I ran the game on an old Galaxy Ace phone it was rendering at 85+ Frames Per Second which got me thinking that it could be using more battery than it needed to (because it was rendering frames which didn't need to be rendered as there were no logic updates in-between them).

So what I did was this:

I set RENDERMODE\_WHEN\_DIRTY, started another thread myself, put my game loop into that thread and from this loop, called update() (For logic updates) and requestRender() (for drawing). I altered the gameloop so that it would only render when there was an update.

Now, the way it stands, If I limit my loop to say, 30 ticks per seconds, then all is good, both rendering and logic run at a smooth 30 tics per seconds. If things get too much and the device can't handle the rendering, and the frame rate drops (lets say, to 12FPS), then the logic will carry on at 30 times per second which is exactly what I'm after.

Howevever, I've used the CPU Meter in Jellybean and it would appear that the first option (2 threads, rendering flat out) is more CPU (and therefore, I assume battery) efficient that the 2nd method (3 threads, but with rendering limited).

I'm trying to figure out why this would be?

Please note that I can't test the CPU usage on the Galaxy Ace phone as it doesn't run jelly bean, but certainly on my Nexus 10 tablet, the CPU usage is more when using the 3 threaded approach.

I understand that now, my loop still 'loops', even when it has no updates or rendering to do (never sleeping), but this was the case in the first loop too (well, when it had no updates, it would carry on rendering regardless).

So what gives here?

**Note:** I haven't posted code as it's not really relevant to the question. But if you want to see the loop, please ask and I will post - thanks

With OpenGL, am I best to just leave the device to render as fast as it can? That certainly seems to be the way it's been set up (at least when using RENDERMODE\_CONTINUOUSLY)

# Answer
GLES rendering has a CPU cost and a GPU cost. Rendering less often should reduce both of these. I don't believe the CPU meter can show you the GPU cost, and I'm not sure why it would indicate that your CPU usage is greater.

Maybe the (presumably trivial) activity of the third thread is being exaggerated in the accounting? You can get a simple per-thread breakdown with `adb shell ps -x -t`; the "u" number indicates time spent in user-space, the "s" number is time spent in the kernel.

The systrace tool can show you exactly what's happening on every CPU core, but it's a bit tricky to use and interpret, and you need a recent, rooted device to get some of the interesting bits.

Note the actual battery life will depend on various other factors. For example, if the CPU and GPU aren't all that busy, they can drop to a lower clock frequency.
> 2 votes

---
Tags: android, game-loop, opengl-es2, frame-rate, efficiency
---


# Question
Title: How would you program sprite movement in a 2-D ariel view rpg game?
I'm relatively new to programming and I have recently programmed an RPG game in java. Any tips on character movement with animations? I would like it to be similar to those of other rpg games such as Pokemon, Final Fantasy, ChronoTrigger etc. As seen in this demo, the current movement system that I have is pretty choppy and has no animation.

# Answer
> 0 votes
If you developed the demo in the video on your own you should be able to understand what is needed for the movement animations. You need to post examples of attempts at coding the movement.

In simple terms;

You need to capture the movement event(s), you then need to specify which animation(s) to use in those events.

---
Tags: java, 2d, animation, sprites, rpg
---


# Question
Title: Designing score system: Combos, chains, multipliers and bonuses
I am making a breakout-clone, I not want only want it to feel "arcade" for home users, but it will have a arcade version (although probably noone will buy, and I will only use the machine to amuse other people...), this make scoring, and high-scores a important part of it, it has no multiplayer, with the community existing around how to score higher and higher scores.

Being a breakout game, if the score is just linear, everyone that "finish" the game, will attain the same maximum score... Obviously this is undesirable, specially because the game DOES have a end, you cannot play it forever until you lose...

So, how to design some decent score system? Currently I added a multiplier, and it increases when you kill several blocks fast, but this has the unintended side effect of creating absurdly high scores near the end of the game when you are highly powerful (yes, my game is not only about batting the ball :P) and can clear a whole bunch of blocks at once...

To make it more clear, you have 5 frames to kill another block and increase the multiplier, on the start of the game, only batting the ball, this only happen when you manage to get the ball stuck behind the wall (something that is desirable to reward... several players plainly have a CRAVING to attempt that), and if you are a MASTER breakout player, you can score on the first five levels something like 100k points... Yet, on one of the late levels, if you use in a mediocre way (not even good way) the powers, you can easily rack-up 2 million points in a single level (and no, my game does not have points padded with 0! Some stuff DO reward you with 1 point, or 10... It is just the multiplier increase of 5 frame kill that skyrocket...)

I want to add more mechanics, fix this one, and make lots of stuff rewardable, stuff that make the screen shine, blink, show pretty stuff and make the player go "WOW, DID YOU SEE THAT?" and tap his friend in the shoulder, and then when he make it on purpose he screams: "HAHAAAA, I AM AWESOME AND YOU SUCK!!! DO IT TOO!! I DARE YOU!!!"

Note: Although the theme here is breakout, no problem in crossing genres, shmups are particularly good in this area, Radiant Silvergun for example was plainly great... But of course, it need to still be applicable on a breakout :)

Meta question: How I create tags? If I really can't, can a moderator put some decent tags for me? Like scoring, or chain-system, or stuff like that? Otherwise we will end with thousands of stuff with the same tags: design, writing and C++... or generic stuff like that.

# Answer
> 3 votes
One thing you can do is scale the multiplier non-linearly, according to a logarithmic scale of some sort. Let's see every block you kill within a certain time limit raises the multiplayer by one. That leads to the escalation problem you are talking about if you allow it to go too high, and if you put an absolute cap it sets a theoretical skill cap.

Instead you can set it so raising it to x2 takes one block, raising it from x2 to x3 takes TWO blocks, and raising it from x3 to x4 takes THREE blocks. Or you can modify the equation whenever you want. The basic idea is that the higher your multiplier, the harder it is to raise it. This has the practical effect of capping out a score multiplier without necessarily putting a hard cap.

You also want to have various likely events that will drop a multiplier. For instance in many vertical shooters using a Bomb will reset or lower your current multiplier, as would dying. Also if you go long enough between bounces it could start to fall. This allows a high score to be two factors: rather they do enough good events to raise the combo, and rather they can keep it going by not failing at various bad events.

# Answer
> 1 votes
I've always rather liked bowling's score system. With bowling, if you get a spare, you get the full ten points for that frame, *plus* the number of pins you knock down on your next ball. If you get a strike, you get the full ten points, *plus* the number of pins you knock down on your next *two* balls. While a full bowling set is 100 pins, the ultimate top score ends up being 300. Despite that, the score going from zero to 300 is surprisingly flat - a novice can reach 100 without too much practice, a skilled player can reach 200, and even the best experts have trouble hitting 300 consistently.

I don't know what the "frame" equivalent would be with your game, but the basic idea of using additive bonuses rather than multiplicative bonuses might be the right way to go.

(Apologies for anyone horrified by my bowling terminology, I don't know the game particularly well.)

# Answer
> 1 votes
If by 5 frames you *actually* mean 5 render/logic frames , I'd be inclined to say that's way too fast for a human player to understand. My first reflex would be to slow down the rate at which the multiplier increases.

If you want people to try to exploit your scoring bonus mechanic, you first need to make sure the player will understand perfectly how it works. You also need to show the player what's happening: display somewhere the current multiplier and possibly his state (increased, cooling down, lost).

To add more mechanics, I believe you first need to be sure the core multiplier mechanic is understood by most. Playtest your game and ask questions like "Can you explain to me how the score for one killed block is calculated?" Then if the multiplier is mentioned, you can follow up with "How do you think this multiplier behaves?". If you don't get the answer you expected to the first question, your mechanic isn't properly explained and needs more sign/feedback work to be clear. Iterate this playtest scheme if possible.

Once you get 80% of respondents to give you an good depiction of your system, you can go on developing additional mechanics to give depth to the scoring system. A very good reference on this is Peggle. Their scoring system is quite complex but easy to grasp. Give that game a look for concrete pointers.

Hope it helps!

# Answer
> 0 votes
Simply limit the multiplier to a max of 5x or 10x. If that strikes you as inelegant, you can do something like:

* Hit 1 block for 2x multiplier
* Hit 2 more blocks for 3x multiplier
* Hit 3 more blocks for 4x multiplier

And so on.

# Answer
> 0 votes
I designed a Columns variant for the Atari 2600 called Strat-O-Gems; the player drops groups of three gems in such fashion as to cause chains of three or more gems vertically, horizontally, or diagonally. This will award a score value which depends upon the number of gems destroyed, multiplied by the level (max 15). When those gems disappear, other gems will fall into the void; if that creates more chains of three or more gems, those will score based upon the number of gems destroyed there, multiplied by twice the level. If that triggers more chains, those will be scored at 3x the level, etc. up to a maximum of 99x (which I've never come close to hitting except when I hard-coded the pattern of gems on the board to test it). As the chains are produced, the screen shows the value of the current chain as (base X multiplier) as well as the total value of all chains triggered by the last triplet that was dropped. Thus, a player can have some understanding of where his score is actually coming from.

Additionally, if an AtariVox or MemCard is plugged into the second joystick port, the game can reward really impressive combos by showing an instant replay (a function I've sometimes wished for--but seldom seen--on other games of the genre such as Chuzzle); it can also store the three best combos of all time and show them during attract mode. Such features could add considerable enjoyment by letting the player know what he did to suddenly net a huge number of points. If I was able to implement such a feature on a system with a whopping 128 bytes of RAM and 256 bytes of EEPROM, it should be possible to implement such features on newer systems as well.

---
Tags: game-design, scoring
---


title: Isometric Map Rendering Incorrectly

text:
# Question
Title: Isometric Map Rendering Incorrectly
I've currently been trying my hand at Isometric map rendering via the tutorial over at XNA resources; http://www.xnaresources.com/default.asp?page=Tutorial:TileEngineSeries:4

However, unfortuanely the map isn't quite rendering as you can see in this photo of my output; https://i.stack.imgur.com/9Gelo.png

I've not too sure where i'm going wrong, here below is my rendering code;

```
        protected override void Draw (GameTime gameTime)

    {

        graphics.GraphicsDevice.Clear (Color.CornflowerBlue);

        //Set Up Screen Geo, see how many times we can display on the screen

        int tileOnX = ((int)scroll.X / tileWidth);

        int tileOnScreenX = (((tileOnX * tileWidth) + graphics.PreferredBackBufferWidth) / stepX) + 1;

        int tileOnY = ((int)scroll.Y / tileHeight);

        int tileOnScreenY = (((tileOnY * tileHeight) + graphics.PreferredBackBufferHeight) / stepY) + 1;

        if (tileOnScreenX > isoMap.getWidth())

            tileOnScreenX = isoMap.getWidth();

        if (tileOnScreenY > isoMap.getHeight ())

            tileOnScreenY = isoMap.getHeight ();

        //Set up Depth

        float maxdepth = ((isoMap.getWidth() + 1) * ((isoMap.getHeight() + 1) * tileWidth)) / 10;

        //Locals

        int tileX, tileY;

        float depthOffset;

        spriteBatch.Begin (SpriteSortMode.BackToFront, BlendState.AlphaBlend);

        //Draw Iso Map

        for (int y = tileOnY; y < tileOnScreenY; y++)

        {

            int rowOffset = 0;

            if ((tileOnY + y) % 2 == 1)

                rowOffset = oddRowXOffset;

            for (int x = tileOnX; x < tileOnScreenX; x++)

            {

                //Draw Base Layer Cells

                foreach (int tileID in isoMap.rows[y].columns[x].getBaseCells()) {

                    //Get Current Tile

                    tileX = (tileID % numberOfTilesPerRow) * tileWidth;

                    tileY = (tileID / numberOfTilesPerRow) * tileHeight;

                    //Set Poisition Rect

                    basePosition.X = (x * stepX) - (int)scroll.X + rowOffset;

                    basePosition.Y = (y * stepY) - (int)scroll.Y + baseOffsetY;

                    basePosition.Width = tileWidth;

                    basePosition.Height = tileHeight;

                    //Set Source Rectangle

                    baseImagePoisition.X = tileX;

                    baseImagePoisition.Y = tileY;

                    baseImagePoisition.Width = tileWidth;

                    baseImagePoisition.Height = tileHeight;

                    spriteBatch.Draw (tileSheet, basePosition, baseImagePoisition, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 1.0f);

                }

                //Draw Core Layer Cells

                int heightRow = 0;

                depthOffset = 0.7f - ((tileOnX + (tileOnY * tileWidth)) / maxdepth);

                foreach (int tileID in isoMap.rows[y].columns[x].getCoreCells())

                {

                    //Get Current Tile

                    tileX = (tileID % numberOfTilesPerRow) * tileWidth;

                    tileY = (tileID / numberOfTilesPerRow) * tileHeight;

                    //Set Poisition Rect

                    corePosition.X = (x * stepX) - (int)scroll.X + rowOffset;

                    corePosition.Y = (y * stepY) - (int)scroll.Y + baseOffsetY - (heightRow * 32);

                    corePosition.Width = tileWidth;

                    corePosition.Height = tileHeight;

                    //Set Source Rectangle

                    coreImagePoisition.X = tileX;

                    coreImagePoisition.Y = tileY;

                    coreImagePoisition.Width = tileWidth;

                    coreImagePoisition.Height = tileHeight;

                    spriteBatch.Draw (tileSheet, corePosition, coreImagePoisition, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None,

                                      depthOffset - ((float)heightRow * heightRowDepthMod));

                    heightRow++;

                }

            }

        }

        spriteBatch.End ();

        base.Draw (gameTime);

    }

}

```

Any help with this would be greatly appreciated. P.s - The base layer of tiles is rendering correctly just in case anyone was wondering, i just kept the entire base layer at tileID 0. \*the plain grass tile you see in my output :)

# Answer
> 1 votes
```
int mapx = (tileOnX + x);
int mapy = (tileOnY + y);
depthOffset = 0.7f - ((mapx + (mapy * tileWidth)) / maxdepth);

```

I forgot to add on the incrementing x & y values from the for-loop :/.

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


# Question
Title: Optimization of Storage of Spells a Character Knows
I need to store which spells a character knows. While the game is executing I have them stored in a vector. Obviously storing this many values is either going to take a lot of computing to get the file size smaller or simply a large file size.

My best bet was to convert the vector into a single long int variable to store in the file. This will work out fine until there are too many spells to contain in a single variable.

I could split it up into multiple values but I was just wondering if there was a better way to accomplish that or if I should simply store the full list (strings, ints, etc.) in a text file and deal with the slightly large file size.

I'm using c++.

# Answer
If storage size is your main concern, using `vector<bool>` is probably actually your best bet. This is because `vector<bool>` is optimized to use one bit per bool instead of one byte (see reference here). From there for file read/write just make sure to write the capacity of the `vector<bool>` to file then use the same one bit per bool/spell (there's probably a good way to do this as a block).

If you go this route you can check if a spell is known just by knowing it's index in the vector, which will just be a matter of storing an unsigned variable of sufficient size. The vector operation should handle the bitmasking to get that one bit for you.

* char: 255
* unsigned short: 65535
* unsigned int (32 bit): 4294967295
* unsigned int (64 bit): 18446744073709551615

Really if you find yourself needing over an unsigned short for spell indexes you're probably going to find yourself running into other problems, but at very least this part of the system will expand fairly easily.
> 2 votes

---
Tags: c++, vector, file-format, file
---


title: XNA 4.0 Plane size

text:
# Question
Title: XNA 4.0 Plane size
Possibly a dumb question, but do planes stretch on to infinity? I can't define a spanning area for it, and would have to do some sort of check for collisions like `if(x intersects BoundingBox and Plane`?

**Edit**: I'm trying to do wall collision and would like to take into account diagonal walls, which would be impossible for bounding boxes as they are axis aligned.

# Answer
A plane is only defined by a normal vector and a position. The position is the 'center' of the plan and the normal vector is where 'up' is. Other than that a plane has no bounds, it is indeed infinite. If you would just like a square piece of ground (or wall or whatever) you should just use `BoundingBox` since they have a position and bounds so they should suit your needs.
> 1 votes

# Answer
It sounds like you already conceived of using planes to define arbitrarily shaped regions. It's not necessarily the most efficient method, but you can use them for collision detection. The planes can represent half-spaces, informally meaning that one half of space is on one side of the plane.

An axis-aligned bounding box is a specific case of using six halfspaces, two for each axis with opposite directions. If a point is on the positive side of all six planes, it is within the bounding box. If a point is on the wrong side of any plane, you immediately know it does not intersect the box, and you can skip further checks.

The same method can be used for an oriented bounding box (different plane normals) or for shapes other than rectangular prisms. Wikipedia calls them convex polytopes.

So for your purposes, you could use planes to define your diagonal walls. Planes are purple, your player is red.

If your player's position, projected onto the plane's normal vector (dot product), is less than the plane's distance from the origin in the direction of its normal (accounting for some radius of size of the player), then that player has not collided with the wall. If it exceeds that check value, then you know the distance and direction to push your player back out of collision.

Unforuntely, you don't get the early-exit benefit because you aren't using convex shapes, but you can still accomplish what you want.
> 1 votes

---
Tags: collision-detection, xna-4.0
---


title: What is a Fragment Pipe?

text:
# Question
Title: What is a Fragment Pipe?
I remember someone saying "24 fragment pipes on nVidia 7800" in a presentation.

Am I correct in saying that a *fragment* is the data that can generate a pixel in the frame buffer? Or are fragments the same thing as pixels? I'm getting confused here.

What *is* a fragment pipe?

# Answer
> 4 votes
A fragment pipe is a portion of the pixel pipeline that processes fragments. The more you have, the more you can parallelize fragment rendering. More is better, but like many things you get diminishing returns. You can learn more about the graphics pipeline here. The pixel pipeline is what's responsible for creating what goes in each pixel on screen, essentially the last two steps of this process:

So, what's a fragment?

From Wikipedia:

> In computer graphics, a fragment is the data necessary to generate a single pixel's worth of a drawing primitive in the frame buffer.

With a more detailed description also provided:

> As a scene is drawn, drawing primitives (the basic elements of graphics output, such as points,lines, circles, text etc.) are rasterized into fragments which are textured and combined with the existing frame buffer. How a fragment is combined with the data already in the frame buffer depends on various settings. In a typical case, a fragment may be discarded if it is farther away than the pixel that is already at that location (according to the depth buffer). If it is nearer than the existing pixel, it may replace what is already there, or, if alpha blending is in use, the pixel's color may be replaced with a mixture of the fragment's color and the pixel's existing color, as in the case of drawing a translucent object.
>
> In general, a fragment can be thought of as the data needed to shade the pixel, plus the data needed to test whether the fragment survives to become a pixel (depth, alpha, stencil, scissor, window ID, etc.)

---
Tags: shaders, fragment-shader
---


# Question
Title: 2D water shader similar to Limbo's effect
I'm wondering how I would go about creating a 2D water shader that is seen in this video http://www.youtube.com/watch?v=phChFfi4GOs

The water effect that limbo uses is pretty awesome. I'm not so much concerned about the waves, other articles cover that, but how can I get the..diffraction, I believe it's called, and various blurriness and how the object looks like it's moving even though it isn't (like real water).

GLSL is my target language.

But I don't have any idea on how to do the blur-like below-surface water movement effect. Any ideas?

# Answer
> 1 votes
For refraction, you need to render the background to an offscreen buffer. Then draw it on screen. Finally you draw the water on top and pass the background texture into the water shader.

In GLSL you can use gl\_FragCoord to get the onscreen coordinate of the pixel. You will have to divide by the background texture size to get the uv for the texture lookup.

Now, to have cool water refraction, you have to perturb the uv coordinate slightly. There are 2 ways: You can either use a load of sines and cosines, based on x, y and time. Or you could have bumpy normal maps and scroll them differently, summing them up, normalising and using xy of the normal vector to perturb the background sample position.

Finally, if you want to have a bit of blur there are a variety of ways to achieve this. The easiest is a simple box filter. Just sample a grid of pixels around the lookup point and get the average.

Hope that helps.

# Answer
> 0 votes
Any idea or help about this shader effect ? I found a couple of idea but I don'r know if they are great : GPUGems - Refraction

---
Tags: opengl, 2d, shaders, glsl, water
---


# Question
Title: How should I setup my Minecraft-like world rendering for the best performance?
I want to know what technique will give me most fps in game. I have minecraft-like world and I need to display it. Now I have only one cube, created as VBO and if i need to display cube I just display it. But now I want to know what will be faster:

Create for each cube type VBO (even for each side of it) or to create new VBO each frame for whole mesh to display?

I am very new to subject so if there are other faster techniques let me know. Thanks in advance.

# Answer
> 3 votes
This is not a simple question - but the philosophy is simple - seek out like things and bundle them together so that the pipeline never starves for data nor stops to change gears.

Secondly, do NOT create the same thing again and again - if you have a cube, build the vertex buffer and index buffer once - use instancing, and use the world matrix to change location, size, and orientation of the cube.

If you have many cubes that never move, then preprocess them to incorporate their position in the world into their vertices proper - i.e., you are changing from project\*camera\*world to just project\*camera

If you have many cubes that all have the same texture or material, consider bundling them all up into one vertex buffer - course this is assuming you're never going to fiddle with the geometry

Use constant buffers whenever you can - organize things so they change only when they have to - never load them with the same data all over again - sort things so that like comes through the pipeline with like

At the end of the day, your final techniques will likely be tuned to the nature of your application - you'll do what you need to do to keep those pipes flowing in the gpu as efficiently as possible

---
Tags: directx, voxels
---


# Question
Title: How do I implement fog of war in a tile-based game?
I have created a 2D Tile Based game. The game has a single path that the sprite can move on. I want to create to make the entire screen black except for where the sprite is.

The sprite has commands such as *left* where he keeps looking left, *right* where he keeps looking right and *move forward* where he moves in the direction he is looking. I want to make it such that when he looks left then the tile on the left of the sprites, fog should be removed and so on for all the sides.

How can I do this?

# Answer
> 1 votes
As always, you have several ways of doing it:

In any case, add a **bool Visible** to each tile, and set it to **true** when it has been discovered. This property decides whether your tile is visible or not. How you save that property entirely depends on your code, only you can answer that.

a) Set the background to black (GraphicsDevice.Clear(Color.Black);) at the beginning of each draw step, and simply don't draw an undiscovered tile.

b) All overloads of SpriteBatch.Draw have a parameter Color, which tints the texture to a certain color, without changing the actual texture in any way. If Visible == false, then you use Color.Black in the Draw method, otherwise you use Color.White.

c) If at some point you want a nicer texture than plain black, you can simply start out with all tiles being the fog tile, and then replace the texture at a visible tile with the one it is supposed to be.

# Answer
> 0 votes
To do what you want you need to use combine the char line of sight with the visibility of the tile.

### Line of sight

You will use some algorithm to determine which tiles are visible or not at a given time.
There are several algorithms for that, research one suitable for your game type.

Each tile will have three states:

### Visibility states

1. **Unknow.** This is a tile never saw. You will usually keep it black or otherwise mark it as unknow.
2. **In sight.** This tile is in your sight, you can see what type is the tile and its contents. The first time you see it, you flag it as *Know*.
3. **Know but out of sight.** This tile was saw before. You know that type it is but not the contents. You may mark it with some obscuring fog and may or may not show the last know content.

---
Tags: xna, c#, tilemap, fog-of-war
---


title: What is "tools development?"

text:
# Question
Title: What is "tools development?"
I have been looking at different jobs in the games industry and a lot of the jobs that I have seen advertised are for a "Tool Developer" position. I do not know what this actually is.

Could someone explain what this is to me please? And if anyone has any links to material that would help me understand it more then that would be very much appreciated.

# Answer
A tools programming position is *generally* about being a force-multiplier for the rest of the development team. The exact nature of the work will of course vary widely from studio-to-studio, depending on the individualized needs of that company.

Primarily, however, you would be tasked with creating software that was going to be consumed by other developers within the studio, and the role of that software might be to:

* author assets or content (levels, models, items, spells, whatever) for the game directly
* act as a bridge between your studio's game or build pipeline and another content creation tools (for example, exporters for Maya).
* be part of automated build processes that transform the source game assets into their final compiled forms for distribution with the retail game
* assist developers in day-to-day boilerplate tasks, such as syncing to particular builds of the game or transitioning between branches

It's also important to note that in some studios this is considered an extremely entry-level position, because it ends up involving mostly thoughtless grunt work (moving buttons around on a UI for a designer, perhaps). In others, it's exactly the opposite, because it involves the care and feeding of mission-critical build and deployment pipelines for live shipping MMOs.

The range of responsibility and expectation is large (although really, this is true of almost any position in the industry), but the overall goal is usually the same: keep on the lookout for any bottlenecks in the organization, and then buy, build or retrain until you have optimized that bottleneck.
> 21 votes

# Answer
In short: Develop programs used by others to create something (i.e. tools).

A popular and easy example would be a level editor for a game.

But this could be a lot more behind the scenes, like some version tracking program, a bug tracker, forums, some checker to verify content is without mistakes, etc.
> 17 votes

# Answer
A tools programmer is a specialized role, one that is becoming essential to production. You are essentially someone who looks at the pipeline used to create a game and find ways to optimise the process.

As a tools programmer for several triple-A games, I have done:

* Create new editors, e.g. level, graph, and sound, for designers to use.
* Extend, fix bugs, or add features to existing editors, e.g. in Unreal 3 and 4.
* Writing scripts and plug-ins for Digital Content Creation (DCC) packages like Maya and Photoshop, e.g. animation import/export, content management, etc.
* Source control (Perforce) integration into tools.
* Modifying open source tools to fit into a pipeline.
* Content verification.
* Mastering the final game for consoles.
* Build system and continuous integration.
* Localization import and export tools.
* Occasionally write new engine features and supporting tools.
* Managed databases with billions of records, e.g. performance data.
* Cloud computing/applications for back-end servers (AWS)
* ... etc

In some studios, e.g. independent, it is expected that every programmer can write tools to help the production of the game.

There are a few links below to the IGDA Tools SIG and the Toolsmiths blog (International Game Developers - Tools Special Interest Group).
> 6 votes

# Answer
Scenario 1: **Flash and AS3**

Sometimes you need to create certain functionalities which will help yourself more in your game production pipeline . By 'tool' it means something that can help speed your development process.

For example Flash basically does not provide with perfect pixel collision detection. So you could either write one yourself or try googling whether some guy has done it earlier and put it up as opensource code. A collection of source codes in properly arranged folders will folders will benefit you in the long run. Something like your own library.

Scenario 2 **Unity**

Likewise you can use unityscript(unity version of javascript) or c# to write components, small small tools for example B Splines, Bezier curves. Things that does not come as default in unity. Either write one yourself or get one from out there in the internet. They come in free/paid versions.
> 1 votes

---
Tags: software-engineering, tools, terminology
---


# Question
Title: Why is there a different set-constant-buffer function for every shader type?
Why are there `VSSetConstantBuffers()`, `GSSetConstantBuffers()`, `PSSetConstantBuffers()` (and so on) instead of just one `SetConstantBuffers()` for all shaders?

Should I have completely separate constant buffers for every shader type or should I use different functions (e.g. `VSSet...`/`PSSet...`) to set the same constant buffer when it holds data used in multiple shader types (such as light position or transform matrices)?

# Answer
> 8 votes
Because the alternative is worse.

There's a set-constant-buffer function for each major shader type because it is often desirable to have a completely different set of constants for each (and also, because one does not necessarily utilize every type of shader in all scenarios).

It's usually the case that each stage of the shader pipeline does a drastically different operation. The vertex shader transforms geometry from model space to clip space, the geometry shader manipulates or produces new vertex or adjacency information, the fragment shader makes color determinations, and so on. Because of the wildly different intents of each shader type, one will usually have very different constant inputs.

It would not make sense (and would be drastically limiting) to homogenize the interface such that you could have only a single constant buffer for every stage of the shader pipeline.

In your case, if you happen to be able to usefully use the same constant buffer for all shader stages, then its fine to set that buffer to each stage using the appropriate method. As your usages of each shader stage become more advanced, the likelihood that you'll want exactly the same data across every stage will decrease.

# Answer
> 0 votes
In systems that manage distinct shader types, as opposed to those with uber-shaders, it's extremely helpful to be able to segregate the constant buffers for the different shader types - consider cases where the vertex shader, and it's associated constant buffer remain fixed - however the pixel shader definition alternates between a pure material based shader, a pure texture based shader, and a texture and material based shader - if this were conflated with the vertex shader constant buffer, then you could end up doubling the number (ok 2n - 1 for the purists :-) of constant buffer definitions for no good reason, not to mention requiring that some constant buffer information would be updated when it didn't actually need to be

---
Tags: directx11
---


title: How to make a map surface object

text:
# Question
Title: How to make a map surface object
I'm making a 2d tile based game. In pygame I could create a map like this:

```
screen = pygame.display(resolution)
map = pygame.Surface(width, height)
for tile in all_tiles:
    map.blit(tile)
screen.blit(map)

```

The strength of this is that I can scroll the map by changing the map surface x and y. Also all the in-game coordinates are conveniently set in relation to the map rather than the screen. However I can no longer use pygame, and I'm trying to switch to pyglet instead. As far as I can tell pyglet doesn't have an equivalent `surface` class built in, and therefore I need to build my own, this is what I need help with.

I've used `pygame.Surface` extensively without really understanding how it works (python programmers these days huh). So I'm hoping you can offer some insight on how to get started. I know it needs a width and height, as well as some kind of list of the sprites which have been 'blitted' to it, and that moving the surface itself moves all the contained sprites, so surfaces blitted to it are somehow anchored to the surface rather than the screen.

How is this stuff done in pygame, and how do we create a pyglet friendly version?

# Answer
The concept of a surface in this situation is simply describing a texture. To understand this better, you should also understand the rendering process. When rendering anything using modern graphics API's, the end result is always going to be the same, a buffer (texture) of color data that is presented to the screen. How you get to that buffer can vary quite significantly, but the end goal is still the same. The rendering pipeline today is a complicated multi-stage system that involves at the simplest level per-vertex and per-pixel operations. When rendering a 2D image to the screen, you are essentially passing through a quad of a certain size, and uv/texture information for that quad. The graphics pipeline takes care of transforming the vertices of that quad into the appropriate coordinate system for your screen, and rasterize the texture you passed in to the pixels at that rectangles location on the screen. This pixel color data is all drawn to a texture, before finally being presented.

To finally answer your question about how to create a surface that can represent a tile, you should consider the requirements of your surface. You need a way to represent its location on the screen, you also need a system for representing the size of the surface, and the texture information associated with it. Chances are that pyglet already has support for renderable sprites/surfaces/textures, and you simply need to wrap this functionality in such a way that it is easy to use in your game. A quick look up shows pyglet provides an easy method of rendering a grid of textures to the screen already, as well as support for per-texture render calls.

http://www.pyglet.org/doc/programming\_guide/displaying\_images.html
> 4 votes

---
Tags: sprites, pygame, pyglet
---


title: Move object to position using velocity

text:
# Question
Title: Move object to position using velocity
I'm trying to make a simple object move to a desired location using its velocity. But I'm having trouble with it over shooting its target.

I have to use velocity, I can't simply lerp the position, although something like lerping is the effect I'm looking for.

# Answer
> 4 votes
There are two problems. One, you are setting the velocity directly yet applying it as a force by taking into account the ridged body mass. Two, your "slowing down" is exactly the same as you are speeding up, you are not inverting the speed adjustment.

Though I am unsure why (if the object has a ridged body) you are performing this by hand instead of with physics forces, may I suggest:

You effectively need to answer two questions at any given time, with one more optional questions.

1. How far will it take me to stop?
2. How far is my target?
3. Optional: How much more distance can I accelerate until I would be unable to decelerate in time.

To stop we'd the time for our velocity to decelerate to zero:

* Let *v* be the current velocity and *v'* the velocity in time *t*. ***0=(v - v')*** or ***v' = v***
* Then letting *a* be acceleration ***a\*t = v*** or ***t = v/a***

We then need the distance this takes us:

* First calculate the average velocity *A* ***A= (v+v')/2*** or ***A= v/2***
* Then the stopping distance *d* is a matter of applying time to the average velocity ***d = tA*** or ***d = tv/2*** or ***d = (v/a)v/2***

The code is as follows

```
protected virtual void Movement(){
    targetDistance= Vector3.Distance(transform.position, wantedPos);
    stoppingDistance = GetCurrentStoppingDistance(Velocity.magnitude, acceleration);
    public Vector3 engineVelocity = transform.forward * acceleration; //assume we are accelerating forward at first
    if(targetDistance<= stoppingDistance ){
        engineVelocity = -1 * engineVelocity; //decelerate instead;
    }
    else if(targetDistance<= (stoppingDistance * 1.05) ){
        engineVelocity = Vector3.zero; //stop accelerating  5% of the distance before we need to start slowing to avoid over shoots between frames
    }
    /*
     * set the velocity as a velocity (no mass adjustment needed, this isn't a force being applied.
     * Note we SHOULD be using the ridged body ApplyForce and supply it with a VelocityChange force
     * type instead)
     */
    Velocity += engineVelocity;
}

private float GetCurrentStoppingDistance(float velocity, float accelerationPossible){
    return (velocity/acceleration) * velocity * 0.5f;
}

```

Remember: Velocity changes do not take mass into consideration, only application of a force or an impulse would require that.

# Answer
> 1 votes
To sum up the comments:

Use the following strategy for the arrival behavior. This paper has more information.

```
target_offset = target - position
distance = length (target_offset)
ramped_speed = max_speed * (distance / slowing_distance)
clipped_speed = minimum (ramped_speed, max_speed)
desired_velocity = (clipped_speed / distance) * target_offset
steering = desired_velocity - velocity

```

You can calculate the `slowing_distance` dynamically using the current speed of your entity and it's maximum acceleration with the following equation:

```
distanceToComeToStop = (speed*speed)/(2*maxAccel)

```

Finally, you need to remember to stop once you get there! Pick a small distance that makes the entity "close enough". If your entity is within this distance and moving slow enough to stop using the maximum acceleration, set your entity speed to `0` and stop checking if it's close enough.

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