title: Get world-position in Vertex shader

text:
# Question
Title: Get world-position in Vertex shader
I'm wondering how I can get the final position of a vertex. I use glTranslate in my render code, and I'm not getting the world-coordinates correct. My world is devided in chunks and my position get's screwed up.

I have tried multiplying the position with the 3 built-in matrices, but no success.

# Answer
> 1 votes
Unless you are pre-transforming all of your vertex data, vertices should come into the vertex shader in object/model space. This is typically where the vertices are converted into screen space by transforming the vertex by the world, view, and projection matrices. If you want to perform operations on the vertices in world space, then either pass through the objects world transformation matrix in addition to a pre-multiplied world-view-projection matrix. Or pass in the world, view, and projection matrices separate from each other. You would then transform the vertex by the world matrix, perform all necessary operations on it, and then transform it by the view, and projection matrices before passing it through to the pixel shader.

---
Tags: opengl, shaders, glsl, vertex
---


title: Android TCG structural design

text:
# Question
Title: Android TCG structural design
I started developing tcg for android, using ADT bundle.

What is the right approach/way for making/storing cards/game info, local sqlite, some kind of data file? some service? or something else?

# Answer
You could probably benefit of a data driven approach. I'm assuming the premisse that every card might have one or more associated effects, or it can just have some stats and no special effect, something like M:tG.

You can create the effects each on it own class and probably use a factory to generate them as the cards are instantiated. The more generic the effect, the easier to reuse.

Then you create the cards as data, if they are saved on xml, sqlite, or whatever is up to you. With this approach you only need to change the code if implementing new effects, any new card using existing effects will just be added to the data files.

example:

```
<card name="Fireball" type="INSTANT" cost="2">
  <effects>
    <effect value="3">DAMAGE_OPPONENT<effect>
  </effects>
</card>

<card name="Leech" type="SORCERY" cost="4">
  <effects>
    <effect value="3">DAMAGE_OPPONENT<effect>
    <effect value="3">HEAL_PLAYER<effect>
  </effects>
</card>

<card name="Healing Monk" type="Creature" cost="3" attack="1" defense="1">
  <effects>
    <effect when="COME_IN_PLAY" value="1">HEAL_PLAYER<effect>
    <effect when="LEAVE_PLAY" value="1">HEAL_PLAYER<effect>
  </effects>
</card>

```

Of course those are only illustrative, you need to design the TGC first and only then you can design a good data model.
> 1 votes

---
Tags: java, android, game-design, multiplayer, libgdx
---


# Question
Title: Removing drawn Allegro texts and primitives
I'm working on a game with Allegro 5 that has a loop. I'd like to make the program write onto the screen, how much time the loop has ended. These are the rounds of a turn-based game, obviously. I use the `al_draw_textf` function for it, which works perfectly, but I put it into the loop. Its consequence is obviously that the number is written on the same place all the time.

To prevent it, I should delete it at the beginning of every loop. Sadly, I couldn't find any functions in Allegro Manual that does it. How can I do that then?

# Answer
> 0 votes
Typically, you would do a Clear Screen before starting your subsequent Draws, otherwise all your drawings would remain on screen and overlap.

With Allegro, you will need to clear the bitmap you are drawing to before you draw to the screen. I haven't used Allegro in a very long time, so I may be wrong about this.

---
Tags: c++, game-loop, allegro, text
---


title: International Font in XNA?

text:
# Question
Title: International Font in XNA?
I'd like to know are there some international fonts?

I mean a font for all European languages including Russia.

The question is about XNA fonts.

# Answer
Yes International Fonts will work in XNA(SpriteFont). There are international fonts scattered across the internet and there might be some on your computer.

Please visit this thread for more details:

http://xboxforums.create.msdn.com/forums/p/93395/609738.aspx

EDIT:

I would suggest using Segoe UI, it supports a numerous amount of languages. See the link for more details.

http://www.microsoft.com/typography/fonts/font.aspx?FMID=1941
> 0 votes

---
Tags: xna-4.0
---


# Question
Title: Problem with Widget Event Reporting in Libgdx
So I'm trying to test an ImageButton on an Android device. I can get the button to appear on the screen, but when I press it nothing happens or appears on the log. Here is what I have in the Show() method of a class that implements the Screen class.

```
public void show() {
    uistage = new Stage();
    Texture tankSprite = new Texture(Gdx.files.internal("TankSpriteBase.png"));
    tank = new Tank(0, true, tankSprite);
    tank.rect.x = 100;
    tank.rect.y = 100;
    tank.rect.width = 44;
    tank.rect.height = 45;

    dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
    rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));

    rainMusic.setLooping(true);
    rainMusic.play();

    float w = 800;
    float h = 400;

    camera = new OrthographicCamera();
    camera.setToOrtho(false, w, h);
    batch = new SpriteBatch();
ImageButton.ImageButtonStyle ibs = new ImageButton.ImageButtonStyle();
    ibs.up = new TextureRegionDrawable(
                new TextureRegion(
                        new Texture(Gdx.files.internal("direction_left.png"))));
    ibs.down = new TextureRegionDrawable(
                new TextureRegion(
                        new Texture(Gdx.files.internal("direction_left_pressed.png"))));

    leftButton = new ImageButton(ibs);
    leftButton.setX(300);
    leftButton.setY(300);
    leftButton.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log(LOG, "down");
                System.out.println("down");
                return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log(LOG, "up");
                System.out.println("up");
        }
    });
    leftButton.setWidth(ibs.up.getMinWidth());
    leftButton.setHeight(ibs.up.getMinHeight());
    leftButton.setBounds(0, 0, ibs.up.getMinWidth(), ibs.up.getMinHeight());
    leftButton.setTouchable(Touchable.enabled);

    uistage.addActor(leftButton);
            Gdx.app.log(LOG, "Width is "+Gdx.graphics.getWidth()+" and height is "+Gdx.graphics.getHeight());

    background = new Texture(Gdx.files.internal("background.png"));
    background.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    TextureRegion region = new TextureRegion(background, 0, 0, 512, 301);

    sprite = new Sprite(region);
    sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
    sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
    sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);
            }

```

Might anyone know why this doesn't appear to be working?

# Answer
> 1 votes
Oh wow, completely bungled this. I forgot to add:

```
Gdx.input.setInputProcessor(uistage);

```

Why this is important is detailed here. Remember to check your code and read your docs, kids! (Eat your veggies too)

---
Tags: android, libgdx, events, interface
---


# Question
Title: It is okay to use a string as a resource location key in a GUI system?
I'd be afraid of the efficiency. Is there a better way?

# Answer
Yes, it's perfectly fine to use a string as a key to look up resources. The "efficiency" of the check (the string comparison) isn't that damning on its own, especially if you do it intelligently and employ reasonable caching behavior, and so on.

A string has several advantages as well, such as affording you more data-driven flexibility than an enumeration will (since adding or changing enumerations usually means rebuilding code).

If the string look-ups ever do become a problem, according to your profiler, you can consider changing them to something else at that point.
> 1 votes

---
Tags: gui
---


title: Player getting caught on floor

text:
# Question
Title: Player getting caught on floor
My player is getting caught on something on the floor. My whole environment is just blocks. I have looked through (and tried to change) just about everything I can think of in my player update method. Any idea what could be solving this? Here is the code:

```
public void update(GameContainer gc, int delta, Map m){
    boolean updateX = true;
    boolean updateY = true;

    if(!movingLeft && dx < 0f){
        dx += .2f;
    }
    if(!movingRight && dx > 0f){
        dx -= .2f;
    }

    if(!movingLeft && !movingRight && ((dx < 0 && dx > -.2f) || (dx > 0 && dx < .2f))){
        dx = 0f;
    }
    boolean fallFlag = true;
    prx = new Rectangle(x + dx, y, 10, 10);
    pry = new Rectangle(x, y + dy, 10, 10);
    for(Platform p : m.platforms){
        r = new Rectangle(p.getX() - 2, p.getY() - 2, 20 + 2, 20 + 2);
        if(prx.intersects(r)){
            updateX = false;
            dx = 0;
        }
        //check if my dy will cause me to hit a platform
        if(pry.intersects(r)){
            //if I am moving down, set falling to false
            if(dy > 0)
                fallFlag = false;
            updateY = false;
            dy = .025f;
        }
    }
    inAir = fallFlag;
    if(inAir)
        dy += .025f;
    if(updateX)
        x+=dx*(delta/10);
    if(updateY)
        y+=dy*(delta/10);
}

```

# Answer
> 6 votes
I think the problem is that you are not taking gravity into consideration when checking for collision. For example, you update dy as follows:

```
if(inAir)
    dy += .025f;

```

However, for your collision check rectangle, you do the following:

```
pry = new Rectangle(x, y + dy, 10, 10);

```

This takes into account the movement of your object based on input, but it doesn't take into account the extra 0.025f accumulated by your falling acceleration.

Instead, create your rectangle as follows, and it may fix your issue:

```
if (inAir)
   pry = new Rectangle(x, y + dy + 0.025f, 10, 10);
else
   pry = new Rectangle(x, y + dy, 10, 10);

```

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


title: Path finding in games

text:
# Question
Title: Path finding in games
I am writing my term paper about Path finding algorithms in games, and i've got a couple of questions, hopefully you people could help me out with those ;)

So, i've done a little bit of searching around here and stumbled on this question. Now, the things are explained nicely there, but i wonder if anyone got examples of games using those? (obviously A\* won't be hard to find, it seems to be quite popular now). I figured that BFS or DFS would probably be found in some older games but I'm not that familiar with those, perhaps someone knows a couple that might be using those algorithms so i could investigate deeper?

