title: Maya 6 vs Maya 2013

text:
# Question
Title: Maya 6 vs Maya 2013
I have the entire "Learning Maya 6" books that I purchased back when Maya 6/6.5 was the hottest thing. I read some of the books but never finished the series. I don't know much about Maya or the field. I want to get back into the field but I have a concern.

My question: Would I be failing if I decided to use my old Maya 6 books and Maya 6.5 software? As opposed to ditching my old books and starting with Maya 2013 and online tutorials, videos, etc.?

# Answer
> 3 votes
I have used Maya in a production environment for several years as an artist, across multiple versions, and I have to say that learning a newer version of the program is going to be more beneficial than sticking to 6.5.

If you are truly serious about getting back into the program I would recommend that you shop around and find an updated textbook- the investment will pay off!

Although the fundamentals of the program have been stable since version 6.5, there have been many improvements to the user interface, the scripting editor, the render settings, better view-port previews and much more. Being aware of these differences is important.

Make sure to check out the 'Whats new in version X' website, for example this website for Maya 2011. Checking out these pages will assist you in making an informed decision about the software package you decide to learn.

In addition to the new improvements, bear in mind that many new plugins that you may wish to use with your work may not support older versions of Maya, and any plugins that do may no longer be supported by the people who wrote them.

Finally, assuming you want to use Maya in the workplace, learning an outdated package may mean that your skills won't be as appealing to a prospective employer, unless their pipeline is also built around older versions.

# Answer
> 2 votes
There's a third approach you didn't mention, and this is what I would recommend: Continue using your Maya 6 books but use the latest Maya software. Not *that* much has changed, especially in the fundamentals/basics. Just refer to online tutorials or the learning videos that come with Maya to fill you in on anything that's changed from what the book says.