Also, i'm having trouble figuring out the strong/weak sides of those algorithms compared to each other, as in when should i use BFS instead of Dijkstra's Method for example, from both efficiency and mechanics point of view? (If amount of available memory isn't the issue). Or is A\* an answer to all the prayers and there is no reason not to use it?

Any help would be appreciated!

# Answer
> when should i use BFS instead of Dijkstra's Method

BFS applies to unweighted graphs only. Dijksta's is just an extension of BFS to weighted graphs \- Dijksta's on an unweighted graph will examine exactly the same nodes as BFS.

So, they can essentially be viewed as the same algorithm.

> Or is A\* an answer to all the prayers and there is no reason not to use it?

A\* is just an extension of Dijkstra's algorithm, which speeds it up by using a distance-heuristic.

Dijkstra's and A\* are for much more general problems than just pathfinding on a grid: they can be used to pathfind on any directed, weighted graph. A distance-heuristic for these won't always be possible; that's when Dijkstra's should be used.

However, if you have a heuristic available, there is no reason *not* to use A\* - it will always be as-fast or faster than Dijkstra's. For pathfinding in games, which often just involve units moving through 2D or 3D space, you usually have a distance-heuristic *(the actual distance between the points)*, so A\* should be chosen over Dijkstra's.

---

The reason A\* is often chosen over more complicated algorithms for games is that it's simple to understand and implement, yet fast enough for our needs. The biggest mistakes when using A\* for games is not using the wrong algorithm, but implementing it incorrectly. For example, it is not well-known that ties must be broken towards the endpoint, and amateurs often incorrectly run the pathfinder every frame.

There are other algorithms that are sometimes used, though. A rather recent algorithm that is gaining popularity is Theta\*. It is like A\*, but gives the unit freedom to move in all directions *(which is common in games)*. The old approach to do this was using A\* + linear interpolation, but Theta\* gives better results, with very little cost to speed or complexity.

Another interesting one which I recently wrote a post in is HPA\*, which is a useful way of decreasing the search-space to make searches go faster *(at the cost of returning non-optimal results)*

---

You can read about more about different pathfinding algorithms here. However, some of them are extremely complicated, and very few of these will actually give much benefit for most games anyhow - as a game programmer, it suffices to just learn and understand A\*.
> 8 votes

---
Tags: algorithm, game-mechanics, path-finding
---


title: Procedural Geometry Generation

text:
# Question
Title: Procedural Geometry Generation
I have recently been looking into SceneKit for OS X and noticed that there are several factory methods to create geometric shapes such as:

Box, Capsule, Cone, Cylinder, Plane, Pyramid, Sphere, Torus and Tube.

I am interested in adding such primitive shapes to my renderer but am struggling to find any reasonable source from which I can gather an understanding of procedural generation. There are several resources which detail the theory, but lack the appropriate source code to back it up.

SceneKit provides factory methods which allow for dynamically setting the attributes of such shapes. In the case of the Box, you can provide integer values for the number of width, height and depth segments which each face should be divided into.

I understand the theory but lack the knowledge to begin subdividing geometry faces to achieve the desired effect.

The vertices for each shape are most likely quite easy to generate in simple loops. What stumps me is knowing how to create the faces, or rather the appropriate texture coordinates for each face. Normals can be calculated per face so I'm fairly confident I could achieve what I want, it's just knowing where to start.

Can anyone provide any details on procedural geometry? What I really need is some source code to glean some information from. I have searched high and low for tutorials but have so far come up with only a few reasonable sites or blogs. Any good books, tutorials, blogs or research papers would be appreciated.

**Edit based on comments**

I should have clarified that I know how to create vertices for basic shapes, most of these can probably be achieved by simple loops. What I don't comprehend is how to create faces from the generated array of vertices. How do I create a triangle strip, or triangles, from a seemingly unordered array of vertices?

I assume that once I get past this point, I can create the normals from each face. Whilst I haven't delved into this yet, I have seen a lot of references to this and am sure it will be easy enough to implement.

Ideally, i'd like to be able to generate geometry from a given set of properties such as the way that SceneKit provides. Given SceneKit has done it, and you can do similar things in Blender and Maya etc, I assume i'm not trying to implement the impossible.

The final aspect would be applying textures. Again, this isn't something I have implemented but have read up on and am aware of the requirements.

The main problem here is that I know what I want to achieve but am struggling to decipher how to implement for the aforementioned primitives. I was hopeful that I would be able to find some semblance of knowledge by way of source code but I really haven't come across anything suitable so far.

# Answer
The way to generate the edges and the faces of a primitive shape like a box, a cone and all those you cited is to generate them at the same time you create the vertices. In fact, you should create the vertices in a logical way that makes it easy to compute the edges and faces accordingly.

There are algorithms that take as input a set of points in space and compute a so-called "point set triangulation" over it, but the problem of point set triangulation is NP-complete, so that it is faster to make the edges and faces as you go than to just compute the vertices and let an algorithm do the work. Just letting you know this solution exists.

Apart from this inefficient solution, I reckon you can only treat the primitives on a per-case basis, as in the examples that follow.

**A mesh is vertices and faces**. The edges are contained within the description of the faces unless your mesh contains lines that do not make up faces. The vertices are tuples of 3 floating-point coordinates. The edges are simply pairs of references to the vertices, but then again you surely won't need them. Say for instance that your vertices are in an indexed array. Well your your edges could then be pairs of indices of that array. **The faces are triplets of references to vertices or triplets of indices in the indexed array case**.

You should be able to count the vertices, edges and faces that make up each of these primitive shapes because being able to count them means understanding the properties of the object which helps you devise the method with which you'll build them, using loops and other tools as we'll see.

## Cone

For a cone with *n+2* vertices, *3n* edges and *2n* faces:

1. Make two separate vertices.
2. Make a circle around one of the vertices (the base vertex), that is within a plane perpendicular to the segment between the first two vertices. Hopefully you can make a circle using trigonometry, right? That's already all of the vertices of the cone. That's also one third of all the edges (there are *n* edges in the circle and *3n* in total).
3. Make *n* edges from the base vertex to the *n* vertices in the circle. You can make one half of the faces (that's *n* faces) as you do that.
4. Make *n* edges from the tip vertex to the *n* vertices in the circle. You can make the other half of the faces (that's *n* faces) as you do that.

1) 2)
3)
4)
End result:

You can also create the edges and faces as you run the loop that makes the circle. Same complexity, same thing. Make one vertex on the circle, store it into your array of vertices, add the corresponding edge (pair of indices) to the array of pairs of indices if you feel like it, and finally add the corresponding face to your array of triplets of indices. Move on to the next vertex.

## The cylinder and the tube: not doing the same work twice, and quads

Again, for the tube it starts with a vertex and a circle which will be the center of either the top or the bottom disc of the cylinder:

1. Make a vertex.
2. Make a circle around the vertex. Add edges (if you want edges) between the successive vertices of the circle and between the center vertex and each circle vertex. Add faces between each triplet of vertices made of the center vertex and two successive vertices on the circle.
3. Duplicate all that, translate the copy in the direction perpendicular to the base you just made, by the length of the desired cylinder.
4. Link the top and the bottom.

To link the top and the bottom, you must make quads between pairs of pairs of vertices that face each other. So think ahead and why not make yourself a function that makes two triangular faces out of four vertices?

Done. Notice that this time we use the fact that the same structure (circle + center) appears twice in a cylinder to take a shortcut. We don't have to make *all* of the vertices, edges and faces by hand, contrary to the cone where it was necessary.

Following this laziness principle, it's also possible to just make one quarter of the circle and duplicate it, and again, to make a full circle with very simple transformations (valid with any circle so with the cone too), but that's really overkill for a not so complex shape.

**You must always use the geometric properties of the objects you make to simplify their making**. Namely, their symmetries and invariants.

For a cylinder, just don't make the base vertex, just make the circle, duplicate, translate the copy, make the quads, done.

## The sphere and the capsule: adding complexity, still not the same work twice

To create a capsule, we want to create a UV sphere, split it into two halves, translate the first half and then link the two with the sides of the capsules.

Again it's possible to make only one eighth (!!) of the sphere, then duplicate it and reverse it, and then duplicate and reverse the result except along another axis, etc, to get a full sphere, in 4 steps (create the eighth, duplicate and reverse three times). Maybe overkill, but less so than in the case of the circle.

A simple UV sphere:

We in fact only make one half of it (for example), duplicate that half, turn the copy upside down and translate it by the length of the capsule:

We link the top and bottom half:

The real (somewhat) hard work comes from the trigonometry that goes into making a sphere. The set of all vertices belonging to a UV sphere can be described as the set of all points of the form:

where *R* is the radius of the sphere and, for a certain positive even integer *N*, we have the constant

*θ = × π/N*,

*k* and *n* are integers with *k* varying from *0* to *2N-1* and *n* varying from *-N/2* to *+N/2*.

To make a half-sphere or an eigth of a sphere, you have to restrict the set of values taken by *k* and *n*.

If *k* were real numbers and not just integer numbers, you'd get a whole sphere, not just the vertices on its surface. So what we've done here is **rasterizing the surface equation of the primitive**.

## The fearsome torus: it's easy after all we've seen!

Again, more trigonometry, more vertices, more quads, more symmetries, more invariants... more geometry! Find out the equation for the surface of a torus, "rasterize it" properly, simplify the problem using the (obvious) symmetries of the torus and, finally, loop through the set of vertices you just defined and make the edges and faces as you go!

See? Completely straightforward.
> 11 votes

---
Tags: geometry, procedural, computational-geometry
---


# Question
Title: Is ruby a suitable language for game development?
I want to move into some game development, but the only language I know really well is Ruby. Most of what I have read seems to point towards lower level languages like C++ for game development, or languages for specific frameworks like C# for using XNA. Does anyone have any experience using a language like ruby for game development? If so, would you advise for or against it?

# Answer
> 48 votes
I have no preference towards Ruby (or Python), I'm a Java person myself. But UnknownDevice's answer about how Ruby is somehow "not really for games" and Python is, frustrated me. I do hope he will clarify.

I know Pygame exists and has been around, and I recognize that Python has a larger userbase than Ruby. But to be honest, neither of them seems like a language "for games". Neither does Java, and that's my game programming language of choice. (and when I say "of choice", I do mean **by choice**, not because it's what's taught in school or because it's something I "know"). And really, what is a language "for games"? Well, speed is a factor, and obviously it must have libraries for graphics and other game systems (audio, input, etc).

As far as speed goes, it seems to be a tossup between Ruby and Python. Do some searches and you'll quickly find benchmarks and arguments for both sides of the spectrum, and various configurations which put one or the other ahead. Python with something called "Psycho" seems a popular speed demon compared to Ruby, yet regular Python seems to be a bit slower than Ruby. In the end, if you're choosing such a high-level language you're obviously not concerned with native speeds anyway; go with the language you know best. And obviously you know Ruby best, so I encourage it!

The other factor is whether the technology is there to create games; whether it can support drawing to the screen and collecting input and playing audio. Ruby can do all of these. In fact there are a good number of options in this respect. There's a ruby-opengl package at RubyForge which will give OpenGL support to Ruby (or it might be included by default?). Alternatively, Chingu provides "lightning fast OpenGL accelerated 2D graphics!" according to its homepage; it builds extra features on top of Gosu, which you could choose to use if Chingu is too much for you. Or for 3D graphics, if you don't want to use ruby-opengl, try G3DRuby, "a very clean set of wrapper classes for many of the more advanced OpenGL features". There's even Rubygame, which I can't find much information on but it claims to be "a cross-platform multimedia library" and given the name, must have emphasis on game development. If you are familiar with the popular SDL library for C++, there's Ruby/SDL or RUDL, both of which are Ruby wrappers of SDL. Or if you prefer the newer, more object-oriented SFML, it is also available for Ruby!

There is no reason that Ruby should be less of a game programming language than Python; if there is one, I'd really like to hear it so I can argue against it. **If you feel most comfortable programming in Ruby, and you are aware of the pros and cons compared to other popular languages, then by all means you can certainly develop games in Ruby!**

# Answer
> 9 votes
http://gafferongames.com/2009/01/11/ruby-is-not-at-all-suitable-for-game-development/

The URL is probably a bit of a spoiler.

tl;dr: the naive garbage collector is a real problem.

# Answer
> 5 votes
There's no reason why you can't. As long as there's multimedia support for a language, then it's gamedev material. Heck, a large proportion of one of the Rollercoaster Tycoon games was done by hand in ASM.

# Answer
> 1 votes
While I'm not familiar with a lot of the deep spec work surrounding Ruby, Enterbrain created the game making programs RPG Maker VX and RPG Maker XP that use game scripts based off Ruby: http://www.rpgmakerweb.com/

This was actually my first dive into the language. As most people said, you probably won't get the high performance of other languages, but if you're looking to start a 2D RPG (or other 2D game, really), it's probably one of the most sophisticated game editors out there to help.

# Answer
> 1 votes
Don't expect to write highly-performant, professional, commercial, 3D games with Ruby, but Ruby is a great language to use when learning game development concepts.

Gosu is the most popular (and actively maintained) library for writing 2D games in Ruby. It has an underlying C++ library that it uses to improve performance and interact with the underlying display rendering libraries like OpenGL.

As far as performance goes, the "default" Ruby implementation (MRI) will work fine (I suggest the latest Ruby 2.0 for best performance) but there are alternative implementations that have native threads and alternative garbage collection algorithms such as Rubinius, JRuby, etc. If you're making use of threads, you may want to try Rubinius, otherwise MRI Ruby will work just fine.

# Answer
> 0 votes
Ruby is a nice language, but it's not really for games to be honest. If you don't want to use C++ but want something like Ruby check out Python. For a good Python framework you should check out something like www.cocos2d.org/.

# Answer
> 0 votes
It depends what type of game you are interested in writing. I've used ruby to write AI clients for several games, including Diplomacy, poker, and Lost Cities. I find it's a very friendly language for quickly experimenting with different concepts. On the other hand, I wouldn't want to use it to write my real-time shooter - it just won't have the performance I need.

# Answer
> 0 votes
Your question is too general. Do you want just to write some computer game as a hobby project or do you want to get into indie/professional game development? Will it have graphics? On which platforms is it supposed to run?

In general, Ruby is suitable for hobby projects (BTW my favourite Ruby game is Ruby Warrior) and for the development of web-based games like Farmville. There's even certain demand for such programmers, try to google something like: "ruby programmer social game".

On the other hand, if you want to develop desktop- or mobile-based games with graphics, Ruby is not the best option. Consider:

* Javascript library supporting Coffeescript (its syntax is very similar to Ruby)
* Python - very similar to Ruby, better game libraries

# Answer
> -2 votes
I said Python because it has a bigger userbase and more choices when it comes to frameworks/libraries for games development. Its pretty obvious that this person has no experience in games development so it doesn't make sense to me to recommend that they use something like Ruby just because it's possible.

When I work on games I use C++ with Lua, I don't go off and write my game in Visual Basic just because it has media support. I'm sure everyone here has heard someone say certain tools for certain jobs. I'm sure you can hammer a nail with a shoe, but why would you do that when you can use a hammer.

---
Tags: ruby
---


# Question
Title: Implementing the "earn resource every N seconds" mechanism common to F2P games
In many free-to-play games, play will be rate limited in some manner by a resource that you naturally earn on a timed interval, but can opt to increase artificially through buy-ins.

A current example of this is the popular game Candy Crush, which refills 1 life (retry) on some set interval.

Key requirements:

* The client should be able to accurately predict the time to the next resource, such that it might display a countdown, etc.
* Resource gain is not regular. It can be offset by, at least, resource buy-ins, or perhaps varying intervals between users.
* Resource gain is capped, and thus not continual. E.g. maximum "lives" might be 5.
* The server is the resource authority, obviously. The client might predict resource generation without actual notification as to such, but the resource count is determined server side.

Naively, one might simply implement this as a database update across the collection on the interval (if the interval is constant), but this would surely not scale. It would become more and more out of sync with the client timers as the dataset scales and the operation takes more time. Not to mention, it would be wasteful, as it's likely that only the percentage of your membership currently online needs to see realtime updates.

It seems like it would be possible to *calculate* the resource as a function of time since creation, time spent uncapped, resources earned, and resources spent. Would this be a viable option?

**The question is, what is the best way to implement this mechanism to scale?**

# Answer
> 4 votes
It's simple arithmetic and requires no loops or periodic DB updates.

The player has a rate of resource gain. This is fixed until some external stimulus happens like the player buying an item to change speed. You need only know the current speed and resource counts for this to work.

Take the current time. Take the last time the resource counts were updated in the DB. Find the difference. Divide by speed. Add to current resources. Cap the value. Done.

If forced to calculate for any reason besides simple display, update the resource count, set last update time to now minus the remainder from the speed division, and you're good. Recalculate the current count and last time and store back in the DB if the speed is changed for any reason.

The only time you'll need to invoke this operation is when a timed-event occurs that changes resource acquisition rate or the player performs an action. Very efficient and scalable.

You don't even *need* to do the reculation for some timed events. If the player gains 30 resources/second for 10 seconds and then gains 10 resources/second after, you can easily account for this. Take the elapsed time and cap at 10 seconds. Calc new resources. Take the elapsed time minus that capped time value from the first recalculation, calc additional resources gained at the slower rate. You can extend this to be more generic and flexible. Essentially you can move all need to ever actually calculate a value to the client in most cases (for display) and only update the server when the server actually needs the updated values when the user tries to do something. No constantly running server code, no frequent ticks from the DB, no need to constantly write back into storage for inactive players.

The client generally does not need to be *exact*. Network latencies and the like make it impossible anyway. So long as you can pass the current resource count and last update time (in UTC or UNIX time or something), the client can estimate the current resource values within a few seconds of accuracy. This will generally be enough. The client will at worst be a few seconds behind. If that really matters, the client should periodically ask the server for its calculation and lerp over to that, accounting for measured request latency/RTT. You really don't need that for the average social game, though.

# Answer
> 2 votes
I've done things like this before using delta timing.

Here is an example:

```
int millisecondsThatPast = 0;
int numberOfPowerUpsToGive = 0;
int timeForEachPowerUp = 0;

public void setTimeForEachPowerUp(int timeInMilliseconds)
{
    timeforeachPowerUp = timeInMilliseconds;
}

public void onGameUpdate(int delta)
{
    millisecondsThatPast += delta;
    int n = 0;
    if (millisecondsThatPast >= timeForEachPowerUp)
    {
        for (int i = millisecondsThatPast; i >= timeForEachPowerUp; i -=
            timeForEachPowerUp)
             n++;
    }
    numberOfPowerUpsToGive = i * timeForEachPowerUp;
}

public int getNumberOfPowerUpsToGive()
{
    return numberOfPowerUpsToGive;
}

```

Here is an example on how to use it:

```
setTimeForEachPowerUp(5000); //5 Seconds

while (game_loop_in_progress)
{
    onGameUpdate(delta);
    int powerups = getNumberOfPowerUpsToGive();
    //Use the number of power ups to give this update
}

```

---
Tags: web, online, synchronization, free-to-play
---


title: How to handle and make animations?

text:
# Question
Title: How to handle and make animations?
I just finished a game for my design class and I ran into a problem that I always have but this time I'm going to learn the right way to do it. I was making the background animation for my menu in photoshop (just moving layers and tweening them)and I ended up rendering out 300 frames as pngs. I always do animations this way because the only way I've learned how to write animation engines is to use a root file name and append 00x on the end to get the current frame or to create an array of images to then loop through. This results in me having large numbers of individual images in my assets folder. Is there a better way to do animations? Both programmatically and in making them. I want to hand draw the frames most of the time but I don't usually want vector images. (So no flash unless its changed recently.)