For example, around then (I don't recall exactly which version) they changed the name of one crucial preferences window from Render Globals to Render Settings (or something like that). The preferences are all the same, you'd just need to know the changed name.

(btw I'm assuming your issue here is that ditching the old books and getting new ones would be expensive, because those books are expensive! if that's not your issue then absolutely go for the latest learning materials)

# Answer
> 1 votes
Failing? No, but you would be limiting yourself if you have access to Maya 2013 (which is expensive... not going to ask...). Also, it depends on what you are trying to achieve. Do you want to only make some models for games? If so, Maya 6 should work just fine. However, if you want to get into some of the more advanced CG topics (cloth, dynamics, sculpting, animation, etc.) and interop with other applications, Maya 201X is going to be your best bet.

If you don't need all the junk features that's in Maya, I would take a look at some cheaper specialty tools (such as modo for modeling).

---
Tags: 3d, maya
---


# Question
Title: UV Mapping in Autodesk Maya 2011 goes wrong
I'm always struggling with UV mapping, I'm still a student though. When I am creating a UV map the texture on the object always seems to be very low resolution... does anybody know a very good tutorial, or can somebody tell me what I am doing wrong? Thank you.

# Answer
UV mapping is one of the trickier things to get used to. It can actually be pretty fun. I always think of it as solving a puzzle you made yourself. Its also an art in itself and making good UV maps only comes with a lot of practice (but reading stuff on the net helps too!)

Texel density, or the amount of texture space you give different parts of your mesh, plays a big part in avoiding fuzzy elements. Read over this thread to get a good grip.

Pretty much, your texture corresponds to the 0-1 square of the UV editor. If you are not using a tiling texture, you need to make sure that all your UV 'islands' fit within this space, and are given enough room relative to how big the area is on the actual 3d mesh.

The bigger the mesh area, the bigger the UV island needs to be to avoid resolution issues.

To address other causes of fuzziness: \- Make sure your texture is of a high enough resolution. \- Try to keep visible areas to a similar texel density. \- Save texture space by making sure obscure parts of the mesh have smaller UV islands. \- Use a texture format that doesn't use hardcore compression (I like to use TGAs)

Hope some of that helps!
> 1 votes

---
Tags: textures, maya
---


# Question
Title: Precise Touch Screen Dragging Issue: Trouble Aligning with the Finger due to Different Screen Resolution
Please, I need your help. I'm trying to make a game that will drag-n-drop a sprite/image while my finger follows precisely with the image without being offset. When I'm trying on a 900x1280 (in X \[900\] and Y \[1280\]) screen resolution of the *Google Nexus 7* tablet, it follows precisely. However, if I try testing on a phone smaller than 900x1280, my finger and the image won't aligned properly and correctly except it still dragging. This is the code I used for making a sprite dragging with my finger under *touchDragged()*:

```
x = ((screenX + Gdx.input.getX())/2) - (fruit.width/2);
y = ((camera_2.viewportHeight * multiplier) - ((screenY + Gdx.input.getY())/2) - (fruit.width/2));

```

This code above will make the finger and the image/sprite stays together in place while dragging but only works on 900x1280.

You'll be wondering there's **camera\_2.viewportHeight** in my code. Here are for two reasons: to prevent inverted drag (e.g. when you swipe with your finger downwards, the sprite moves upward instead) and baseline for reading coordinate...I think.

Now when I'm adding another orthographic camera named **camera\_1** and changing its setting, I recently used it for adjusting the falling object by meter per pixel. Also, it seems effective independently for smartphones that has smaller resolution and this is what I used here:

**show()**

```
    camera_1 = new OrthographicCamera();
    camera_1.viewportHeight = 280; // --> I set it to a smaller view port height so that the object would fall faster, decreasing the chance of drag force.
    camera_1.viewportWidth = 196;  // --> Make it proportion to the original screen view size as possible.
    camera_1.position.set(camera_1.viewportWidth * 0.5f, camera_1.viewportHeight * 0.5f, 0f);
    camera_1.update();

```

**touchDragged()**

```
    x = ((screenX + (camera_1.viewportWidth/Gdx.input.getX()))/2) - (fruit.width/2);
    y = ((camera_1.viewportHeight * multiplier) - ((screenY + (camera_1.viewportHeight/Gdx.input.getY()))/2) - (fruit.width/2));

```

But the result instead of just following the image/sprite closely to my finger, it still has a space/gap between the sprite/image and the finger. It is possibly dependent on coordinates based on the screen resolution. I'm trying to drag the blueberry sprite with my finger. My expectation did not met since I want my finger and the sprite/image (blueberry) to stay close together while dragging until I release it. Here's what it looks like:

I got to figure it out how to make independent on all screen sizes by just following the image/sprite closely to my finger while dragging even on most different screen sizes instead.

***UPDATED QUESTION (as of 12/5/2012)***:

The **camera\_1.unproject(touchPoint)** still not working (and confused in which order should I put) and that is because of the two other cameras under **show()** method. Also, I changed the viewport of **camera\_1** by 70x100 for falling object answer based on my previous question, " How to Make Objects Fall Faster in a Physics Simulation ". Take a look below:

```
    Mother_Camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);

    // For background.
    background_camera = new OrthographicCamera();
    background_camera.viewportHeight = 1280;
    background_camera.viewportWidth = 900;
    background_camera.setToOrtho(false, background_camera.viewportWidth, background_camera.viewportHeight);

    // For fruits. (READ: Pixels per meter!)

    /*
     *
     *     Take note that if you set it at higher value, it might be fall slower starting from the taller peak (e.g. buildings, mountains, space).
     *  Based on physics, it was caused by drag force. Drag force causes any object to fall slower when you try to drop it from at its very tall
     *  peak.
     *
     */

    camera_1 = new OrthographicCamera();
    camera_1.viewportHeight = 100; // --> I set it to a smaller view port height so that the object would fall faster, decreasing the chance of drag force.
    camera_1.viewportWidth = 70;  // --> Make it proportion to the original screen view size as possible.
    camera_1.position.set(camera_1.viewportWidth * 0.5f, camera_1.viewportHeight * 0.5f, 0f);
    //camera_1.zoom = 100;
    camera_1.update();

    // For HUD.
    camera_2 = new OrthographicCamera();
    camera_2.viewportHeight = 1280;
    camera_2.viewportWidth = 900;
    camera_2.setToOrtho(false, camera_2.viewportWidth, camera_2.viewportHeight);

```

Also, there is another problem why my sprite (blueberry) didn't align with my finger while dragging and was it because of using my code under **resize()** method? Take a look:

```
    // Ingredients Needed for Screen Aspect Ratio
private static final int VIRTUAL_WIDTH = 900;
private static final int VIRTUAL_HEIGHT = 1280;
private static final float ASPECT_RATIO = ((float) VIRTUAL_WIDTH)/((float) VIRTUAL_HEIGHT);
private Camera Mother_Camera;
private Rectangle Viewport;

// Ingredients for all Independent Coordinates for Touch Screen (Drag-n-Drop)
private float Y_VIEW;
private float X_VIEW;

@Override
public void resize(int width, int height)
{
    // TODO Resize

    // Calculate new viewport.
    float adjust_screen = ((float)width) / ((float)height);
    float scale = 1.0f;
    Vector2 crop = new Vector2(0.0f, 0.0f);

    // Check for changes.
    if(adjust_screen > ASPECT_RATIO)
    {

        scale = ((float)height) / ((float)VIRTUAL_HEIGHT);
        crop.x = 0;

    } else if(adjust_screen < ASPECT_RATIO){

        scale = ((float)width) / ((float)VIRTUAL_WIDTH);
        crop.y =  0;

    } else{

        scale = (float)width / (float)VIRTUAL_WIDTH;

    }

    // Set new changes for the screen ratio.
    float w = (float)VIRTUAL_WIDTH*scale;
    float h = (float)VIRTUAL_HEIGHT*scale;

    // Set final changes for the screen view coordinates.
    crop.y = Gdx.graphics.getHeight() - h; // --> Set always on top.
    crop.x = (Gdx.graphics.getWidth()/2) - (w/2);

    // Set new changes for the touch screen drag-n-drop for precision in any screen resolution without distorting the alignment between the finger pointer and the object.
    X_VIEW = w;
    Y_VIEW = h;

    Viewport = new Rectangle(crop.x, crop.y, w, h);
}

```

Sorry for a little delay on how to put up by thinking what cause of the problem is. I'm still using @Majd's solution but I'm still in the problem yet. Is there anymore suggestions? Hope I didn't overwhelm my question a bit due to critical thinking and analysis.

# Answer
> 1 votes
Have you looked at the documentation for the Camera class? you can use Camera.unproject(Vector3 vec) to translate a point from touch input to camera coordinates, ie:

```
Vector3 touchPoint=new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera_1.unproject(touchPoint);

```

---
Tags: java, libgdx, coordinates, resolution, touch
---


# Question
Title: SDL_BlitSurface segmentation fault (surfaces aren't null)
My app is crashing on SDL\_BlitSurface() and i can't figure out why. I think it has something to do with my static object. If you read the code you'll why I think so.

This happens when the limits of the map are reached, i.e. (i\>width || j\>height). This is the code:

Map.cpp (this render)

```
Tile const * Map::getTyle(int i, int j) const {
    if (i >= 0 && j >= 0 && i < width && j < height) {
        return data[i][j];
    } else {
        return &Tile::ERROR_TYLE;  // This makes SDL_BlitSurface (called later) crash
        //return new Tile(TileType::ERROR); // This works with not problem (but is memory leak, of course)
    }
}

void Map::render(int x, int y, int width, int height) const {
    //DEBUG("(Rendering...) x: "<<x<<", y: "<<y<<", width: "<<width<<", height: "<<height);
    int firstI = x / TileType::PIXEL_PER_TILE;
    int firstJ = y / TileType::PIXEL_PER_TILE;
    int lastI = (x+width) / TileType::PIXEL_PER_TILE;
    int lastJ = (y+height) / TileType::PIXEL_PER_TILE;

    // The previous integer division rounds down when dealing with positive values, but it rounds up
    // negative values. This is a fix for that (We need those values always rounded down)
    if (firstI < 0) {
        firstI--;
    }

    if (firstJ < 0) {
        firstJ--;
    }

    const int firstX = x;
    const int firstY = y;

    SDL_Rect srcRect;
    SDL_Rect dstRect;

    for (int i=firstI; i <= lastI; i++) {
        for (int j=firstJ; j <= lastJ; j++) {

            if (i*TileType::PIXEL_PER_TILE < x) {
                srcRect.x = x % TileType::PIXEL_PER_TILE;
                srcRect.w = TileType::PIXEL_PER_TILE - (x % TileType::PIXEL_PER_TILE);
                dstRect.x = i*TileType::PIXEL_PER_TILE + (x % TileType::PIXEL_PER_TILE) - firstX;
            } else if (i*TileType::PIXEL_PER_TILE >= x + width) {
                srcRect.x = 0;
                srcRect.w = x % TileType::PIXEL_PER_TILE;
                dstRect.x = i*TileType::PIXEL_PER_TILE - firstX;
            } else {
                srcRect.x = 0;
                srcRect.w = TileType::PIXEL_PER_TILE;
                dstRect.x = i*TileType::PIXEL_PER_TILE - firstX;
            }

            if (j*TileType::PIXEL_PER_TILE < y) {
                srcRect.y = 0;
                srcRect.h = TileType::PIXEL_PER_TILE - (y % TileType::PIXEL_PER_TILE);
                dstRect.y = j*TileType::PIXEL_PER_TILE + (y % TileType::PIXEL_PER_TILE) - firstY;
            } else if (j*TileType::PIXEL_PER_TILE >= y + height) {
                srcRect.y = y % TileType::PIXEL_PER_TILE;
                srcRect.h = y % TileType::PIXEL_PER_TILE;
                dstRect.y = j*TileType::PIXEL_PER_TILE - firstY;
            } else {
                srcRect.y = 0;
                srcRect.h = TileType::PIXEL_PER_TILE;
                dstRect.y = j*TileType::PIXEL_PER_TILE - firstY;
            }

            SDL::YtoSDL(dstRect.y, srcRect.h);

            SDL_BlitSurface(getTyle(i,j)->getType()->getSurface(), &srcRect, SDL::getScreen(), &dstRect); // <-- Crash HERE

            /*DEBUG("i = "<<i<<", j = "<<j);
            DEBUG("srcRect.x = "<<srcRect.x<<", srcRect.y = "<<srcRect.y<<", srcRect.w = "<<srcRect.w<<", srcRect.h = "<<srcRect.h);
            DEBUG("dstRect.x = "<<dstRect.x<<", dstRect.y = "<<dstRect.y);*/
        }
    }
}

```

Tile.h

```
#ifndef TILE_H
#define TILE_H

#include "TileType.h"

class Tile {
private:
    TileType const * type;
public:

    static const Tile ERROR_TYLE;

    Tile(TileType const * t);
    ~Tile();

    TileType const * getType() const;
};

#endif

```

Tile.cpp

```
#include "Tile.h"

const Tile Tile::ERROR_TYLE(TileType::ERROR);

Tile::Tile(TileType const * t) : type(t) {}

Tile::~Tile() {}

TileType const * Tile::getType() const {
    return type;
}

```

TileType.h

```
#ifndef TILETYPE_H
#define TILETYPE_H

#include "SDL.h"
#include "DEBUG.h"

class TileType {
protected:
    TileType();
    ~TileType();

public:
    static const int PIXEL_PER_TILE = 30;

    static const TileType * ERROR;
    static const TileType * AIR;
    static const TileType * SOLID;

    virtual SDL_Surface * getSurface() const = 0;

    virtual bool isSolid(int x, int y) const = 0;
};

#endif

```

ErrorTyle.h

```
#ifndef ERRORTILE_H
#define ERRORTILE_H

#include "TileType.h"

class ErrorTile : public TileType {

    friend class TileType;
private:
    ErrorTile();

    mutable SDL_Surface * surface;

    static const char * FILE_PATH;
public:
    SDL_Surface * getSurface() const;
    bool isSolid(int x, int y) const ;
};

#endif

```

ErrorTyle.cpp

(The surface can't be loaded when building the object, because it is a static object and SDL\_Init() needs to be called first)

```
#include "ErrorTile.h"

const char * ErrorTile::FILE_PATH = ("C:\\error.bmp");

ErrorTile::ErrorTile() : TileType(), surface(NULL) {}

SDL_Surface * ErrorTile::getSurface() const {
    if (surface == NULL) {

        if (SDL::isOn()) {
            surface = SDL::loadAndOptimice(ErrorTile::FILE_PATH);
            if (surface->w != TileType::PIXEL_PER_TILE || surface->h != TileType::PIXEL_PER_TILE) {
                WARNING("Bad tile surface size");
            }
        } else {
            ERROR("Trying to load a surface, but SDL is not on");
        }
    }
    if (surface == NULL) { // This if doesn't get called, so surface != NULL
        ERROR("WTF? Can't load surface :\\");
    }

    return surface;
}

bool ErrorTile::isSolid(int x, int y) const {
    return true;
}

```

# Answer
I suspect these are never initialized:

```
static const TileType * ERROR;
static const TileType * AIR;
static const TileType * SOLID;

```

You haven't shown code with them ever being initialized. Even if they are, you're likely suffering from the "static initialization fiasco" outlaid here: http://www.parashift.com/c++-faq/static-init-order.html

In general, I'd shy away from all this static data. But for now, I'll note there's a workaround: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

If this is not the problem, I recommend comparing the address given to you in the access violation or segfault with any and all of the pointers involved in the line of code that's crashing, including the implicit "this" pointer used to access member variables. While it likely won't match exactly due to member variable offsets and the like, this will likely point you to the exact pointer that's causing the crash when dereferenced.
> 2 votes

# Answer
The only thing I can imagine in this situation, is that you are trying to access data far beyond the array limit, just check this...
> 2 votes

# Answer
MaulingMonkey's answer has the gist of it.

Very specifically, Tile::ERROR\_TILE is being initialized by storing a copy of Tile::ERROR's value, but this is total garbage (because Tile::ERROR hasn't yet been initialized). Namely:

```
// this object is constructed before main() is invoked
// and TileType::ERROR is just an uninitialized pointer
// which you're copying into Tile::ERROR_TYPE.type
const Tile Tile::ERROR_TYLE(TileType::ERROR);

```

As some unsolicited advice, the entire structure of the code is just... awkward. If you find yourself wanting to use the "mutable" keyword, you should pretty much rethink everything you're doing. In almost 20 years of programming C++, I've never once had a legitimate use for that keyword; anything it can solve you can solve by a better abstraction (which may well mean *less* abstraction).

In your case, I'd keep a TileDatabase that just mapped simple integer IDs to TileType values. It can even just be a simple std::vector wrapper that returns a reference to the error tile for out-of-bound indices (e.g. invalid tile IDs).

You've got a ton of different objects/types defined, which is a usual sign of newer coders who've just learned about object-oriented programming but haven't learned the do's and dont's yet.

Remember: just because you have some conceptual "object" doesn't mean that it deserves its own C++ class. C++ classes and interfaces should **focus on how things work in the algorithm** and **do not focus on how a human would categorize conceptual entities**. In other words, don't make overly "concrete" classes, but rather focus on algorithmic abstractions. It takes a lot of practice and experience to really start understanding what that really means. A classical treatise of the subject is the Coffee Maker example, with a good explanation available at http://web.archive.org/web/20081227131937/http://www.objectmentor.com/resources/articles/CoffeeMaker.pdf
> 1 votes

---
Tags: c++, sdl
---


# Question
Title: Blending textures together, texture fade over / fade in
What is the best way to render a texture overlapping effect?

Like in this example:

I want either the grass to fade in to the snow texture, or the other way around. No rough edges. Somehow make them blend over. So the grass has a bit of snow or the snow has a bit of grass How is this possible during runtime? If that's possible.

I don't render this by using the SpriteBatch, since the ground isn't rectangles (they can be moved).

This is the way I render each shape (each one of those squares):

```
// LoadTexture
// Apply EffectPass

device.DrawUserIndexedPrimitives<VertexPositionNormalTexture>
(
    PrimitiveType.TriangleList,
    render.Item.Points, // Array of VertexPositionNormalTexture
    0,
    render.Item.Points.Length,
    render.Item.Indexes, // Array of int indexes (triangulation)
    0,
    render.Item.Indexes.Length / 3,
    VertexPositionNormalTexture.VertexDeclaration
);

```

# Answer
> 4 votes
Edit: I missed that these aren't sprites, but actually polys. You want multitexturing. Keeping the content here, hopefully off use to someone looking for something similar.

You want to create a series of "Fringe" tiles and layer those where you need them. You will need to create corner and edge pieces for each of the tiles you intend to use, and it would be recomended to set an order in which tiles must always be in (Water, below earth, below rock, below grass, below trees, etc).

As an example of a sprite sheet I used to do this, see below. The top left tile is the "Full tile" for grass. The other 17 are either corners, edges or some combination. Using these, I can draw any combination of grass:

Then, you draw from the bottom up. First draw what you have, then do a pass for each fringe. Check the tiles around the current one, and draw an appropriate fringe.You want to draw everything from a single sheet at a time if possible, to avoid retexturing calls.

There are several ways to do it. Here are some links

Adventures in bitmasking

Tileset design tip

My horrible implementation can be found here between lines 253-369 (A gigantic if statement) however it runs fine.

# Answer
> 1 votes
I wrote an article about auto tiling that is a technique used to achieve that.

http://autoloot-games.com/?p=232

Here is a video showing it running:

http://www.youtube.com/watch?feature=player\_embedded&v=x\_iKY\_laARs

---
Tags: c#, xna, textures, blending
---


# Question
Title: Where can I find "magic numbers" for classic game play mechanics?
I'd like to find some "magic numbers" for the classic helicopter game. For example the numbers that determine how fast the helicopter accelerates up and down. Also perhaps the "randomness" of the obstacles (uniformly distributed? Gaussian?). **Where can I find these numbers?**

p.s. I don't care about the particular platform... Flash on the desktop browser is just as good as some implementation on a mobile device.

# Answer
**Decompile the game to figure them out**, but don't use any of their code, I would say the fall rate of an object cannot be copyrighted.
> 8 votes

# Answer
You have to think like a scientist. How would you determine physical constants in the real world if you didn't know them? Observation!

Here's a good example from Super Mario Brothers: http://hypertextbook.com/facts/2007/mariogravity.shtml

If you record video of some controlled experiments, you should be able to plot the curves of a game object's motion in a spreadsheet program, and then you can fit curves to it.
> 4 votes

# Answer
If you are implementing the game itself, put controls inside the game to tweak it while you play the game. Simple pushbuttons with "+" and "-" will do the job. Start playing and tweak the values as you go until it feels right. Also, remember to print the current value on screen. Whey you found the value, paste it into the code and remove the buttons.

The same for choosing the algorithm, make it possible to switch between them during gameplay and experiment until you figure out which option is the one you prefer.
> 2 votes

# Answer
Just try out values and tweak them until it "feels" right.
> 1 votes

# Answer
This is a bad question because this is done **by experiment**. The game developer was likely tweaking gravity/acceleration and horizontal scroll speed right until he finished the game. You tweak it to suit the difficulty you want the game to be at.
> 0 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: circle - rectangle collision in 2D, most efficient way
Suppose I have a circle intersecting a rectangle, what is ideally the least cpu intensive way between the two?

1. method A

1. calculate rectangle boundaries
    2. loop through all points of the circle and, for each of those, check if inside the rect.
2. method B

1. calculate rectangle boundaries
    2. check where the center of the circle is, compared to the rectangle
    3. make 9 switch/case statements for the following positions:

    * top, bottom, left, right
        * top left, top right, bottom left, bottom right
        * inside rectangle
    4. check only one distance using the circle's radius depending on where the circle happens t be.

I know there are other ways that are definitely better than these two, and if could point me a link to them, would be great but, exactly between those two, which one would you consider to be better, regarding both performance and quality/precision?

Thanks in advance.

# Answer
Method B is more precise for a perfect circle. You are talking about running through every point in the circle, in Method A, and I'm assuming that's not small number of points (probably at least 12). Consider, then, that you are looping through points -- and conditionals are slower than non-conditional operations.

On the other hand, method B uses square roots. This is not cheap, but a single square root is almost certainly better than `n` conditionals.

Having said all of that, I'm pretty certain method B is going to be your best bet if you want both accuracy and good speed.

The correct and standard approach is actually this:

Method C

1. Calculate rectangle bounds (either their own bounds if no rectangle rotation, or their bounding boxes if they are rotated in the plane).
2. Calculate each circle's rectangular bounds.
3. Apply a fast range overlap test in each of x and y axes to check for intersection of bound between object A and B (maybe a rectangle and a circle). If overlap, continue, else break as there is no way they can overlap if their bounds don't overlap.
4. Apply the more expensive test circle-circle or rect-circle intersection test to see if they *actually do* overlap. This is where the somewhat costly square root ops come in, to determine whether each of the 4 points of the given rect are within the radius of the circle.

A hierarchical approach like this, where you test successive possibilities for elimination, by order of increasing cost (of conditional), is ubiquitous in all forms of collision detection.

Ultimately, you want to avoid conditionals, particularly lengthy loops, inasmuch as possible. See this thread for an idea of precedence. This is why lower level languages such as C offer loop-unrolling as a compile-time optimisation.

**EDIT** opatut has kindly noted that square roots are not a requirement for methods B & C (see comments), leaving method A as the clear worst method.
> 4 votes

---
Tags: collision-detection
---


# Question
Title: Legal considerations when starting a game development team
I am about to start a project with two other developers and an artist, who I still haven't found. I'm not sure how exactly should we handle that from a legal perspective, though.

Are we supposed to sign a contract? What should be stated in such a document?

The game will most likely be free.

# Answer
When it's not for profit, you could agree to share your work under the terms of an open source license (Yes, Mr. Stallman, I know that the term open source is missing the point). Should you ever decide to split up, each of you will have the rights to the full project and can decide to continue development independently, with or without help from additional people.

When you want to make sure that none of you ever monetizes the game without permission of the others, you could use CC-BY-NC. That way you all can can use it, just not for making money.

When you want to allow each other to try to make money with it independently but you don't want them to obtain exclusive copyright, you could use the GNU General Public License. This, however, will also give end-users the right to use and modify your work.

Another option would be the BSD license. It doesn't force you to give rights to the end users. But it also doesn't prevent anyone of you to fork the project and keep exclusive copyright to the modifications he does after leaving you.

Using a free software license will also make it easier for you to find contributors who don't have financial interests. Many hobbyists (me included) would rather contribute to a project under a stock open source license than one where the copyright situation is unclear and you risk getting exploited for profit.

Or you can just roll your own license agreement. Just make sure that you agree how you want to handle copyright when one of you wants to continue without each other due to creative differences and how to handle any profits and losses. Just a hint: Do not agree on splitting profits evenly. You will soon realize that you all invest different amounts of time and energy into the project. For those of you who feel that they did more than the others, an even split will soon feel very unfair.
> 2 votes

# Answer
I think that if you're planning to sell this(or use it as a professional project) , then a contract would be appropriate, where as if it's just for fun, then a contract is overboard. if you get a contract, be sure to have it looked over by a lawyer as to patch up all the loopholes. If you really don't want it distributed, but aren't creating it as a professional project, a friendly agreement should be enough.
> 3 votes

# Answer
I recommend a contract regardless of what you're doing. If it's not for profit, a simpler one will work, as "spirit of the agreement" can be important in civil trials.

I am not a lawyer, and this does not constitute proper legal advice. It is only my opinion, and you should check local laws.
> 1 votes

# Answer
Free or not, it's better to have *some* contract than none at all, particularly if people aren't going to kick up a fuss about it (and they shouldn't, if it's fair). Even for free product projects, it serves to restrict people from going off with all your assets, or half your code, for example.

In fact, that would be my major concern if I were in your shoes: How do I set up an environment that is conducive to people sticking around through the lifetime of the project; or, if they don't/can't, how can we mitigate the impact of that (eg. do we get to keep, or at least maintain rights to to use, their code or assets)?

You should perhaps also cover what people give up if they voluntarily leave the project, vs. if they have no choice (depending on how much knowledge of that you can realistically have; it's hard to tell if a remote team member is actually suffering through eg. a divorce or if they just decided to drop your project in favour of something that looked more enjoyable to them).

A couple of excellent books on this topic are:
> 1 votes

---
Tags: legal, game-industry
---


title: Calculating Delta time , what is wrong?

text:
# Question
Title: Calculating Delta time , what is wrong?
For 2 days now i am trying to calculate the correct delta time for my game , I am starting to getting crazy since i tried all the solutions that i found on the 5 first google pages... What is wrong? I cant get the correct delta time ,whatever i tried is just not working , the delta goes from 1 to 4 and then back 1 and then to 3 even if i take the averange delta between many frames.Plus the game runs way much faster(i mean the movement) on slow devices than in fast. The game runs on android so the spikes between frames are expected.

My code is this:

```
    void Game::render()
    {

        timesincestart=getTimeMil();

        _director->Render();
        _director->Update();

        float dif=(getTimeMil()-timesincestart);//usally its about 5 milliseconds

        lastcheck++;
        sumdelta+=dif;
        if(lastcheck>20)
        {
            sumdelta=sumdelta/20;
            delta=sumdelta;
            sumdelta=0;
            lastcheck=0;
        }

        LOGI("delta:%f",delta);
    }

```

**SOLVED:**

```
void Game::render()
{
    oldtime=newtime;
    newtime=getTimeMil();

    delta=(newtime-oldtime)/16;//divide by 16 is just making the dt closer to 1

    _director->Render();
    _director->Update();

}

```

# Answer
> 5 votes
i am a bit confused with your delta...

But how i do it is like this :

```
while( 1 )
{
    old = newTime;
    newTime = GetTime();

    DoMyGameAndUseLotsOfCyckels( newTime - old );
}

```

# Answer
> 8 votes
Read Gaffer's article, Fix your Timestep. Understand how time accumulators work. Implement them. And apply actual time delta to physics and rendering, rather than some assumed constant `dt`. See if that serves you better.

Because in the end, if the time delta is varying wildly on your given platform, there is nothing you can do about that but to simulate around it as described above.

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


# Question
Title: Is it possible to compile an android game for pc desktop?
If I have an android game based on java native libraries. Is it to possible to compile into a windows/linux executable without a 3rd party emulator?

# Answer
> 5 votes
No, you cannot directly compile an Android project into a non-Android based executable.

You're going to need to port the code out. How easy that will be is going to depend greatly on how you structured your code base. If the game/application logic is separate to that of your Android specific code (think Activities, etc), it should be fairly easy to do, because that's the code that will obviously need to be re-written.

I would take a look at LibGDX to aid this. If you port your game using LibGDX, you'll have both desktop and Android with virtually the same code base.

# Answer
> 5 votes
The short, official answer is no, you can't. Android has it's own specific API's which don't exist for any desktop environment.

That being said, there's things you can do:

* Most of the Android Java API is the same as that of the desktop JDK. So for some application, migrating them for the desktop could mean simply grabbing the code, building it with the JDK, and maybe just change a small part of the code (like UI stuff, and OpenGL APIs etc). I've actually done this, and manually replaced the Android Java UI code with Desktop Java Swing code by hand, and it was fairly painless
* finally there's the Android x86 project which lets you run an Android environment on a desktop machine (like a virtual machine, it's actually built as a VirtualBox machine). Using this you can deploy and run your Android app on a desktop. There are limitations, like the fact that the latest version of Android will take some time before being ported to Android x86.

---
Tags: java, android
---


title: Isometric Rendering and Picking

text:
# Question
Title: Isometric Rendering and Picking
> **Possible Duplicate:**
> Isometric rendering and picking?

I've been looking for a formula to plot (world-\>screen) and mouse pick (world-\>screen) isometric tiles in a non-diamond-shaped world. What's the usual/correct way to do this?

# Answer
> 3 votes
I think you may be confusing some terms. Theme Hospital *is* diamond shaped from what I can tell. That's the shape of the tiles, not the entire world. You can shape the entire would however you like. The shape of the world would be the same as the shape of the tiles if the world was square (meaning equal width and height), but you don't need to make it that way.

You can use the algorithms described for this question. It's just an artistic style that will make it look like Theme hospital or Poxnora.

---
Tags: rendering, tiles, isometric, mouse, picking
---


# Question
Title: Architectural advice - websockets javascript/php integration
Myself and a friend have started making a game, he's likely to be using impact.js for the user interaction etc, but we need multiplayer functionality so some form of websockets for TCP connections etc. So we were thinking impact.js into socket.io and node.js. However, user accounts, ecommerce, session handling and social media integration will all be handled with Codeigniter (PHP), my question is, is it wise to have node.js running in parallel with Codeigniter, or if this is even possible? If not, if you were to create a multiplayer online game utilising ecomms to buy credits and user accounts, how would you go about this from a structural position and what engines/frameworks would you recommend? I'm new to this site so I apologise in advance if I'm posting something inappropriate.

Cheers,

Ewan

# Answer
> 1 votes
It is entirely possible to have nodejs and CodeIgniter (or any other web server framework) running at the same time. They do need to be running on different ports, or they need to have a reverse proxy (using Apache, nginx, lighttpd, etc.) to host them on different paths on the same host+port.

Sharing data between CodeIgniter and nodejs can be done by simply using the same database for both. You can also allow the nodejs service to make HTTP requests to your CodeIgniter backend, by creating a Web API for your backend services' needs.

Your other questions ("what tech do I use" and "how do I get started with this") are off-topic for GDSE. Really, though, use whatever libraries or tech you want. The core of your architecture is going to just be simple HTTP requests, a database, and a WebSocket server. How any of those pieces are implemented isn't really important.

---
Tags: javascript, html5, php, websocket
---


title: XNA 3D coordinates seem off

text:
# Question
Title: XNA 3D coordinates seem off
I'm going through a book, and the example it gave me seems like is should work, but when I try and implement it, it falls short.

My Camera class takes three vectors in to generate View and Projection matrices. I'm giving it a position vector of (0,0,5), a target vector of Vector.Zero and a top vector (which way is up) of Vector.Up.

My Three vertices are placed at (0,1,0), (-1,-1,0), (1,-1,0).

It seems like it should work because the vertices are centered around the origin, and thats where I'm telling the camera to look but when I run the game, the only way to get the camera to see the vertices is to set its position to (0,0,-5) and even then the triangle is skewed. Not sure what's wrong here.

Any suggestions would be helpful.

Just to make sure I've given you guys everything (I don't think these are important as the problem seems to be related to the coordinates, not the ability of the game to draw them): I'm using a VertexBuffer and a BasicEffect.

My render code is as follows:

```
effect.World = Matrix.Identity;
effect.View = camera.view;
effect.Projection = camera.projection;
effect.VertexColorEnabled = true;

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

    GraphicsDevice.DrawUserPrimitives<VertexPositionColor>
         (PrimitiveType.TriangleStrip, verts, 0, 1);
}

```

# Answer
The first thing which can be wrong is the vertices order. Now they are drawn counterclockwise (if we are looking from the 0,0,5 position. Try to draw them clockwise.

And that your triangle is skewed - you should post some picture. It can be caused by projection matrix. So you should also write how you create it.
> 1 votes

---
Tags: xna, 3d, camera, coordinates
---


# Question
Title: Handling game logic events by behavior components
My question continues on topic discussed here

I have tried implementing attribute/behavior design and here is a quick example demonstrating the issue.

```
class HealthAttribute : public ActorAttribute
{
public:
    HealthAttribute( float val ) : mValue( val ) { }

    float Get( void ) const { return mValue; }
    void Set( float val ) { mValue = val; }

private:
    float mValue;

};

class HealthBehavior : public ActorBehavior
{
public:
    HealthBehavior( shared_ptr< HealthAttribute > health )
        : pHealth( health )
    {
        // Set OnDamage() to listen for game logic event "DamageEvent"
    }

    void OnDamage( IEventDataPtr pEventData )
    {
        // Check DamageEvent target entity
        // ( compare my entity ID with event's target entity ID )

        // If not my entity, do nothing
        // Else, modify health attribute with received DamageEvent data
    }

protected:
    shared_ptr< HealthAttribute > pHealth;

};

```

My question - is it possible to get rid of this annoying check for game logic events? In the current implementation when some entity must receive damage, game logic just fires off event that contains damage value and the entity id which should receive that damage. And all HealthBehaviors are subscribed to the DamageEvent type, which leads to any entity possesing HealthBehavior call OnDamage() even if he is not the addressee.

# Answer
> 0 votes
Ok, I found the solution by myself.

It turned out that I missed the point where every entity should have own event manager. So, I modified the code:

```
HealthBehavior( shared_ptr< HealthAttribute > health )
    : pHealth( health )
{
    // Set OnDamage() to listen for entity local event "DamageEvent"
}

```

Now, behaviors dont care about game logic, they listen only to events triggered by their own event manager. And the game logic now fires event to entity's local event manager instead of global event manager:

```
// somewhere in game logic
{
    // simplified example of usage
    GetEntity( entityId )->GetEventManager()->TriggerEvent( damageEvent );
}

```

This way OnDamage() gets called only for target entity, so we can remove the check.

---
Tags: c++, component-based, events
---


# Question
Title: Coordinate spaces and transformation matrices
I'm trying to get an object from object space, into projected space using these intermediate matrices:

The first matrix (I) is the one that transforms from object space into inertial space, but since my object is not rotated or translated in any way inside the object space, this matrix is the 4x4 identity matrix.

The second matrix (W) is the one that transforms from inertial space into world space, which is just a scale transform matrix of factor a = 14.1 on all coordinates, since the inertial space origin coincides with the world space origin.

```
    /a 0 0 0\
W = |0 a 0 0|
    |0 0 a 0|
    \0 0 0 1/

```

The third matrix (C) is the one that transforms from world space, into camera space. This matrix is a translation matrix with a translation of (0, 0, 10), because I want the camera to be located behind the object, so the object must be positioned 10 units into the z axis.

```
    /1 0 0  0\
C = |0 1 0  0|
    |0 0 1 10|
    \0 0 0  1/

```

And finally, the fourth matrix is the projection matrix (P). Bearing in mind that the eye is at the origin of the world space and the projection plane is defined by z = 1, the projection matrix is:

```
    /1 0 0   0\
P = |0 1 0   0|
    |0 0 1   0|
    \0 0 1/d 0/

```

where d is the distance from the eye to the projection plane, so d = 1.

I'm multiplying them like this: (((P x C) x W) x I) x V, where V is the vertex' coordinates in column vector form:

```
    /x\
V = |y|
    |z|
    \1/

```

After I get the result, I divide x and y coordinates by w to get the actual screen coordinates.

Apparenly, I'm doing something wrong or missing something completely here, because it's not rendering properly. Here's a picture of what is supposed to be the bottom side of the Stanford Dragon:

Also, I should add that this is a software renderer so no DirectX or OpenGL stuff here.

# Answer
> 2 votes
OK, I have fixed it. I used a more simple shape as per Nathan Reed's suggestion. Turns out the eye was too close to the projection plane. I have set a d of 1000 units and now it appears to render properly.

---
Tags: 3d, coordinates, projection
---


# Question
Title: Detecting if an object is following a path
I am attempting to take GPS data and track it on a map and see if it follows a given path. I have the path as a set of points and the GPS data streams in as a similar set of points. I am attempting to track the progression of the current position across the path and I am wondering if there are any well known algorithms for this. I have come up with my own that works ok but it is a complex enough problem that I would like to minimize the amount of re-inventing of the wheel that I do.

What approach or algorithm would you recommend taking for this problem?

# Answer
Just thinking it out, first I would get the formula to calculate the nearest distance from a point to a line. When you say you have the path as a set of points, I assume it's a directional graph and not just a set of points.

Then I would do an algorithm like this: (there are probably logical errors, but the idea is there):

```
loop through every line in the path
     get the line which is closest to your current point
if the nearest distance is greater than some threshold
     return not on path
#you could check if the nearest line segment is the next expected one if you want to do checkpoints

```

for the formula: https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
> 1 votes

---
Tags: path-finding
---


title: Collision planes confusion

text:
# Question
Title: Collision planes confusion
I'm following this tutorial by **thecplusplusguy** and in the linked video he explain that for example for the world basement and walls we need to create the actual rendered (shown to the player) walls and then duplicate them, place them in the same coordinates as the rendered walls and call them `collision` (by defining their material to `collision`). Then it defines in the Object loader function that those objects with `material == collision` are collision planes and should not be rendered but just used to check collision.

Now I'm pretty confused. Why would we add this kind of complexity to a problem that can easily be solved by a simple `loadObject(string plane_object, bool check_collision);`:

1. Creating only the walls object (by loading .obj file in `plane_object`)
2. Define them also as collision planes whenever the `check_collision` is set to true

In this case we have lowered the complexity of his method and make it more flexible and faster to develop (faster because we don't always have to make a copy for each plane and flexible because we don't hardcode the Object loader). The only case in which this method could not work is when we need hidden collision planes, and for that we could modify the loadObject() function like this: `loadObject(string plane_object, bool check_collision = true, bool hide_object = false);`

1. Creating only the walls object (by loading .obj file in `plane_object`)
2. Define them also as collision planes whenever the `check_collision` is set to true
3. And add the ability to actually show the object or hide it based on `hide_object`.

The final question is: am I right? What would the possible problem encountered with my solution versus his?

# Answer
> 1 votes
While your solution would certainly work, and make for simpler Object files, it will mean that for every level you need to add in extra code whenever you want to add or remove collision objects.

If the collision object generation is handled completely by the Object loader, then your level-designer can create and modify levels without involving the programmer or forcing a rebuild of the engine. This is ***very important***, since a huge part of creating a game (\>90%) is making assets and levels.

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


# Question
Title: isometric drawing order with larger than single tile images - drawing order algorithm?
I have an isometric map over which I place various images. Most images will fit over a single tile, but some images are slightly larger. For example, I have a bed of size 2x3 tiles.

This creates a problem when drawing my objects to the screen as I get some tiles erroneously overlapping other tiles.

The two solutions that I know of are either splitting the image into 1x1 tile segments or implementing my own draw order algorithm, for example by assigning each image a number. The image with number 1 is drawn first, then 2, 3 etc.

Does anyone have advice on what I should do?

It seems to me like splitting an isometric image is very non obvious. How do you decide which parts of the image are 'in' a particular tile? I can't afford to split up all of my images manually either.

The draw order algorithm seems like a nicer choice but I am not sure if it's going to be easy to implement. I can't solve, in my head, how to deal with situations whereby you change the index of one image, which causes a knock on effect to many other images. If anyone has an resources/tutorials on this I would be most grateful.

# Answer
Divide your objects into 1×1×1 cubes, assigning to each cube a picture of the parts of the object that would physically be in that cube.

This is easy if you're starting with actual 3D objects and rendering them down to 2D. If you're drawing your objects directly in 2D (or if you have existing art that you need to split), it takes some manual effort. Fortunately, the split doesn't need to be exact, as long as you make sure that none of the image parts assigned to a given cube spill outside the hexagonal area that a solid 1×1×1 cube at that position would cover. It may help to make an overlay showing the outlines of each cube as an extra layer in your graphics editor.

Then you just assign a priority to each cube as *p* = *x* \+ *y* \+ *z* (assuming that all three coordinates increase towards the camera) and render the cubes in ascending order by priority.

---

Here's a quick example based on this image from Wikimedia Commons (by Phasmatinox / Allefant, used under the CC-By-SA 3.0 license):

The chest of drawers in the picture takes up two tiles, and I've drawn the boundaries of those tiles (the red hexagons) on top of it. The parts of the image that lie inside each hexagon should be assigned to the corresponding tile; the part where the hexagons overlap can be assigned to either tile (or even to both, if you like), since the choice won't affect the end result.

Note that you may need to elaborate on this simple algorithm if you can have multiple objects in one tile, walls/floors between tiles, or objects (such as people) moving smoothly between tiles. Walls and floors are pretty simple to handle: they can be drawn at any point after the content of the tile they're in front of (from the camera viewpoint) and before the tile they're behind. This is also a useful rule of thumb for objects moving between tiles; treat them as you would a wall between those tiles.

As for multiple objects in a tile, *sometimes* those are pretty simple: for instance, if you had a book lying on top of the chest in the picture, it should obviously be drawn after the surface it lies on. However, things can get more complicated if you, say, have objects that people can sit on. For example, if a person was sitting on a bench, facing away from the camera, then the person's body should be drawn after the bench but their legs (which are behind the bench from the camera) need to be drawn before it. One solution, in this case, would be to split the legs of a sitting person into a separate component with its own position (either in the adjacent tile, or between the tiles).
> 4 votes

# Answer
What you need is called a painter's algorithm.

You want to draw the furthest tile first, including any doodads or characters on it.

Then draw the next closest, and repeat until finished.

Your objects that span more than one tile must have an anchor/origin point declared. This is the grid cell that when drawn, will result in your larger object also being drawn. The origin point is chosen so that it is drawn after all cells the object bleeds into are drawn first.

Based on your question, your origin point will be the tile that is closest to the camera. (If you are using square, rather than diamond-shaped tiles, either the bottom-left or bottom-right tile should be chosen.)

Example code for a square-grid. Alter the loop direction for your diamond-grid.

```
for(int y = 0; y < GridHeight; ++y) {
    for(int x = GridWidth - 1; x > -1; --x) {
        MapCell cell = getMapCell(x,y);
        DrawTerrain(cell);
        if(cell.IsDoodadOrigin){
            DrawDoodad(cell);
        }
        if(cell.IsCharacterOrigin){
            DrawCharacter(cell);
        }
    }
}

```
> 3 votes

# Answer
It may help you to partition your objects by *type* or by *altitude.* For example, landscape (floors, walls) should be drawn before objects (beds). Also, because of the isometric perspective, lower-altitude tiles should be drawn before higher-altitude ones.

Also, if you go with the index-numbering (Z-ordering, really), I recommend using gaps between numbers -- don't make your floors `1` and your bed `2`. Use something like floors = `10` and beds = `20` or `100` or something else, so you can "insert" stuff in the middle without domino-incrementing everything else.
> 1 votes

---
Tags: 2d, algorithm, maps, isometric, tilemap
---


title: Camera game 2d Javascript using box2d

text:
# Question
Title: Camera game 2d Javascript using box2d
I'm cloningg, i'm doing camera 2d in angry bird game using javascript html5 game and box2d.js . I'm using context.translate(x,y) to move canvas, but i meet an error like this : many image
of birds saved

http://i1168.photobucket.com/albums/r489/thegioisach1/1.png

Everyone has a solution about camera 2d?? Thanks!!!

# Answer
> 3 votes
### Short answer:

Call `context.clearRect( 0, 0, context.canvas.width, context.canvas.height )` just before drawing onto the canvas every frame.

---

It's not really about the camera though, unless it's responsible for the drawing onto the canvas. It's also not about box2d.

As mentioned by Byte56, you need to clear the canvas before drawing. This is because the methods used to draw onto the canvas (e.g. `context.drawImage`) only draws on top of the existing image.

The canvas can't clear the frame automatically because the canvas would not know when to clear it. Luckily, the canvas allows the following methods to clear it manually.

https://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing suggested two ways (by Pentium10):

1. `context.clearRect( x, y, w, h )` where x and y is usually zero, or wherever you want it to start clearing (the top-left corner), and w and h are width and height respectively.
2. `canvas.width = canvas.width` or if that doesn't work try `canvas.width = someOtherWidth;` and *then* setting it back `canvas.width = width`. (**note:** Prestaul noted that using `clearRect` can be 10% faster than changing the width)

Later Prestaul reminded that if you had modified the transformation, you'll need to save the current transformation, then use `clearRect`, and finally changing back the transformation.

trembl also reminded that you need to `beginPath()` in order for lines to be cleared.

Please **go over to that page** yourself, because I did not cover everything mentioned there. That page can also be found by googling "javascript canvas clear". Also, remember that even though it may work on your web browser, doesn't mean that it will work on others!

Anyways, good luck on your game!

---
Tags: javascript
---


# Question
Title: Why do GPUs require game specific drivers?
PC GPU driver updates often cite improvements made to performance of specific, recently released games. Why is this game-specific updating needed? How do the game-specific changes interact with the game code?

# Answer
> 33 votes
As someone with a few years of driver development, I see this as two separate issues.

A graphics driver is a very complicated beast. To implement everything in a optimal way would be a simply impossible task; it's a big enough hurdle just to make a driver that actually follows the specs - and the specs keep getting increasingly more complex. So, you develop your driver based on the spec, and a handful of test applications (as, in many cases, there's no *real* software yet).

Along comes a real game (or benchmark, or some other use case for the driver, like video decoding) that exposes a bottleneck in the driver. In you go, figuring out how to smooth things out and make that use case faster. You can easily report that game XYZ is 27.3% faster, but in reality every application that has said use case (say, dynamic texture update) gets faster.

Then there's the ugly side, real per-application optimizations, wherein the driver detects what application is being run (or which shader is being compiled) and does something non-generic. There's been plenty of publicized cases of this, where, for example, renaming 3dmark executable suddenly changes the results.

I feel these kinds of optimizations are a waste of everybody's time - you lie to your customers in the case of benchmarks, and you may change the way a shader behaves from what the developer actually wants. I recall a case where a shader was changed from a texture lookup to a in-shader calculation (which only worked for said manufacturer's hardware) which was close, but not exactly the same result, and the developer balked that this wasn't a legal optimization.

# Answer
> 14 votes
In an ideal world they wouldn't.

This is not an ideal world however, so game-specific performance improvements may come from one or more of the following (not intended to be an exhaustive list):

* The game is doing a combination of operations A, B and C with states X, Y and Z set. The driver can make assumptions based on this and push things to a more optimal code path.
* The game never does operations I, J or K. Again, the driver may be able to choose a more optimal code path based on being able to assume that these operations are never done.
* The game does some things in a slightly (or not so slightly) suboptimal manner. The driver knows this, intercepts the calls, and converts them to something (hopefully!) equivalent that will work better with it.
* Game-specific tradeoffs can be made; e.g. it's OK if *this* combination of render states goes slow because it's more important that *that* combination goes faster so let's optimize accordingly.

It's important to note here that none of these should actually be "required". So long as both the driver and the game's API usage are conformant, things should work. But sometimes special-case tradeoffs to be able to extract max performance may be seen as appropriate. I'll refrain from commenting on whether or not that's a good thing.

# Answer
> 8 votes
Game developers push the bounds of GPUs. We can make an analogy to a game and a game engine. The more advanced the requirements of the game, the more advanced the game engine needs to be to support it. This is the same with graphics cards.

Computer games and GPU manufactures are good bed fellows. It's in their best interest to work together to improve the GPU, thereby improving the game. This is the classic software guys working with the hardware guys relationship. Both parties have something to add when it comes to designing the interface between software and hardware. That interface is the driver.