Thanks! (I'm working off no sleep for three days now so if I need to clarify let me know)

# Answer
> 3 votes
For absolute laziness, it *might* be possible to just use those images as a background; it may end up being the joke of the class that 20MB of your 20.3MB game is just the menu background, but if you haven't slept for days some people are okay with that.

Some options I can think of for animations:

* Use a spritesheet. This isn't a good idea here, but often for characters people will make one large image, containing each of the possible states of a character. Various rendering systems can then clip out the part of the texture they need to display, for each frame (no copying it; just specifying which section of the texture to draw).
* Apply an animation engine. If the movements of the background are fairly simple, then you could have a rudimentary system of tweening parts of that animation in the game. Or, you could divide its parts into spritesheets to simplify how much is done by code. (For instance: One foreground spritesheet of the game's small hero looking out over a cliff with the wind moving his hair, a static texture of the sunrise in front of him, and another spritesheet of the villain looking down at him)
* If the coding environment easily supports it, you may render the result as a movie. From Photoshop, I think the easiest format would be an uncompressed AVI (which will be way too big!) Then, you can use a conversion tool like Handbrake to turn it into an H.264-compressed MP4 file.

# Answer
> 0 votes
I am working with AndEngine (2D, based on OpenGL) and AndEngine's approach to animation is to have one tiled texture where each tile is a frame. You can have 12 frames in a texture 1x12, 2x6 or 3x4. Because graphics hardware is very capable when dealing with textures, showing a region of the texture is very fast. Based on what engine do you use, or whether you make everything from scratch, you can probably use similar approach.

This is actualy the SpriteSheet that @Katana314 is talking about, but I am not sure why he/she says it's not a good idea here.

---
Tags: animation, software-engineering
---


# Question
Title: How to handle NPCs and other entities on moving objects like trains or planes
I was always wondering how trains or other moving platforms are implemented in games. For example: there a many games where you can walk on the back of a truck or on a train that starts to move. During this time you can freely walk around like you could on normal map. (I don't think about rail-shooter parts were you just fire a gun or sit still somewhere). Of course you could load a new map that just gives you the feeling of moving where actually the map is pure static, but that's not what I mean.

How does the game translates all the vehicle movements to the actual position of the entities that are on it? Especially AI, collision (you don't fall throu the platform due to some glitches) and smooth rendering (some games screw this up and you see the entities bouncing up and down).

If I would do this than I would probably use an own coordinate system for the platform and translate this into the "real" on. But I have no idea how this would look since you would have to store the "belonging" platform for every entitie and I think there's probably a better solution.

I think a good example is the transport system in World of Warcraft. The NPCs even have waypoints during flights and you can trade with them. It actually feels like on the ground.

I would really like to get some links with detailed explanations if there are any.

# Answer
It varies by game. Some try to model things physically using a physics engine and rely on friction to keep things moved together. This can be a bit fragile.

A more common technique that is used even in games (especially ones that don't have real physics support) is to just parent objects to others. If game logic detects that I've "landed" on a moving platform of some kind, then my avatar is parented to that object. My avatar's position is now relative to that moving platform so I move with it. This connection is then removed when I am no longer in contact with the platform (I jump or walk off the edge) in most cases. Some games will keep me parented if I jump but stay over the platform while in the air, making it so that I move with the platform even when jumping, while others do things more physically and apply the parent's horizontal velocity to my avatar if I jump, and yet others make all jumps purely vertical irrespective of the speed of the platform I might have been on. This technique makes the implementation super-easy and relatively bug-free although it can at times lead to physical inaccuracies (some of which might actually be desirable).

In some cases, there isn't even a moving platform at all, but rather the background objects around the platform I'm on are moved to give the visual sense of movement. This is common in cases where the entire usable play area is on some kind of moving platform, e.g. a fight on the top of train where falling off is just insta-death.
> 0 votes

---
Tags: physics, moving-platforms
---


title: A* Search in games

text:
# Question
Title: A* Search in games
I am making car racing game. I stuck with the `AI` of the game. I go through with the `A*` search, but there is problem that I want to ask that whether we have to make a `2D` array and than apply search on that array. `2D` array mean a grid, to which we apply the search algorithm.

Can an A\* path-finding implementation be practically implemented on data-structures other than a square 2D array?

# Answer
The A\* algorithm requires hat the set of possible agent locations be discrete, not continuous, and that there be a **connectivity** relation between the set of possible locations, called **nodes**.

A well-written A\* algorithm will not require any particular storage choice for the nodes and the connectivity, but will use **Inversion of Control** to obtain the *adjacent* nodes for each node under consideration from the client.

Eric Lippert has written a very good A\* exposition here. that can assist you in seeing how this is done.
> 2 votes

---
Tags: ai, path-finding
---


title: Rendering structure

text:
# Question
Title: Rendering structure
my question is "What is the best way to structure rendering code".

Is it better to make a class with a render function that iterates through all game objects based on there name or type and have no state manager or is it better to make a class with functions like drawpolygon, drawmesh, drawline and use it in a state class something like this(https://gamedev.stackexchange.com/a/13245/18912). or is there something else that works better ?

Thank you in advance.

# Answer
> 1 votes
A common thing people do is they make a drawing method for this. It's generally considered better the draw the object inside the class and directly use the API. It's also good if you can make a class to inherit which has the draw method inside, and allows polymorphism.

Generally the APIs have reasons why they are the way they are. It's best just use them as is without anything special for drawing. And wouldn't you have to eventually implement all the drawing code anyway? It just sounds like a waste of time to me.

Anyways, good luck!

# Answer
> -1 votes
This question is really complex, since it depends from game to game, and what you are going to render. But you know you have chosen a bad design when you constantly needs to update it for your doings.

There are so many different designs out there that you simply have to do some test with what is the best or what you feel is most efficient.

---
Tags: opengl, directx, rendering, state
---


title: Anti-Aliasing in Java

text:
# Question
Title: Anti-Aliasing in Java
In my game I want to have the different anti-aliasing option like: none, x2, x4, x8 and x16. I know that you can use anti-aliasing with `Graphics2D` in the way below bu is there any way that I can use the different levels of anti-aliasing (x2, x4, x8 and x16)?.

```
RenderingHints rh = new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHints(rh);

```

# Answer
> 4 votes
I don't know much about java.awt but from the documentation I can tell you this:

The antialiasing option you are using does not use multiple samples like MSAA and thus does not support the MSAA x2, x4 ... sample counts. The antialiasing method of awt blends the edge pixels with the destination surface by using the exact coverage of the target pixel as the blend factor. The result should be superior even to x16 MSAA but requires all object to be rendered ordered from back to front. MSAA holds multiple samples per pixel and allows rendering in any order as this is required for most 3d scenes.

Keep in mind that the anti aliasing method of awt only influences rendering of geometry edges not of textures. For these you need to use texture filtering methods like KEY\_INTERPOLATION -\> VALUE\_INTERPOLATION\_BILINEAR.

---
Tags: java, graphics, rendering, antialiasing
---


title: Getting correct direction of the Car

text:
# Question
Title: Getting correct direction of the Car
I am building a car racing game using the coordinate system in which I have enemies's cars and the player cars. I want to ask that what is the best way to find the the direction of enemies's cars so that they would facing the player's car and move towards the player's car.

# Answer
If you mean that you want the direction for the enemies to face so that they're looking at the player's car, it's literally just maths. You need to calculate the vector between the enemy and the player, and then normalise it so it's a direction. Code example:

```
Vector3 direction = Vector3.Normalise(player.position - enemy.position);

```
> 3 votes

---
Tags: ai, coordinates
---


# Question
Title: Bitmap vs. Vector Graphics: Building Sprites
I'm currently doing game development of my own I heard that bitmap is much cleaner than Vector graphics since it appear to show up ugly in pixel form? What's better shown in a 2D art form?

# Answer
> 0 votes
I think you should stay at bitmaps, since they are much easier to handle, especially for a beginner. For example, storing pixels are easier: it takes only 24 bits, or **maybe** 32 bits sometimes - but it means that it can display millions of colours.

---
Tags: sprites, art
---


title: GL ES: Fragment shader optimization

text:
# Question
Title: GL ES: Fragment shader optimization
**Summary:** I get FPS slowdown as soon as I try to tint the sprites (i.e: multiply texture with color in the fragment shader)

**Details:**

Hardware: iPod touch 4

I am drawing 700 sprites on the screen using glDrawArrays. And yes I am batching all of these in a single draw call. Following shows Vertex data structure:

```
struct Vertex {
    float Position[2];
    float Color[4];
    float Texture[2];
};

```

Yes I am sending colour with each vertex because I selectively need to tint some sprites but not others. Following is the fragment shader I am using:

```
varying lowp vec2 TexCoord;
uniform sampler2D TextureSampler;

void main(void)
{
    gl_FragColor = texture2D( TextureSampler, TexCoord );
}

```

Till now it is working GREAT, giving me full 60 FPS !!!

BUT

As soon as I change the fragment shader to the following (to allowing tinting):

```
varying lowp vec4 DestinationColor;
varying lowp vec2 TexCoord;
uniform sampler2D TextureSampler;

void main(void)
{
    gl_FragColor = texture2D( TextureSampler, TexCoord ) * DestinationColor;
}

```

Using following 64x64 png texture containing alpha channel, rendering with glEnable(GL\_BLEND):

The performance drops to 47 FPS only due to this single change {just by multiplication with **ONE** vector} (FPS measured using xcode instruments and OpenGL detective). Any ideas what is going on ?

Thanks.

**Edit:**

I've also tried stripping off per vertex color attribute:

```
struct Vertex {
    float Position[2];
    float Texture[2];
};

```

And modifying the fragment shader as follows:

```
precision lowp float;
varying lowp vec2 TexCoord;
uniform sampler2D TextureSampler;

void main(void)
{
    gl_FragColor = texture2D( TextureSampler, TexCoord ) * vec4(1.0,0.0,0.0,1.0);
}

```

It is running at 52 FPS for 700 sprites (a gain of only 5 FPS). So this is not interpolation, seems like the multiplication is extremely expensive. Just this ONE multiplication?

# Answer
I don't think the performance problem is happening on the multiplication, but on the *interpolation* of your `DestinationColor` across the triangles, between vertex and fragment shaders. You have four `float`s to interpolate between tree vertices, for each fragment for each sprite.

For 700 sprites 64x64 pixels each, this is 11468800 additional operations *per frame* that you're asking the GPU to perform. It's quite possible that you will be missing some vsyncs, and therefore dropping to 40-ish FPS.

If you want each vertex to have a different color, so you can have gradients for each sprite, you're out of luck. There's also some other tricks you may want to try, but I think this is not the case.

Since what you seem to be doing is tinting each sprite, you could demote your `DestinationColor` to a `uniform`, use it directly in the fragment shader, and change it for each call. That way no interpolations will take place. You will lose the entire batching, but you may be able to batch a bit if you sort them by color.
> 2 votes

---
Tags: performance, opengl-es2, optimization, frame-rate, fragment-shader
---


title: When to use GameComponents?

text:
# Question
Title: When to use GameComponents?
I know what it is and I'm using it as a frame counter for example. But when should I use it?

Does it make sense to say "I make all the input handling happen in a gamecomponent"? Is it flexible enough to add and remove fast in runtime? I see I can set the update order and draw order, but I guess to keep track of it an enum should be best like "GamePadInput = 0" or "MessageBox = 100".

Or should I just design simple, for example when I want to determinate if a messagebox is open checking "if (MessageBox.Active)" and then manually updating/drawing?

I'm a bit confused and can't decide what to do. I don't want to start designing the game and see later "oops". Maybe you can help me out :)

# Answer
I've got a big, somewhat controversial discussion over here about why Game Components are "bad".

The most annoying thing about `GameComponent`, for me, is that it *looks* really important. It *looks* like a first-class part of the XNA API - like `Vector3` or `SoundEffect` \- but they're actually not (everything in the `Game` assembly is technically optional).

So many an inexperienced developer (and a few intermediate ones who, frankly, have no taste) will come along thinking that implementing things with `GameComponent` is ***The Way*** to architect a game. It's not. And often they end up tying themselves up in knots to try and squash their code into a `GameComponent` shaped box.

So, to answer your question, **when *should* you use `GameComponent`?**

The "correct", "I am an experienced software engineer and know what I'm doing" answer is that you should probably only use `GameComponent` for its intended purpose: creating extremely loosely-coupled drag-and-drop style components to share between different games and different developers.

`GameComponent` (and its friend `DrawableGameComponent`) were designed to this exact thing. No more and no less.

Now, that being said, you can "fudge" this a little. If you wanted to explore the architectural possibilities, you could (as Maik in comments suggests) use `GameComponent` as some generic list for retaining game objects. However you will probably *very* quickly find that you have trouble with, for example, trying to get objects into your `Draw` or `Update` methods.

It is at this point that you should let go of `GameComponent` and take the few minutes to throw together your own actor/game-object/component base class and make a list of those. It really is a handful of lines of code.

(For some components you could just remove the base class completely and call `Draw` and `Update` directly. In fact, for some components - especially unique ones that have a fixed position in the draw/update order - this is often superior, as it removes a layer of indirection from your code.)

See also this answer on architecture.
> 3 votes

---
Tags: xna, c#, architecture, game-component
---


# Question
Title: Hexagon collision detection for fast moving objects?
A object has a position and a speed vector. Usually only the position is used to check if two objects collide, this is problematic for very fast moving objects as it can happen that the object moves so fast that it is in front of the first object in the first collision check, and behind it in the second collision check.

Now there is also line based collision checks, in which you only check if the movement vector of each object intersects with the bounding-box of the other one. This can be seen as a expansion of a point. This only works though if the fast moving object is really small.

So my idea is, instead of expanding a point, why not expanding a rectangle? This results in a Hexagon.

Now, so far so good. **But how do I actually check if two Hexagons of this kind intersect?** Note that these are very specific Hexagon's.

**Bonus Question**: Is it possible to calculate where exactly (or rather after how much time) the collision happened? This could be very useful to detect what really happened, like where and with how much power and to simulate how they moved in the time between the collision and the end of the frame.

# Answer
> 35 votes
The solution is actually simpler than expected. The trick is to use Minkowski subtraction before your hexagon technique.

Here are your rectangles A and B, with their velocities `vA` and `vB`. Note that `vA` and `vB` aren't actually velocities, they are the **distance** traveled during one frame.

Now replace rectangle B with a point P, and rectangle A with rectangle C = A+(-B), which has dimensions the sum of the dimensions of A and B. The Minkowski addition properties state that collision between the point and the new rectangle occur if and only if collision between the original two rectangles occur:

But if rectangle C moves along vector `vA`, and point P moves along vector `vB`, a simple change of reference frame tells us it is the same as if rectangle C was still, and point P moved along vector `vB-vA`:

You can then use a simple box-segment intersection formula to tell where the collision occurs in the new reference frame.

The last step is to move back to the proper reference frame. Just divide the distance traveled by the point until the circled intersection by the length of vector `vB-vA` and you will get a value `s` such that `0 < s < 1`. The collision happens at time `s * T` where `T` is the duration of your frame.

**Comment by madshogo**:
One HUGE advantage of this technique over the one in Mr Beast's own answer is that if there's no rotation, then the "Minkowski subtraction" *A+(-B)* can be computed once for *all the subsequent timesteps*!

So the only algorithm that takes time in all this (Minkowski sum, complexity *O(mn)* where *m* is the number of vertices in *A* and *n* the number of vertices in *B*) can be used only once, effectively making collision detection a constant-time problem!

Later, you can throw the sum away once you know for sure that *A* and *B* are in different parts of your scene (of your quadtree?) and won't collide anymore.

In contrast, Mr Beast's method requires quite a lot of computations at each time step.

Also, for axis-aligned rectangles, *A+(-B)* can be computed much more simply than by actually computing all the sums, vertex by vertex. Just expand *A* by adding the height of *B* to its height and the width of *B* to its width (one half on each side).

But all this only works if neither *A* nor *B* is rotating and if both are convex. If rotation there is or if you use concave shapes then you must use swept volumes/areas.
**end of comment**

# Answer
> 17 votes
First of all, in the case of axis-aligned rectangles, Kevin Reid's answer is the best and the algorithm is the fastest.

Second, for simple shapes, use relative velocities (as seen below) and the separating axis theorem for collision detection. It *will* tell you whether a collision happens in the case of linear motion (no rotation). And if there's rotation, you need a small timestep for it to be precise. Now, to answer the question:

---

# How to tell in the general case whether two convex shapes intersect?

I'll give you an algorithm that works for all convex shapes and not just hexagons.

Suppose *X* and *Y* are two convex shapes. They intersect if and only if they have a point in common, i.e. there is a point *x  X* and a point *y ∈ Y* such that *x = y*. If you regard the space as a vector space, then this amounts to saying *x - y = 0*. And now we get to this Minkowski business:

The Minkowski sum of *X* and *Y* is the set of all *x + y* for *x ∈ X* and *y ∈ Y*.

**An example for X and Y**

**X, Y and their Minkowski sum, X+Y**

Supposing *(-Y)* is the set of all *-y* for *y ∈ Y*, then given the previous paragraph, ***X* and *Y* intersect if and only if *X + (-Y)* contains *0*, that is, the origin**.

Side remark: why do I write *X + (-Y)* instead of *X - Y* ? Well, because in mathematics, there is an operation called the Minkowski difference of *A* and *B* which is sometimes written *X - Y* yet has nothing to do with the set of all *x - y* for *x ∈ X* and *y ∈ Y* (the real Minkowski difference is a little more complex).

So we'd like to compute the Minkowski sum of *X* and *-Y* and to find whether it contains the origin. The origin is not special compared to any other point, so that to find whether the origin is within a certain domain, we use an algorithm that could tell us whether any given point belongs to that domain.

The Minkowski sum of *X* and *Y* has a cool property, which is that if *X* and *Y* are convex, then *X+Y* is too. And finding whether a point belongs to a convex set is *much* easier than if that set were not (known to be) convex.

We can't possibly compute all of the *x - y* for *x ∈ X* and *y ∈ Y* because there are an infinity of such points *x* and *y*, so hopefully, since *X*, *Y* and *X + Y* are convex, we can just use the "outermost" points defining the shapes *X* and *Y*, which are their vertices, and we'll get the outermost points of *X + Y*, and also some more.

These additional points are "surrounded" by the outermost ones of *X + Y* so that they do not contribute to defining the newly obtained convex shape. We say that they don't define the "convex hull" of the set of points. So what we do is that we get rid of them in preparation for the final algorithm that tells us whether the origin is within the convex hull.

**The convex hull of X+Y. We have removed the "inside" vertices.**

We therefore get

## A first, naive algorithm

```
boolean intersect(Shape X, Shape Y) {

  SetOfVertices minkowski = new SetOfVertices();
  for (Vertice x in X) {
    for (Vertice y in Y) {
      minkowski.addVertice(x-y);
    }
  }
  return contains(convexHull(minkowski), Vector2D(0,0));

}

```

The loops obviously have complexity *O(mn)* where *m* and *n* are the number of vertices of each shape. The `minkoswki` set contains *mn* elements at most. The `convexHull` algorithm has a complexity that depends on the algorithm you used, and you can aim for *O(k log(k))* where *k* is the size of the set of points, so in our case we get *O(mn log(mn))*. The `contains` algorithm has a complexity that is linear with the number of edges (in 2D) or faces (in 3D) of the convex hull, so it really depends on your starting shapes, but it won't be greater than *O(mn)*.

I'll let you google for the `contains` algorithm for convex shapes, it's a pretty common one. I may put it here if I have the time.

---

# But it's collision detection we're doing, so we can optimize that a lot

We originally had two bodies *A* and *B* moving without rotation during a timestep *dt* (from what I can tell by looking at your pictures). Let's call *vA* and *vB* the respective speeds of *A* and *B*, which are constant during our timestep of duration *dt*. We get the following:

and, as you point out in your pictures, these bodies do sweep through areas (or volumes, in 3D) as they move:

and they end up as *A'* and *B'* after the timestep.

To apply our naive algorithm here, we would only have to compute the swept volumes. But we're not doing this.

In the reference frame of *B*, *B* doesn't move (duh!). And *A* has a certain velocity *with respect to B* that you get by computing *vA \- vB* (you can do the converse, compute the relative velocity of *B* in the reference frame of *A*).

**From left to right: velocities in the base reference frame; relative velocities; computing relative velocities.**

By regarding *B* as immobile in its own reference frame, **you only have to compute the volume that *A* sweeps through as it moves during *dt* with its relative velocity *vA \- vB***.

This decreases the number of vertices to be used in the Minkowski sum computation (sometimes greatly).

Another possible optimization is at the point where you compute the volume swept by one of the bodies, let's say A. You don't have to translate all of the vertices making up A. Only those that belong to edges (faces in 3D) whose outer normal "face" the direction of the sweeping. Surely you had noticed that already when you computed your swept areas for the squares. You can tell whether a normal is towards the sweeping direction using its dot product with the sweeping direction, which has to be positive.

The last optimization, that has nothing to do with your question regarding intersections, is really useful in our case. It uses those relative velocities we mentioned and the so-called separating axis method. Surely you know about it already.

Suppose you know the radii of *A* and *B* with respect to their centers of mass (that is to say, the distance between the center of mass and the vertex farthest from it), like this:

A collision can occur only if it is possible that the bounding circle of *A* meet that of *B*. We see here that it won't, and the way to tell the computer that is to compute the distance from *CB* to *I* as in the following picture and make sure it's bigger than the sum of the radii of *A* and *B*. If it's bigger, no collision. If it's smaller, then collision.

This doesn't work very well with shapes that are rather long, but in the case of squares or other such shapes, it's a very good heuristic *to rule out collision*.

The separating axis theorem applied to *B* and the volume swept by *A*, however, does tell you whether the collision happens. The complexity of the associated algorithm is linear with the sum of the numbers of vertices of each convex shape, but it is less magical when comes the time to actually handle the collision.

## Our new, better algorithm that uses intersections to *help detect* collisions, but still not as good as the separating axis theorem for *actually telling whether* a collision happens

```
boolean mayCollide(Body A, Body B) {

  Vector2D relativeVelocity = A.velocity - B.velocity;
  if (radiiHeuristic(A, B, relativeVelocity)) {
    return false; // there is a separating axis between them
  }

  Volume sweptA = sweptVolume(A, relativeVelocity);
  return contains(convexHull(minkowskiMinus(sweptA, B)), Vector2D(0,0));

}

boolean radiiHeuristic(A, B, relativeVelocity)) {
  // the code here
}

Volume convexHull(SetOfVertices s) {
  // the code here
}

boolean contains(Volume v, Vector2D p) {
  // the code here
}

SetOfVertices minkowskiMinus(Body X, Body Y) {

  SetOfVertices result = new SetOfVertices();
  for (Vertice x in X) {
    for (Vertice y in Y) {
      result.addVertice(x-y);
    }
  }
  return result;

}

```

# Answer
> 2 votes
I don't think using the 'hexagon' is all that helpful. Here's a sketch of a way to get exact collisions for axis-aligned rectangles:

Two axis-aligned rectangles overlap if and only if their X coordinate ranges overlap and their Y coordinate ranges overlap. (This can be seen as a special case of the separating axis theorem.) That is, if you project the rectangles onto the X and Y axes you have reduced the problem to two line-line intersections.

Compute the time *interval* over which the two lines on one axis intersect (e.g. it starts at time (current separation of objects / relative approaching velocity of objects)), and do the same for the other axis. If those time intervals overlap, then the earliest time within the overlap is the time of collision.

# Answer
> 1 votes
I don't think there is an easy way to calculate the collision of polygons with more sides than a rectangle. I would break it down into primitive shapes like lines and squares:

```
function objectsWillCollide(object1,object2) {
    var lineA, lineB, lineC, lineD;
    //get projected paths of objects and store them in the 'line' variables

    var AC = lineCollision(lineA,lineC);
    var AD = lineCollision(lineA,lineD);
    var BC = lineCollision(lineB,lineC);
    var BD = lineCollision(lineB,lineD);
    var objectToObjectCollision = rectangleCollision(object1.getRectangle(), object2.getRectangle());

    return (AC || AD || BC || BD || objectToObjectCollision);
}

```

**Note** how I ignore the start-state of each object as that should have been checked during the previous calculation.

# Answer
> 0 votes
## Seperate Axis Theorem

The Seperate Axis Theorem says *"If we can find a axis on which two convex shapes don't intersect then the two shapes are not intersecting"* or more practicable for IT:

### "Two convex shapes only intersect if they intersect on all possible axes."

For axis aligned rectangles there are exactly 2 possible axes: x and y. But the theorem isn't limited to rectangles, it can applied to any convex shape by just adding the other axes on which the shapes could intersect. For more details on the topic check out this tutorial by the developer of N: http://www.metanetsoftware.com/technique/tutorialA.html#section1

Implemented it looks like this:

```
axes = [... possible axes ...];
collision = true;
for every index i of axes
{
  range1[i] = shape1.getRangeOnAxis(axes[i]);
  range2[i] = shape2.getRangeOnAxis(axes[i]);
  rangeIntersection[i] = range1[i].intersectionWith(range2[i]);
  if(rangeIntersection[i].length() <= 0)
  {
    collision = false;
    break;
  }
}

```

Axes can be as represented as normalized vectors.

A range is a 1-Dimensional line. The start should be set to the smallest projected point, the end to the largest projected point.

## Applying it to the "sweeped" Rectangle

The hexagon in the question is produced by "sweeping" the AABB of the object. Sweeping adds exactly one possible collision axis to any shape: the movement vector.

```
shape1 = sweep(originalShape1, movementVectorOfShape1);
shape2 = sweep(originalShape2, movementVectorOfShape2);

axes[0] = vector2f(1.0, 0.0); // X-Axis
axes[1] = vector2f(0.0, 1.0); // Y-Axis
axes[2] = movementVectorOfShape1.normalized();
axes[3] = movementVectorOfShape2.normalized();

```

So far so good, now we can already check if the two hexagon's intersect. But it get's even better.

This solution will work for any convex shapes (for example triangles) and any sweeped convex shapes (for example sweeped octagons). However the more complex the shape the less effective it will be.

---

## Bonus: Where the magic happens.

As I said the only additional axes are the movement vectors. The movement is time multiplied by speed, so in a sense they aren't just space axes, **they are time-space axes.**

This means we can derive the time in which the collision could have happened from these two axes. For this we need to find the intersection between the two intersections on the movement axes. Before we can do this we need to normalize both ranges though, so we can actually compare them.

```
shapeRange1 = originalShape1.getRangeOnAxis(axes[2]);
shapeRange2 = originalShape2.getRangeOnAxis(axes[3]);
// Project them on a scale from 0-1 so we can compare the time ranges
timeFrame1 = (rangeIntersection[2] - shapeRange1.center())/movementVectorOfShape1.project(axes[2]);
timeFrame2 = (rangeIntersection[3] - shapeRange2.center())/movementVectorOfShape2.project(axes[3]);
timeIntersection = timeFrame1.intersectionWith(timeFrame2);

```

When I asked this question I kinda already accepted the compromise that there will be a few rare false positives with this method. But I was wrong, by checking this time intersection we can test if the collision "actually" happened and we can sort those false positives out with it:

```
if(collision)
{
  [... timeIntersection = see above ...]
  if(timeIntersection.length() <= 0)
    collision = false;
  else
    collisionTime = timeIntersection.start; // 0: Start of the frame, 1: End of the frame
}

```

*If you notice any errors in the code examples let me know, I haven't implemented it yet and thus was not able to test it.*

# Answer
> -2 votes
As long as the swept areas are both closed (no gaps in the boundary formed by the edge-lines), the following will work (just reduce your collision tests to line-line and point-rect/point-tri):

1. **Do their edges touch?**(line-line collisions) Check whether any edge-line of a swept area intersects with any edge-line of the other swept area. Each swept area has 6-sides.
2. **Is the small one inside the big one?** (Use axis aligned shapes (point-rect & point-tri)) Re-orient (rotate) the swept-areas so that the larger one is axis-aligned and test whether the smaller one is internal (by testing whether any corner points (should be all or none) are within the axis-aligned swept area). This is done be decomposing your hex into tris and rects.

Which test you do first depends on the likelihood of each (do the most commonly occurring one first).

You may find it easier to use a swept bounding circle (capsule rather than hex) because it's easier to split it into two half-circles and a rect when it is axis-aligned. ..I'll let you draw the solution

---
Tags: 2d, collision-detection, geometry, collision-resolution, aabb
---


# Question
Title: How can I implement an asset update/download in a libgdx application?
I am building a game based on libGdx and I want to be able to check for and download updated assets at some point before the player starts playing. The game is being built for PC and for Android.

I haven't been able to find much on downloading assets. It seems libGdx assumes all assets will be packaged with the game or already on "external" storage and available for the AssetManager.

So far, the best option I've found is setting up updating code prior to starting the libGdx application.

How can I have my assets download while the libGdx application is running? Possibly to allow some interaction while waiting, or progressive asset downloads allowing limited game play. My goal is to allow for dynamic updates to assets, and to allow users to get into the game quicker. Especially new players, I don't want them waiting on a download screen before they see anything of the actual game.

# Answer
> 2 votes
As Adam suggested, you can write your own custom loader which could implement a network connection to any type of server which could download assets during runtime and serve them up.

Just implement the file loading interface it provides and request a url as a string for the asset name in the overriden load function and pass that to your downloader. Then you can simply make regular load function calls throughout your code.

---
Tags: libgdx, assets, asset-management
---


title: Play .mp3 with Craftyjs

text:
# Question
Title: Play .mp3 with Craftyjs
I want to play .mp3 sound files in a game I built with Crafty.js. Is this possible without converting the sound file?

# Answer
This really depends on the browser you're using (not all support mp3). I'd recomend using mp4 audio. This should soon be supported by all popular browsers out of the box (actually I think even the Firefox stable supports it by now; that would mean all of them).
> 1 votes

---
Tags: javascript, sound, crafty
---


title: Confusion with Libgdx UI

text:
# Question
Title: Confusion with Libgdx UI
I've started with Libgdx and am currently stumbling about trying to understand how to set up the interface. I have generated the base projects in Eclipse ( \< proj-name \>,\< proj-name \>-android, \< proj-name \>-desktop, \< proj-name \>-html), and can get the program to display a simple background, play a looping sound file, and draw a tank. I have been having some problems implementing the UI though.

I want to make a collapsible interface bar at the bottom of the screen that would contain buttons for movement, and selecting weapons. I'm confused since there appears to be several ways of doing this and the documentation (or tutorials explaining it) tend to be obsolete. How would one go about this? Use a stage for the bar and actors for the widgets? I'm a little lost on this.

# Answer
> 1 votes
You can use `scene2d.ui`. The biggest challenge is finding examples/documentation to match the version you are using.

Some links to get you started:

Also be sure to look at the tutorials listed at http://libgdx.badlogicgames.com/documentation.html

---
Tags: libgdx, ui-design
---


# Question
Title: colliding 2 moving and rotating sprites in xna 2d
I recently started making a game in windows phone XNA, I have a rocket in the middle that I can rotate and has a thrust to speed up in the direction it is facing and meteors coming out. The point is to survive as long as you can and avoid collision with the meteors. I can't manage to implement the collision between two moving and rotating sprites which are the rocket and a random meteor. I've seen rectangular collision which to me appears bad but maybe I am coding it a bit wrong and the pixel collision is way complicated :/ any help would be appreciated, thanks in advance :)

# Answer
> 1 votes
You're right on that main point: **pixel collision is way complicated**. Often times, it's going to be far, far more effort than it's worth. You'll likely have to program a form of collision that's not 100% the same as the visuals you draw. A rocket sounds like something that could very easily use rectangle collision detection. However, a random guess suggests the meteors are more circular. Actually, **circle** collision detection is also pretty basic; for instance, circle-to-circle collision just involves calculating the distance between two objects, and comparing their radii (plural of radius)

This involves a bit of math; I think for the progress of your game development skills, it would be good to try to understand what's happening here, or even look up some textbooks on the subject; but if you get a basic grasp of what goes in and what comes out, you may just be able to drop it into your code...

https://stackoverflow.com/questions/2443845/the-maths-for-2d-collision-detection-between-an-obb-and-a-circle

(Oriented means having some form of rotation. Bounding box is a fancy name for a rectangle.)

---
Tags: xna, windows-phone-7
---


title: center point of a text?

text:
# Question
Title: center point of a text?
i'm drawing a text using a spritefont and the draw.string function of the spritebatch object. in some point, i need to augment the size of the text, so i use a variable to scale it. all this is working fine, but i need to find the center of the text to use as origin to make the effect look like i want. how can i find that center point of a text? when i use textures its easy because i just take half the texture width and height, but with a spritefont, i dont have any idea of how to proceed. Thanks.

# Answer
> 8 votes
You need to use SpriteFont.MeasureString.

```
Vector2 textSize = mySpriteFont.MeasureString("Hello World");
Vector2 center = textSize / 2;

```

The x component of `textSize` represents the width of the measured string while the y component represents the height.

---
Tags: xna-4.0, spritebatch, text
---


# Question
Title: Why do we move the world instead of the camera?
I heard that in an OpenGL game what we do to let the player move is not to move the camera but to move the whole world around.

For example here is an extract of this tutorial: OpenGL View matrix

> In real life you're used to moving the camera to alter the view of a certain scene, in OpenGL it's the other way around. The camera in OpenGL cannot move and is defined to be located at (0,0,0) facing the negative Z direction. That means that instead of moving and rotating the camera, the world is moved and rotated around the camera to construct the appropriate view.

Why do we do that?

# Answer
**Why ?**

Because, A camera represents a projection view.

> But in case of 3D Camera (Virtual Camera), camera moves instead of the world. I have made a detailed explanation later of this answer.

**Understanding Mathematically**

Projection View moves around space and change its orientation. The first thing to notice is that the desired projection on the screen does not change with view direction.

For this reason, we transform other things to get the desired projection.

**Understanding From http://opengl.org**

To give the appearance of moving the camera, your OpenGL application must move the scene with the inverse of the camera transformation. where OpenGL is concerned, there is no camera. More specifically, the camera is always located at the eye space coordinate (0, 0, 0)

**Understanding From http://open.gl**

Also want to share the following lines from **View matrix** portion of http://open.gl/transformations

> To simulate a camera transformation, you actually have to transform the world with the inverse of that transformation. Example: if you want to move the camera up, you have to move the world down instead.

**Understanding by perspective**

In the real world, we see things in a way that is called "perspective".

Perspective refers to the concept that objects that are farther away appear to be smaller than those that are closer to you. Perspective also means that if you are sitting in the middle of a straight road, you actually see the borders of the road as two converging lines.

That’s perspective. Perspective is critical in 3D projects. Without perspective, the 3D world doesn't look real.

While this may seem natural and obvious, it's important to consider that when you create a 3D rendering on a computer you are attempting to simulate a 3D world on the computer screen, which is a 2D surface.

Imagine that behind the computer screen there is a real 3D scene of sorts, and you are watching it through the "glass" of your computer screen. Using perspective, your goal is to create code that renders what gets "projected" on this "glass" of your screen as if there was this real 3D world behind the screen. The only caveat is that this 3D world is not real…it's just a mathematical simulation of a 3D world.

So, when using 3D rendering to simulate a scene in 3D and then projecting the 3D scene onto the 2D surface of your screen, the process is called perspective projection.

Begin by envisioning intuitively what you want to achieve. If an object is closer to the viewer, the object must appear to be bigger. If the object is farther away, it must appear to be smaller. Also, if an object is traveling away from the viewer, in a straight line, you want it to converge towards the center of the screen, as it moves farther off into the distance.

**Translating perspective into math**

As you view the illustration in following figure , imagine that an object is positioned in your 3D scene. In the 3D world, the position of the object can be described as xW, yW, zW, referring to a 3D coordinate system with the origin in the eye-point. That’s where the object is actually positioned, in the 3D scene beyond the screen.

As the viewer watches this object on the screen, the 3D object is "projected" to a 2D position described as xP and yP, which references the 2D coordinate system of the screen (projection plane).

To put these values into a mathematical formula, I'll use a 3D coordinate system for world coordinates, where the x axis points to the right, y points up, and positive z points inside the screen. The 3D origin refers to the location of the viewer's eye. So, the glass of the screen is on a plane orthogonal (at right angles) to the z-axis, at some z that I’ll call zProj.

You can calculate the projected positions xP and yP, by dividing the world positions xW, and yW, by zW, like this:

> xP = K1 * xW / zW
> yP = K2 * yW / zW

K1 and K2 are constants that are derived from geometrical factors such as the aspect ratio of your projection plane (your viewport) and the "field of view" of your eye, which takes into account the degree of wide-angle vision.

You can see how this transform simulates perspective. Points near the sides of the screen get pushed toward the center as the distance from the eye (zW) increases. At the same time, points closer to the center (0,0) are much less affected by the distance from the eye and remain close to the center.

This division by z is the famous "perspective divide."

Now, consider that an object in the 3D scene is defined as a series of vertices. So, by applying this kind of transform to all vertices of geometry, you effectively ensure that the object will shrink when it's farther away from the eye point.

**Other Important Cases**

* In case of 3D Camera (Virtual Camera), camera moves instead of the world.

To get a better understanding of 3D cameras, imagine you are shooting a movie. You have to set up a scene that you want to shoot and you need a camera. To get the footage, you'll roam through the scene with your camera, shooting the objects in the scene from different angles and points of view.

The same filming process occurs with a 3D camera. You need a "virtual" camera, which can roam around the "virtual" scene that you have created.

Two popular shooting styles involve watching the world through a character's eyes (also known as a first person camera) or pointing the camera at a character and keeping them in view (known as a third person camera).

This is the basic premise of a 3D camera: a virtual camera that you can use to roam around a 3D scene, and render the footage from a specific point of view.

**Understanding world space and view space**

To code this kind of behavior, you'll render the contents of the 3D world from the camera's point of view, not just from the world coordinate system point of view, or from some other fixed point of view.

Generally speaking, a 3D scene contains a set of 3D models. The models are defined as a set of vertices and triangles, referenced to their own coordinate system. The space in which the models are defined is called the model (or local) space.

After placing the model objects into a 3D scene, you'll transform these models' vertices using a "world transform" matrix. Each object has its own world matrix that defines where the object is in the world and how it is oriented.

This new reference system is called "world space” (or global space). A simple way to manage it is by associating a world transform matrix to each object.

In order to implement the behavior of a 3D camera, you'll need to perform additional steps. You'll reference the world—not to the world origin—but to the reference system of the 3D camera itself.

A good strategy involves treating the camera as an actual 3D object in the 3D world. Like any other 3D object, you use a "world transform" matrix to place the camera at the desired position and orientation in the 3D world. This camera world transform matrix transforms the camera object from the original, looking forward rotation (along the z-axis), to the actual world (xc, yc, zc) position, and world rotation.

Following figure shows the relationships between the World (x, y, z) coordinate system and the View (camera) (x', y', z') coordinate system.
> 79 votes

# Answer
Mahbubar R Aaman's answer is quite correct and the links he provides explain the math accurately, but in the event you want a less technical/mathy answer, I'll try a different approach.

Positions of objects in the real world and the game world are defined with some coordinate system. A coordinate system gives meaning to position values. If I tell you that I'm at "100,50" that won't help you unless you know what those numbers mean (are they miles, kilometers, latitude and longitude, etc.). If they're Cartesian coordinates (the "normal" kind of coordinates), you also need to know what origin they're relative to; if I just say "I'm 100 feet to the East," you need to know "East of *what*," which is called the coordinate origin.

There's an easy way to think of this. You could tell someone "the train station is 3 kilometers north and 1.5 kilometers east of the southwest corner of the city." You could also tell someone "the train station is 1 mile directly north of where I am right now." Both coordinates are correct and identify the location of the same landmark, but they are measured from a different origin, and hence have different numeric values.

In a 3D application, there is generally a "world" coordinate system, which is used to represent the position of the camera and the objects in the game, measured with Cartesian coordinates with some arbitrary designer-specified origin (generally the center of whatever level or map you're playing). Other coordinate systems exist in the game, such as the Cartesian coordinate system with the camera at the origin. You can define any new coordinate system any way you want at any time you want, and this is done very frequently in 3D simulation to make things easier for the math.

The algorithm that actually renders an individual triangle onto your screen works in a particular way, and so it is not convenient to directly work with the world coordinates when rendering. The math is not really set up to deal with information like "the object is 100 units to the right of the center of the world." The math instead wants to work with "the object is directly in front of the camera, and 20 units away." Hence, an additional step is added to the rendering math to take object world positions and translate them from into the camera coordinate system.

Of course the camera has a position and an orientation as well. So if an object is at position 20,100,50 and the camera is at position 10,200,-30, the object's position relative to the camera is 10,100,80 (the object's position minus the camera's position). When the camera moves in a game, that camera position in world coordinates is moved exactly like you'd expect.

Note that the objects are *not* moved; they are staying right where they were before. However, their position is now being expressed relative to a different coordinate origin. The object's world coordinates only move if the object itself moves, but its camera coordinates also change whenever the camera moves, since they are relative to the camera's position.

Also note that the description from the tutorial you're quoting is a simplified explanation and not necessarily an accurate description of what OpenGL does. I don't think the author of the article failed to understand that; the author just tried to use a simplified analogy that in this case caused confusion rather than eliminating it.

If it helps further to understand why the math cares about camera coordinates, try this exercise: hold up your hands touching your thumbs and forefingers together to make a rectangle (let's call that a "viewport") and look around at the room you're in. Find an object, and look at it, then look around it but not directly at it. When you do so, ask yourself, "where is the object in my viewport?" That object has some specific real-world longitude and latitude that you can use to pinpoint it's location on Earth, but that doesn't tell you anything about what you're seeing. Saying "the object is in the upper left corner of my viewport and looks to be about 2 meters away" tells you quite a bit, though. You've created a coordinate system relative to your head and the direction you're looking that defines where an object according to your vision. That's basically what the triangle rasterizer part of OpenGL/Direct3D needs, and that's what the math requires that object positions and orientation be transformed from their convenient world coordinates into camera coordinates.
> 31 votes

# Answer
Just adding to the other two (excellent) answers some further elaboration on a point that Mahbubur R Aaman touched on: "there is no camera".

This is quite true and represents a failing of the common "camera" analogy, because the "camera" does not actually exist. It's important to realise that the camera analogy is just exactly that - an analogy. It doesn't describe (or pretend to describe) the way things actually work behind the scenes.

So view (pun intended) it as being a means of helping you get your head round this stuff if it's new to you, but always remember that it's just a helper and not any kind of description of the way things actually are.

Now, you have two classes of object that are relevant here: the view point and everything in the world. You want to move the view point closer to some objects, but for this movement the end result is the very same whether the view moves closer to the objects or whether the objects move closer to the view. All that you're doing is changing the distance between them; since the current distance is X and you want the new distance to be Y, it doesn't matter which you move, just so long as that after the move the new distance is Y. So you're not really moving at all, you're just changing a distance. (I didn't mean to come over all Einstein in this... honest!)

But, however, since the camera does not exist, the only thing you can change the distance of is the objects. So you change the distance of the objects and out comes the very same result. Since all objects go through transforms *anyway*, this is no more or less expensive.

A simpler mathematical explanation may help more. Let's pretend that all coordinates are 1D - the viewpoint is at 0, your objects are at 4 and you want the viewpoint to go to 3. That means that the distance between them will change from 4 (4 - 0) to 1 (4 - 3). But since the camera does not exist you can't change that 0; it's always going to be 0. So instead of adding 3 to 0 (which you cannot do) you subtract 3 from 4 (which you can do) - the objects are now at 1, and the end result is the very same - distance between viewpoint and objects is 1.
> 15 votes

# Answer
Moving the camera or moving the world are two equally valid choices which both amount to the same thing. At the end of the day you are changing from one coordinate system to the other. The above answers are correct but which way you visualise it are two sides of the same coin. Transformations can go either way - they are just the inverse of each other.

Part of the rendering process does convert from world coordinates to eye coordinates. However an easy way to model this is with a virtual camera object in your application. The camera can represent both the projection matrix (which is responsible for the perspective effect) and also the view matrix which is used to convert from world space to eye space.

So although the vertex shader uses the view matrix to change the coordinates of your geometry to eye space, it is often easier to think about a camera object moving around your virtual world which as it moves re-calculates the view matrix.

So in your application, you move the camera in world coords, update the camer'as view matrix, pass the new view matrix to the vertex shader as a uniform or part of block, render your scene.
> 7 votes

# Answer
I would posit instead that it's a flawed analogy. At its most basic, "moving the camera" and "moving the world" are exactly the same mathematical construct - it's just that moving the world is somewhat easier to think about conceptually, especially when it comes to hierarchical transformations. Basically, you're moving the world around the camera only in that you're translating the world vertices into the camera's coordinate space - but this is a reversible affine transformation.

However, when you start to bring visibility determination into the mix, the LAST thing you want to do is to translate the entire world around the camera. Instead, in most cases (especially the classical case of fixed BSPs or the like) you're going to be using the camera's position within the world to query your visibility structures to determine which things are likely to be visible, and then only translate THOSE things into the camera's coordinate space.
> 6 votes

# Answer
I don't think that the claim is categorically true, as one only rarely "moves" the world coordinates in a game, but actually changes the coordinates of the virtual camera.

What the concept of camera actually does, is transform the finite viewing frustum -- that is a truncated pyramid with 8 corner points (or defined by intersection of 6 planes) to a unit cube, which represents the clip space in the final stages of openGL rendering pipeline.

In that sense the world is not moved, but one only calculates world coordinates in the coordinate system of the clip space.
> 4 votes

# Answer
Moving the camera or moving the world are two equally valid choices (and both are true). At the end of the day we are changing from one coordinate system to the other. Transformations can go either way - they are just the inverse of each other.
> 2 votes

# Answer
A lot of good answers here. I'll try to not repeat any of them. Sometimes it's easier to think of in terms of a camera, like how Direct3D does it (note: haven't played with a lot of post 9.0c)

"Moving the world" like in the Futurama sense that someone out there quoted is a very good way to look at it ("The engines don't move the ship at all. The ship stays where it is and the engines move the universe around it!"). This was actually quite common for 2D games. You literally had a viewport that you would have a hard time adjusting, and that was sometimes your video RAM or a UI Window. If OpenGL does it for those kind of reasons, eh, hard to tell.

You can certainly think of a 2D motion in terms of a camera as well, and just that kind of thinking process can make it easier to figure out effects.
> 2 votes

# Answer
There seems to be a whole lot of misunderstanding here, starting from the writers of OpenGL docs...

Let me quickly restore your sanity: **the world doesn't move**, it stays put. Whoever tries to implement the world as moving around the player will quickly run into trouble in the multiplayer mode. Not to mention that updating the positions of millions (or billions) of objects in the world at each player's move will make a rather slow gameplay...

So, what really happens there, and what's up with the quote?

Well, first of all you need to understand the concept of a coordinate system. Generally, you pick one point in the world and declare it to be the "origin", that is a point with coordinates (0,0,0). You also choose three "main" directions, which you call X, Y, and Z. Obviously, there are many ways to assign a coordinate system. Usually there is one "world coordinate system", in this system the world is stationary (more or less). In a game this system would be chosen by the level designer.

Now, it is also convenient to consider another coordinate system, tied to the player's eye. In this coordinate system the player is always at coordinates (0,0,0), and the world moves and rotates around him. Thus the quote is correct if you understand as being made *in the player's coordinate system*.

However the world doesn't operate in the player's coordinates, it operates in the world's coordinates. And where two coordinate systems are involved, there is always a way to transform one kind of coordinates into the other. In OpenGL this is done using a 4x4 view matrix.

Ultimately, when a player moves, the world remains stationary, while the player is moved. This is in the world coordinates, the way the objects are stored in your game. The player also has a view camera associated with him, and this camera similarly moves around the world (despite what the OpenGL docs seem to be saying). However, in order to show the world on the user's screen, the coordinates of all visible objects are translated into the player's coordinate system using a transformation matrix, and then additional projection is applied to create a perspective effect. In this player's coordinate system the world actually appears to move around the player. But it's just an extremely unhelpful and confusing way of thinking about it.
> 2 votes

---
Tags: opengl, camera, matrix, transformation, view
---


# Question
Title: Trouble with UV Mapping Blender => Unity 3
For some reason I am getting nasty grey edges around the edges of rendered 3D models that are not present in Blender.

I seem to be able to solve the problem by reducing the size of the UV coordinates within the part of the texture that is to be mapped. But this means that:

* I am wasting valuable texture space
* Loss of accuracy in drawn UV maps

Could I be doing something wrong, perhaps a setting in Unity that needs changing? I have watched countless tutorials which demonstrate Blender default generated UV coordinates with "Texture Paint" which are perfectly aligned in Unity.

Here is an illustration of the problem:

* *Left:* approximately 15 pixels of margin on each side of UV coordinates
* *Right:* Approximately 3 pixels of margin on each side of UV coordinates

**Note: Texture image resolution is 1024x1024**

# Answer
This apparently has to do with how MipMaps are generated, though, in personal experiments I could not reproduce your problem to quite the magnitude you have. My best guess is that you got a double-threat going on: Unity may not be importing the mesh at a high enough resolution, and the gradient color you have going on there may be calling more attention to it. Also consider that it may not be the texture at all, but a reflection effect for the material that you are using.

You may want to turn on interpolation in blender and go exploring with paint mode, to see if you don't have a UV error somewhere. Also, it seems like you have overlapping UV's, you should avoid that whenever possible, or at bare minimum make sure that they don't overlap perfectly.
> 1 votes

---
Tags: unity, graphics, textures, blender, uv-mapping
---