These updates may include bug fixes that the software guys found, or improvements the hardware guys have made to support the requirements of the software guys. You'll find this relationship all over.

Likely the reasoning behind including the specific games in the driver update release notes is PR. It not only shows that card manufacturer X is going to work really well with game Y, but it shows that game Y is going to be even better than it was before.

# Answer
> 6 votes
It's plausible that the game development team ran into a GPU driver bug that would cause the game to *not work correctly* if the driver bug wasn't fixed.

It's also sometimes a **marketing gimmick**. For example, ATI/AMD recently bundled a copy of Dirt 3 with their newer GPUs and pushed the idea of playing with Eyefinity with 3 monitors on this game.

So it's a bit of symbiosis there.

GPU vendor: Hey! This new feature! No one's using it!

Game developer: **We** could use it! Bundle our game with your GPU that uses this feature?

GPU vendor: Hell ya!

# Answer
> 1 votes
The truth is that GPUs do not **require** game-specific drivers.

Game-specific drivers are part of a marketing effort by GPU manufacturers to try to get an edge over other GPU manufacturers. If they can show better performance in popular games by having custom-tuned their drivers for those specific games, then (the theory goes) they attract more players of those games.

That's pretty much all there is to it.

---
Tags: gpu
---


# Question
Title: Is there an isometric 2d game that doesn't use tilemapping?
Is there an isometric 2d game that doesn't use tilemapping?

I want to do this in tilemap but the client doesn't want to use it (since it's easier to design maps without using tiles).

I've tried to research for some time and everything's done using tilemapping.

# Answer
There are lots of games to list for this and they all rely more or less at least on limited tile mapping (for example to fill empty areas).

Thinking a bit about this, two games are coming to my mind immediately, mainly due to them providing an experience making it hard to notice tile mapping (at least it's not that obvious) and using lots of unique graphics in specific areas:

* The early 3D **Final Fantasy** games (Final Fantasy 7-9) use mostly static and prerendered environments for scenes outside fights, while still providing a 3d perspective perspective.
* **Sacred** is similar to games like the Diablo series, however it uses lots of custom backgrounds/drawn scenes and in general is very nice to look at without immediately noticing lots of recurring patterns.

In general, I'd just note two important points you should keep in mind:

* The more unique you want your locations/environments (i.e. avoiding tile mapping), the more memory you'll need just to store/deploy your environments and the more important good resource handling will become (I remember playing Final Fantasy VII on the PC with only 16 MB RAM (32 MB recommended), which caused load times of several minutes between screens; very annoying!).
* Tile mapping isn't something bad, especially when done right (i.e. you don't notice patterns). Also there are ways to make map editors' life a lot easier, without having to abandon tiles or tile mapping. Create a WYSIWYG editor where creative are able to drag & drop elements and just "draw" areas rather than painting them tile by tile.
> 4 votes

# Answer
I know MicroForte used large, pre-rendered images for their maps in Enemy Infestation.

IIRC, their graphics/level design team would output one huge rendered image for a level and a matching Z-Buffer for occlusion culling.
This was the 90's, so a custom blit routine was used which queried the Z-buffer, but nowadays the graphics card will happily handle most of that for you.

I'll gladly expound upon this topic if it sounds like what you are seeking.
> 2 votes

# Answer
You've got a few options, but really, the two which make the most sense in regard to an isometric-projection (45-degree angles), are tiles and full-fledged 3D with a static camera (look at XCOM, StarCraft II, Diablo III).

Of course, you can also do without tiles if you're, say, making a game like TMNT2 - The Arcade Game or River City Ransom, and it's an old-fashioned hallway brawler, where in a modern version, rather than tiles, you could use one large hand-drawn background, if you wanted, (plus parallax images) and then create collision-nodes in-place, on the map.

Also, creating a map using tiles becomes vastly more simple, as soon as a map-editor is written.

What is the client actually trying to accomplish, here, and on what scale/budget/timeframe?
> 1 votes

# Answer
In a tone similar to @phobius' answer, the famous Infinity Engine (Baldur's Gate etc) used prerendered backgrounds and sprites for characters, buildings, trees etc.
> 1 votes

---
Tags: 2d, architecture, isometric
---


title: Markup format or script for data files?

text:
# Question
Title: Markup format or script for data files?
> **Possible Duplicate:**
> How to choose how to store data?

The game I'm designing will be mainly written in a high level scripting language (leaning towards either Lua or Squirrel) with a C++ core. In addition to scripts I'm also going to need different data files. Many data files will be for static information such as graphical assets and monster types. I'd also want to create and update data files at runtime for user information like option settings and game saves.

Can I get away with using plain script files (i.e. .lua or .nut files) for my data files, or is it better to use dedicated markup formats like XML or YAML?

If I use script files, loaded separately from my true scripts, then I wouldn't need an extra library to read those files. Scripting languages like Lua also have table syntax that lend themselves towards data definition. On the other hand I'd have to write my own schema check code. These languages also don't seem to support serialization "out of the box" like the markup format libraries do.

# Answer
I recommend using a markup format rather than putting all of your data in script files. The main reason being that editing and generating JSON or XML will be easier than generating comparable Lua or Squirrel code due to the availability of JSON and XML libraries. Another reason is it allows you more flexibility by keeping the data in its own format, and the scripts in their own format:

* If you decide to *change scripting languages* your data will still be usable.
* If you decide to *not use scripting at all* your data will still be usable.

In fact, you could take things to the other extreme and even store Lua or Squirrel code chunks in your data files -- but this is probably something you would want to avoid to keep your data and scripts clean.

**A note about JSON and Squirrel**: Squirrel 3.0 supports JSON-like declaration of objects, so you could actually use raw JSON strings and the Squirrel VM can parse them into tables. I see this as an advantage of using both technologies together.
> 3 votes

# Answer
> Can I get away with using plain script files (i.e. .lua or .nut files) for my data files...

**Sure**, that's a valid option.

I've worked on a game where a good chunk of the data files were written in Lua, nobody got hurt too bad, and it had some benefits:

* Lua table syntax is quite human readable, even if it has some quirks.
* One "parser" for everything (actually a bit more than a parser, the fantastic LuaBind). This can actually be a good thing: smaller code base, less things to maintain.
* You get "programmable data": it's easy to add a little routine in a data file e.g. to generate lists of things or parameterize some parts. I'm quite sure this sounds horrible to some ears, but it can actually be really useful for rapid prototyping. Just use it wisely, and refactor away the parts that get too dirty.

> ...or is it better to use dedicated markup formats like XML or YAML?

**That is yours to tell**, there is no such thing as *the best* option.

Of course there are some downsides to the data-as-scripts approach, Zack The Human mentioned some of them in his answer. I'd add that tool support is something very important to consider before going this way. There are good tools for editing regular data formats (XML, JSON), but you'll probably have to roll your owns if you plan to use a scripting language.

As usual the final choice is yours, just go the way that seems to suit your project the best.
> 1 votes

---
Tags: scripting, data, configuration
---


title: LibGDX tutorial help Scene2D

text:
# Question
Title: LibGDX tutorial help Scene2D
I'm having trouble understanding this tutorial. It defines the importance of classes, but it doesn't show an outline of the project file so far. From what I got from that tutorial was that there is a stage and actors. Stage would be the static parts of the game, while the actors are the ones moving. After that I got confused with the drawing method. I tried modifying it so I can draw a shape, but it wouldn't work.

How, if possible, would I create sprites using LibGDX's scene2d?

# Answer
You can find complete demo code on github and quick description on http://minimaldevelop.com/blog/libgdx-scene2d-game-example-code/
> 3 votes

# Answer
Most people here will suggest that you post your code. Honestly, you don't have to use the Stage/Actor framework to create a game if you choose not to. There's a class called DecalBatch and even SpriteBatch that may help you to understand the process to render sprites. It might help to start there but again, it's hard to explain why it's not working without seeing what you have already tried.

Here's a link to the DecalBatch test code: http://libgdx.googlecode.com/DecalTest.java

If you post your code, I can revise my comments to include some suggestions to get something up and rendering.
> 1 votes

---
Tags: android, sprites, libgdx
---


# Question
Title: Keeping Aspect Screen Ratio While Stays in Center
I sqw and I tried this suggestion on \*PISTACHIO BRAINSTORMIN\** on how to make a good and adaptive screen ration. For every different screen size, let's say I put the perfect circle as a *Texture* in LibGDX and played it on screen. Here's the blueberry image example and it's perfectly rounded:

When I played it on the *Google Nexus 7*, the circle turn into a slightly oblonng shape, resembling as it was being flatten a bit. Please observe this snapshot below and you can see the blueberry is almost but slightly not perfectly rounded:

Now, when I tried the suggested code for aspect ratio, the perfect circle retained but another problem is occured. The problem is that I expecting for a view on center but instead it's been moved to the right offset leaving with a half black screen. This would be look like this:

Here is my code using the suggested screen aspect ratio code:

**Class' Field**

```
// Ingredients Needed for Screen Aspect Ratio
private static final int VIRTUAL_WIDTH = 720;
private static final int VIRTUAL_HEIGHT = 1280;
private static final float ASPECT_RATIO = ((float) VIRTUAL_WIDTH)/((float) VIRTUAL_HEIGHT);
private Camera Mother_Camera;
private Rectangle Viewport;

```

**render()**

```
    // Camera updating...
    Mother_Camera.update();
    Mother_Camera.apply(Gdx.gl10);

    // Reseting viewport...
    Gdx.gl.glViewport((int) Viewport.x, (int) Viewport.y, (int) Viewport.width, (int) Viewport.height);

    // Clear previous frame.
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

```

**show()**

```
        Mother_Camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);

```

Was this code useful for screen aspect ratio-proportion fixing or it is statically dependent on actual device's width and height?

\**see http://blog.acamara.es/2012/02/05/keep-screen-aspect-ratio-with-different-resolutions-using-libgdx/#comment-317*

# Answer
I figure it out on how to stay center or inside the screen visibly (regardless of the device's screen aspect ration) by changing the value **crop.x** and **crop.y** as possible(basically set at 0). Regardless of the calculations to fit what's best for the screen and the whole game view, it will do.

```
crop.x = 0; //  I recommend this coordinate.
crop.y = 0; //  Default is 0 so that it will stay at bottom. It's a bit advance if you
            // put it on top leaving a "spacer" on it. Specify the Y-coordinate calcu-
            // lately.

```
> 1 votes

# Answer
I see that you've already accepted an answer, but I feel I can add to it. I have written a blog post about this here. The gist of it is as follows:

"After a bit of research, I’ve come to the conclusion that most Android phones that I want to target have a 480×800-ish resolution. I’ve also noted that the smallest aspect ratio of any Android phone (held in landscape orientation) is 4:3, that is Android phones don’t get any ‘squarer’ than 4:3.

With this data in mind, I created a virtual game screen of 800×600. This means my game logic acts under the impression that the game is always running in a resolution of 800×600. All positions and velocities are absolute to that resolution. The game logic calls the render-helper class to render and load textures. This render-helper class scales the virtual game canvas to fit on the actual device screen. The textures are scaled by the same class at load time using the Bitmap.createScaledBitmap function. Drawing position coordinates are also scaled similarly. The scale is determined by:

**Scale = Actual Screen Width / Virtual Screen Width.**

In devices with wider screens, some of the virtual screen bleeds out vertically. Alternatively, I’d have to horizontal display black bars on squarer screens, which is plain horrible. To deal with this vertical overflow, I just draw the HUD elements relative to the vertical offset. This offset can be calculated using:

**Offset = ((Scale * Virtual Screen Height) - Actual Screen Height)/2.**"
> 4 votes

---
Tags: java, libgdx, screen, resolution, aspect-ratio
---


title: Deferred rendering order?

text:
# Question
Title: Deferred rendering order?
There are some effects for which I must do multi-pass rendering. I've got the basics set up (FBO rendering etc.), but I'm trying to get my head around the most suitable setup. Here's what I'm thinking...

The framebuffer objects:

1. FBO 1 has a color attachment and a depth attachment.
2. FBO 2 has a color attachment.

The render passes:

1. Render g-buffer: normals and depth (used by outline & DoF blur shaders); output to FBO no. 1.
2. Render solid geometry, bold outlines (as in toon shader), and fog; output to FBO no. 2. (can all render via a single fragment shader -- I think.)
3. (optional) DoF blur the scene; output to the default frame buffer OR ELSE render FBO2 directly to default frame buffer.
4. (optional) Mesh wireframes; composite over what's already in the default framebuffer.

Does this order seem viable? Any obvious mistakes?

# Answer
> 1 votes
That's the standard way for it, I would profile your second stage as your performance may decrease with only a large shader with branches. you are mostly bound to one shader in the last stage tho. Use multi target render if possible and again, profile some setups.

# Answer
> 2 votes
Depending on your target platforms (e.g. if you're not targeting ios/android) you may wish to take advantage of multi-target rendering, combining your first two passes using an FBO with two color attachments (normals and diffuse or final color, depending on if you're doing deferred lighting or not). Sounds viable though.

---
Tags: opengl, shaders, glsl, deferred-rendering, frame-buffer
---


# Question
Title: Elegant solution for coloring chess tiles
I am re-developing a chess game I wrote in Java, and was wondering if there is an elegant algorithm to color chess tiles on a numbered chess board.

Right now my solution uses if else statements to determine if the tile is on an even or odd row, and based on that, if it should be a light or dark square.

# Answer
> 42 votes
The most elegant way I can think of, given that you have the `row` and `column` indices, is the following:

```
bool isLight = (row % 2) == (column % 2);

```

or, conversely:

```
bool isDark = (row % 2) != (column % 2);

```

Basically, a tile on a chessboard is light wherever both the column and row are mutually odd or even, and is dark otherwise.

# Answer
> 35 votes
```
bool isLight = ((row ^ column) & 1) == 0;

```

XOR together the row and column indices and look at the least-significant bit. Changing the row or column index by one will invert the result, hence it generates a checker pattern.

# Answer
> 22 votes
Another suggestion, very straightforward:

```
isLight = (row + column) % 2 == 0;

```

Adding the row and column gives the number of horizontal and vertical steps away from the top-left tile.

Even number of steps gives light colour.
Odd numbers of steps gives dark colour.

# Answer
> 4 votes
This one assumes that our squares are numbered in the range \[0..63\].

```
bool IsLight(int i)
{
    return 0!=(i>>3^i)&1;
}

```

Figuring out why it works is half the fun. :)

# Answer
> 2 votes
1. Number the tiles. You could derive this information by calculating row\*8+column or something similar.
2. Take modulus 16 of the grid number. (There are 16 positions before the tiles repeat.)
3. Color the tile based on if it has an even or an odd number. Flip the tile color if the result is greater than 7.

Code for zero-based indices:

```
int cellNum = (row*8+column) % 16;
bool isSecondRow = cellNum > 7;
if(cellNum % 2 == 0 ^ isSecondRow){ //XOR operator
    setColor(Color.White);
}else{
    setColor(Color.Charcoal);
}

```

# Answer
> 0 votes
Although this approach isn't really necessary for something as simple as a chess board, when I think of an elegant way to render something related to the view, I want to make it as easy as possible to change the rendered view as possible. For example, suppose you decided you wanted to alternate black and white on each row, but not each column. The one-liners used in answers so far would have to be re-written.

If I was to go as far as I could with this and make it as easy to redesign the pattern on the Chess board as possible, here is what I would do:

1) I would make a file that indicates what color each square in the chess board is.

For example, I could make a file `chess_board_pattern.config` that looks something like this:

```
bwbwbwbw
wbwbwbwb
bwbwbwbw
wbwbwbwb
bwbwbwbw
wbwbwbwb
bwbwbwbw
wbwbwbwb

```

2) I would write a class/component/whatever that can read this file and create some kind of object that represents the board pattern:

```
public class BoardPattern {
    private Color[][] pattern;

    public BoardPattern(File patternFile)
    {
        pattern = new Color[8][8];
        //Parse the file and fill in the values of pattern
    }

    public Color[][] getPattern {
        return pattern;
    }
}

```

3) I would then use that class in the function that actually draws the board.

```
File patternFile = new File("chess_board_pattern.ini");
Color[][] pattern = new BoardPattern(patternFile).getPattern();
ChessBoardDrawable chessBoard = new ChessBoardDrawable();

for(int row = 0; row < 8; row++) {
    for(int column; column < 8; column++) {
        chessBoard.drawSquare(row, column, Color[row][column]);
    }
}

```

Again, this is a lot harder than is necessary for a Chess board. I think in general, though, when working on more complicated projects, it's best to come up with generalized solutions like this instead of writing code that's difficult to change later.

---
Tags: tiles, chess
---


# Question
Title: Efficient existing rating system for multiplayer?
I would like to add a rating for online version of a board game. In this game there are many game rooms each normally having 3-4 people.

So I expect that player's rating adjustments (RA) should depends on

1. Rating of opponents in the game room
2. Number of players in game room and final place of a player
3. Person gets rating increase if he plays more games and more frequently
4. If a person leaves a game room (disconnect) before the game ends he should get punished with a high rating decrease

I have found two related questions in here

Developing an ELO like point system for a multiplayer gaming site

Simplest most effective way to rank and measure player skill in a multi-player environment?

**Please, let me know what would be the most appropriate existing rating model to refer.**

# Answer
> 4 votes
The ELO system is used by the FIDE (World Chess Federation) as ranking systems and League of Legends is using a system based on ELO. I have used it for local long-term game tournamets. ELO is a good system. If you want penalize those who play less, you can modify the ranking every certain time to remove points and positions to those who deserve it.

---
Tags: game-design, multiplayer, leaderboards, ranking
---


# Question
Title: Who has the rights to the party game Mafia / Werewolf?
Who has the rights to the party game Mafia / Werewolf?

Or is it public domain, meaning anyone can do an implementation of the game and release it as a commercial product?

**Update 1**: According to this question: Making a mobile app from a board game. Copyright infringement?

You can't copyright concepts or mechanics. This basically means this should be public domain, right?

# Answer
I am not a lawyer, but here are my findings.

The game's wiki page here leaves me to believe that a number of companies have marketed their own versions of the game successfully.

"Looney Labs successfully marketed a commercial version of the game as *Are You a Werewolf?*, which was later followed by Asmodee Editions under the title *Werewolves of Millers Hollow*, Mayfair Games as *Lupus in Tabula* and Bezier Games as *Ted Alspach's Ultimate Werewolf: Ultimate Edition*. A Cthulhu Mythos variant (*Do You Worship Cthulhu*) was published in 2006."

As long as you stay away from all art and certain terms used in these games you should be fine. As mentioned in the GDSE link in your update, *Words With Friends* exists without any problems from Scrabble.
> 3 votes

# Answer
Werewolf is owned by bezeer games and it is copyrighted. This i think mean you have to ask them first!!

Werewolf isn't what i call a party game imo btw.
> -1 votes

---
Tags: copyright, commercial
---


title: Path Modifier in Tower Of Defense Game

text:
# Question
Title: Path Modifier in Tower Of Defense Game
I implemented PathModifier for path of each enemy in my tower of defense game. So I applied fixed time to path modifier in that enemy complete their path. Like following code describe.

```
new PathModifier(speed, path);

```

Here speed define the time to complete the path. But in tower of defense game my problem is, there is a tower which slow down the movement of the enemy. In that particular situation I was stuck. please someone provide me some guidance what to do in this situation.

EDIT :

```
        Path path = new Path(wayPointList.size());
        for (int j = 0; j < wayPointList.size(); j++) {
            Point point = grid.getCellPoint(wayPointList.get(j).getRow(),
                    wayPointList.get(j).getCol());
            path.to(point.x, point.y);
        }

```

# Answer
> 2 votes
If your units have a fixed time in which to complete their path, then they have a velocity. Calculate the velocity and use that instead of the fixed path time. The velocity is `pathLength/timeToCompletePath`. When a tower slows them, it lowers the unit velocity.

# Answer
> 1 votes
if i understand this correct, you should have some sort of timeModifier that are usable from the outside of an enemy. so that the tower could set the modifier down when it hits with its projectiles.

If that is not an optition, you could try explaining abit how you find your path and how it´s done. and how it´s executed.

# Answer
> 1 votes
I found the following solution from other forum so I paste it to help other members.

Well the easiest solution I can think of is: 1) Create new class MyPathModifier(or Something...) 2) Make it extend PathModifier. 3) Create a class level float variable. Let's call it mSpeedModifier. Default value is 1.f 4) create public set/get methods for this variable 5) Override onUpdate:

```
        @Override
        public float onUpdate(final float pSecondsElapsed, final IEntity pEntity) {
                return super.onUpdate(pSecondsElapsed * mSpeedModifier, pEntity);
        }

```

6) When required call setter for this variable. pass 0.5f for half speed. Works both ways, so 2.f will make enemy move 2x faster. 7) Enjoy.

---
Tags: andengine
---


# Question
Title: How to create GoogleMaps-like camera for simple 2D strategy game?
I am just starting in game development (with web programming background). I want to know how to create 2D game with camera that can zoom in/out and can be moved like map in Google Maps. Could you help me with advise where to look for this, please? Thank you

# Answer
> 2 votes
If you have have a way of resizing your canvas, you can implement this easily.

Create a camera class (or constructor function, in the case of JavaScript), and make it have properties like zoom, position, maybe even speed and acceleration.

Then, when you are rendering it, call this:

```
canvas.draw(entity.image,
    entity.position.x - camera.position.x,
    entity.position.y - camera.position.y)

```

You can now move your camera around the world, without actually moving the world.

And for zooming... You must have a way of scaling your entire canvas, before/after of rendering anything:

```
canvas.scale(camera.zoom, camera.zoom)

```

There are different implementations of the `scale` function though. This one assumes that each time you scale, you scale from the default scale (1).

In most implementations, though, you'd want to save the state of the canvas, scale, render, and then load the state back. Why? Because scaling with a factor of 0.5 two times in a row wouldn't give you a picture two times larger, but a picture 4 times larger. You're not setting a constant scaling factor by calling `scale`, but actually rescaling everything. So, by setting the `camera.zoom` to anything except 1, the camera would appear to be constantly zooming/unzooming, because you're scaling each frame.

Notice how `camera.zoom` is a scalar, not a vector.

I suggest you don't scale every frame though. Scale only if the `camera.zoom` has changed.

---
Tags: 2d, camera
---


# Question
Title: How do I create a game that runs on Windows, iOS and Android?
I use C++ to create windows games and now I want to step into another other OS like Android or iOS. I'm totally familiar with C++ so I tried to create app for iOS using objective C it was working awesome. However, I also want to publish games for Android but not by using Java.

I don't want to create a single game 5-6 times for other platforms. Is their any way that if I create game for Windows then it will work in Android *and* iOS ? Or should I use Action Script 3.0? If I use action script 3.0, will it require Flash player to run the game in Windows, Android, iOS?

# Answer
Find an engine that runs on all three platforms (i.e., is *cross-/multi-platform*) *and* meets your requirements. The latter will vary with time and only you know all the requirements you need, so finding the correct engine is left up to you.
> 12 votes

# Answer
The world of cross-platform is a pain. The most convenient way is to create your game using OpenglES, and then try to do specific ports to other devices.

With android you have to pretty much hack to get it going but it might be worth it. Even if the NDK gives you the ability to use c++, it still is really hard to get it going with a simple cross-platform engine.

For android you have to use NDK, and for iOS you can compile c++ with objective-C.

So finally, it all comes down how you want to do it. Either you do it really easy and rewrite your game to Java, C++ and Objective-c ( might be awfully slow, but it´s easier than the rest). Or if you want to go with C++ on all devices and do special libraries for every devices and so on.
> 2 votes

---
Tags: c++, android, game-design, ios, actionscript-3
---


# Question
Title: Narrow-phase collision detection algorithms
There are three phases of collision detection.

1. **Broadphase**: It loops between all objecs that can interact, false positives are allowed, if it would speed up the loop.
2. **Narrowphase**: Determines whether they collide, and sometimes, how, no false positives
3. **Resolution**: Resolves the collision.

The question I'm asking is about the narrowphase. There are multiple algorithms, differing in complexity and accuracy.

1. **Hitbox intersection**: This is an a-posteriori algorithm, that has the lowest complexity, but also isn't too accurate,
2. **Color intersection**: Hitbox intersection for each pixel, a-posteriori, pixel-perfect, not accuratee in regards to time, higher complexity
3. **Separating axis theorem**: This is used more often, accurate for triangles, however, a-posteriori, as it can't find the edge, when taking last frame in account, it's more stable
4. **Linear raycasting**: A-priori algorithm, useful for semi-realistic-looking physics, finds the intersection point, even more accurate than SAT, but with more complexity
5. **Spline interpolation**: A-priori, even more accurate than linear rays, even more coplexity.

There are probably many more that I've forgot about. The question is, in when is it better to use SAT, when rays, when splines, and whether there is anything better.

# Answer
> 6 votes
Two that you're missing which immediately stand out to me are GJK and MPR.

GJK is an algorithm for finding the closest point of two convex polygons. With a little bit of extra work you can use it to find incident points for intersecting objects, and hence calculate a collision manifold. This is done via polygon clipping, same as if using SAT, but GJK saves you some steps (since you'll already have the closest points).

MPR (Minkowski Portal Refinement) is another algorithm, similar to GJK (they both use Minkowski spaces). It can't find the closest point between non- intersecting objects like GJK, but it does have a lot of other nice properties for games, and is way to use to get a contact manifold.

MPR is one of the more popular for games. It is very efficient, numerically stable, and easy to implement.

Other narrow phases are used more in specialized games. Racing games usually use ray casting as modeling actual tires and getting realistic (or even just fun) behavior is not yet possible using traditional collision shape and resolution modeling. Platformers also typically use highly customized collision and physics, as the preferred "Mario-like" physics are not modeled with traditional physics algorithms. You'll also often see different collision and physics methods for fluids and such, though I know less about those.

See:

# Answer
> 3 votes
I wanted to say, its Separating Axis *Test*, not Theorem.

You'd use SAT on non moving polygons (2D), although you can extend it to cope with relative linear motion.

2D polygon-based collision detection and response: Tutorial 3 - Extending further for fast moving objects

Don't use GJK in 2D, I found its actually slower than simply brute forcing SAT.

Another technique you can use is Minkowski Difference, which shrinks one object down to a point and 'grows' the other by the shape of the first. Then you test the combined object against the point which is a lot easier - this gives you penetration distance and normal. I find this tool is conceptually very useful for approaching new collision detection problems; easier to visualise than SAT.

For moving and rotating polygons (and polyhedrons) you can use Conservative Advancement to find the exact time and point of contact.

Continuous Collision Detection and Physics

You can read more about these techniques in this blog post which I wrote a while back:

Collision detection for dummies

Hope that helps!

Cheers, Paul.

# Answer
> 0 votes
This is really depends on the type of game you have. Each method above have its own trade-offs.

However, SAT is pretty standard in my experience for generic physics libaries, Ex. Box2D uses it extensively (Angry Birds, and many other games use Box2D).

Variations of color intersection mixed with SAT or Hitbox intersection is used in games like Sonic, Megaman with good results.

I don't know much about #4 and #5 though.

---
Tags: collision-detection, raycasting, interpolation, separating-axis-theorem
---


title: How display path ball will bounce?

text:
# Question
Title: How display path ball will bounce?
I'm trying to figure out a way to show the path a ball will travel, so that the player can line up a shot before they fire the ball.

I can't think of a way to calculate this path in advance and show it to the player, especially if it involves collision detection. At first I thought I would run the game at a super high speed for one update, plot the path with some dotted lines where the ball bounced, and then in the next frame hide the 'tracer' ball. This seems to have two issues - Calculating collision detection without actually updating the frames and collision detection getting less reliable at high speeds.

If they were straight lines I think I could figure this out in a while loop, but trying to take into account the speed of the ball, the curve of the path, the reflecting from other objects..it all seems a bit much.

I'm not looking for any code and this isn't a platform specific question, more just help trying to figure out conceptually how this would work. Can this be done? Are there techniques to achieve this?

# Answer
> 4 votes
You have a couple options depending on how complicated your situation is, but for the things you are mentioning I would say your first instinct is pretty close to what you want to do.

When you wish to display the path, go ahead and make a copy of your ball launched at the appropriate angle and run it forward without regard to framerate or drawing. You'll still step it forward in the same increments you normally would (to avoid high speed issues), you'll just start the next step immediately rather than wait for next frame as normal. You'll also want to keep track of the simulated time passed, as it's unlikely you'll want to trace out forever. You'll also need it for applying correct amounts of force as all physics will use the simulated timestep rather than the actual one.

Now, if your ball is going to affect the things it collides with, you'll have to include them in the simulation (and anything *they* hit) past that point, in which case you'll likely want to show a tracer "ghost" version of those objects as well. Obviously if this isn't an issue (or you can make it not an issue through design choices) it makes your problem quite a bit easier to manage. I'd make a copy of anything involved in the simulation for purposes of said simulation as that way you can affect them with your normal physics calculations without worrying about actually moving anything.

Every time you collide, figure out the new effects to the ball (primarily velocity) and continue running your simulation in a loop until either you stop (velocity under threshold) or you hit the end of your tracer (say, 5 seconds of simulated time, much less than that actually) For ease of calculation I'd set it up so you only trace the ball as things are right now, if that bounce will effect other obstacles and you want to stay accurate you'll have to update all of them as well should they be affected by anything moving in the simulation.

Once you have that data display just depends on how you want to handle it. You could have the simulated ball drop visible spheres at a regular rate during it's path, or you could play it in sections and let the tracer ball itself be seen. I would recommend that you only run the long calculation of what happens when the input factors change (direction/power difference) in order to cover up the extra time it takes to process.

---
Tags: physics
---


title: How to remove bezier handle in 3dsmax?

text:
# Question
Title: How to remove bezier handle in 3dsmax?
While editing spline, I need to make one of the vertexes to be an absolute corner. I.e. bezier control points should be in zero distance from the vertex.

How to do that?

# Answer
> 5 votes
You could try creating an actual vertex of the corner type while you are first creating the spline.

I don't know of a way to change a vertex from bezier to corner after it has been created, however you can use the refine tool to create a new "corner" type vertex right next to it, and delete the old bezier vertex.

# Answer
> 4 votes
Go to vertex mode, select the vertex that needs to be changed then right click on it and select Corner from the menu. To convert it back to bezier then just select bezier again.

---
Tags: 3dsmax, beziers, splines
---