# Question
Title: Engine for 2D Top-Down Physics-Based Skeletal Animation
I just watched at the Sui Generis video, and was completely amazed. Specifically, the part where the big troll thing is beating up the player with his flail.

This got me really excited, and I would like to try implementing something like this in a 2D Top-Down format. Something like this.

That atloria example seems simple enough, but it's not exactly what I'm looking to make. I think atloria is using predefined animations, where as I would like to make something more physics-based like the Sui Generis engine does.

So, I'm wondering what physics engines might work for something like this, and if I'd need to implement my own skeletal system, or if I could just use "joints" and such from the engine. The only experience I have in terms of physics engines is Box2D, which I've heard shouldn't be used for top-down settings, and I can think of a few reasons it wouldn't work out well. One of those reasons being gravity. In box 2D, gravity pulls towards a side of the screen (usually the bottom.) I wouldn't want my player's forearms constantly being pulled to one side. :)

Also should mention that the programming language doesn't matter all that much to me. I'm currently playing with HTML5 stuff, though. :)

Thanks in advance!

# Answer
> 4 votes
Any physics engine can do (at least) half the work for you. The effect you're seeing is achieved by blending ragdoll physics with explicit animations. You can do this by having animations apply forces to bones and letting physics do the work for you. I haven't implemented this myself so I'm not 100% sure on the technique, but there's some articles out there on the Web on it.

Wolfire's blog used to have some good articles on it, but I can't for the life of me find them right now. BTR Studios has a nice overview of the technique. There's a great set of slides on Just Cause 2's ragdoll animation blending. Google "ragdoll animation blending" and you can find more.

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


# Question
Title: How do I render an entire frame to a Texture2D?
I asked a question here: C# XNA Make rendered screen a texture2d

But, I ended up not getting the exact result I was looking for since I didn't ask the question right.

In a game I am writing, I render an extremely large city out of objects, this can cause lag when moving the camera to view things that are off screen. I need a way to render then ENTIRE city, even the stuff that is off screen, and make it into a Texture2D.

The answer I chose for the last one didn't work entirely right because it only gets what is on screen, not what is off.

# Answer
> 1 votes
You can still use this approach.

For 3D Just move the camera much further away so that the entire city is in the view volume. \[or make the view volume wider/higher if using orthographic projection\]

You will have to make the size of the render target much bigger to accommodate the required resolution, but you will not be able to make a texture more than 4,096 pixels in either dimension.

If 4,096 sized textures is not enough, than you could look at making a number of textures

\[EDIT\]

For 2D just render the scene on a render target much larger than the screen size e.g 4096 pixels across, making sure that you render things with the same scale (i.e. if a building is 10 pixels across on screen, it should be 10 pixels across on the render target). This way you will get a much larger area of your city drawn. You can then draw subsections of this texture on the screen.

```
int vpw = graphics.GraphicsDevice.Viewport.Width;
int vph = graphics.GraphicsDevice.Viewport.Height;

spriteBatch.Begin();

//camera.Position is the point in  the world you want at the centre of the screen
//cityRect is the sub-area of the large background you want to display
Rectangle cityRect=new Rectangle(
                (int)(camera.Position.X-vpw/2),
                (int)(camera.Position.Y-vph/2),
                vpw,
                vph);

//cityTexture is the large pre-rendered texture
spriteBatch.Draw(cityTexture, Vector2.Zero,
            cityRect, Color.White);
spriteBatch.End();

```

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


# Question
Title: Finding the normals of an oriented bounding box?
Here is my problem.

I'm working on the physics for my 2D game.

All objects are oriented bounding boxes (OBB) based on the separate axis theorem.

In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating.

To do this I need to find the normal of the face(s) that the other OBB is touching.

Example:

The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there.

Here are my questions:

1. How do I determine which edges the car is penetrating.
2. I know how to determine the normal of an edge, but how do I know if I need (-dy, dx) or (dy, -dx)?
3. In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out?

Answers or help with any or all of these is greatly appreciated.

Thank you

# Answer
> 3 votes
I think what you need is the Minimum Translation Vector (MTV). This is the smallest displacement which will separate the intersecting two objects.

The MTV is easy to find when using SAT.

1. Find the normal (separtaing axis) with the smallest overlap
2. The direction of the MTV is the direction of this axis
3. The length of the MTV is the amount of overlap

The direction of the MTV will depend on which objects's normal was used. E.G. If the normal belonged to the car, then the MTV will be pointing away from the car.

---
Tags: geometry, collision-detection
---


# Question
Title: Custom inventory items based on inheritance
So, here's the scenario: I'm building an RPG. Like most of the other RPGs on the market, my game will feature an inventory and of course, inventory items. So far I've worked well with using a single class for all items, because I did not need anything else than character stat alteration on item usage (consumption). However, I'd like some items to have a more exotic effect. Think of something like when the user consumes a transformation potion, he automatically turns into a beast.

In order to achieve this I've thought about declaring a new class that inherits from BaseItem for each item. Each descendant would override some methods (like void OnConsume()), to change the base behavior.

This works fine, but when it comes to inventory management, I have some issues. The actual inventory will have to work with BaseItem components only (for obvious reasons, as it's an enumerable collection of objects of the same type); casting any descendant to the base class is possible, so no problems in adding items to the inventory. But how can I keep track of the descendant's type (class) for each item in the inventory? And how to perform the descendant's OnConsume from withint he inventory, for each item?

Let me know if you can think of a better solution than mine, or if you can think of a solution to my problem only.

Development is done in C#, inside Unity 3.5.

Thanks!

# Answer
To check whether an object is an instance of a class in C#, use the `is` keyword:

```
var item = inventory.getItem( ... );

if ( item is SpecialItem ) {
    var specialItem = (SpecialItem) item;
    // do something special...
}

```

or just cast it with `as` and see if it succeeds:

```
var specialItem = item as SpecialItem;
if ( specialItem != null ) {
    // do something special...
}

```

See also: How to: Safely Cast by Using as and is Operators (C# Programming Guide)

---

**Edit:** To keep track of your items, you should organize them into a reasonable class hierarchy instead of having all of them inherit directly from `BaseItem`. So, for example, a helmet might be an instance of class `Helmet`, which extends `Headgear`, which extends `Armor`, which extends `Wearable` (armor, jewelry, etc.) which extends `BaseItem`. (Of course, you don't *have* to do it exactly like this. For example, if you have no use for a separate class for headgear, you can just have `Helmet` inherit directly from `Armor`.)

You'll probably also want to use interfaces to describe different aspects an item might have. For example, imagine that you want to have a magic helmet. Obviously, you could have a parent class `MagicItem` for all magic items, but C# won't let you inherit from both `Helmet` and `MagicItem` at the same time. Instead, you can define an interface `IMagicItem` that any item class can implement to indicate that it's magic (and provide methods to invoke its magic effects), and declare your magic helmet class like this:

```
public class MagicHelmet: Helmet, IMagicItem {
    // Implement the IMagicItem interface here, and optionally override some
    // methods from Helmet.
}

```

You could also, for example, define an `IWearable` interface in addition to (or instead of) the `Wearable` class, so that when you decide to, say, implement a flower that can be worn on the head (or maybe a tame parrot that can be worn on the shoulder), you can do that even though neither `Flower` nor `Parrot` are subclasses of `Wearable`.

(Ps. I had to go AFK for a while as I was writing this edit, and I see from the comments that you managed to solve your real problem in the meanwhile. I'll post this anyway, since it might still be helpful.)
> 6 votes

---
Tags: c#, unity, rpg, inheritance
---


# Question
Title: Seeking an C/C++ OBJ geometry read/write that does not modify the representation
I am seeking a means to read **and write** OBJ geometry files with logic that does not modify the geometry representation. i.e. read geometry, immediately write it, and a diff of the source OBJ and the one just written will be identical. Every OBJ writing utility I've been able to find online fails this test.

I am writing small command line tools to modify my OBJ geometries, and I need to write my results, not just read the geometry for rendering purposes.

Simply needing to write the geometry knocks out 95% of the OBJ libraries on the web.

Also, many of the popular libraries modify the geometry representation. For example, Nat Robbin's GLUT library includes the GLM library, which both converts quads to triangles, as well as reverses the topology (face ordering) of the geometry. It's still the same geometry, but if your tool chain expects a given topology, such as for rigging or morph targets, then GLM is useless.

I'm not rendering in these tools, so dependencies like OpenGL or GLUT make no sense.

And god forbid, do not "optimize" the geometry! Redundant vertices are on purpose for maintaining oneself on cache with our weird little low memory mobile devices.

# Answer
I have written a command line OBJ manipulation tool myself, which has the representation preservation as one design goal. It does not offer an intermediate form of the model (so it does not "load" it), but rather reads the file line by line and dumps the same line back, unless the requested operation such as scaling or centering needs manipulating the data. All comments and empty lines etc are preserved. Maybe this could be something you could expand to fill your needs.

https://github.com/tapio/obj-magic
> 2 votes

# Answer
Parsing OBJ files is trivial; you shouldn't need a library to do it. All you have to do is read the file line by line, add v/vt/vn data into arrays, and add 'f' faces into 'g' groups and remember the 'usemtl' material for each group. (This is assuming you don't use the fancy OBJ features like lines or curves.)

I've written a simple python script to minimize OBJ files by removing duplicated vertex data. Feel free to use it and strip out the minimization steps that you don't want.

https://github.com/ccxvii/asstools/blob/master/objcrush.py
> 0 votes

---
Tags: serialization, model-loader
---


# Question
Title: iPhone 3d Model format: .h file, .obj, or some other?
I'm beginning to write an iPhone game using OpenGL-ES and I've come across a problem with deciding what format my 3D models should be in. I've read (link escapes me at the moment) that some developers prefer the models compiled in Objective-C .h files. Still, others prefer having .obj as these are more portable (i.e., for deployment on non-iPhone platforms).

Various 3D game engines seem to support many(?) formats, but I'm not going to use any of these engines as I would like to actually *learn* OpenGL-ES. Am I putting myself at a disadvantage here by not using a packaged engine?

Thanks!

# Answer
> 3 votes
Every engine that you learn will actually teach you OpenGL ES better, as long as you see what is happening under the hood. You can roll your own engine, but be ready to rewrite it many, many times. It'd better to learn an existing one, and then decide wether you want to write from scratch.

That said, personally I think that storing models in `.h` is a very crude and ugly way of doing it. It will work only if you have just a few models. Do not even start to think about in a case of a game that will need resource handling (ergo have more than a basic amount of models/textures).

# Answer
> 1 votes
No. It all depends what you want to learn.

If you want to learn game programming as a whole but more aimed towards logic, then use a game engine.

If you want to learn OpenGL-ES, which is what you say, then it makes a great deal more sense not to use a game engine. That way you can see what works, and what doesn't. With a game engine, you would maybe do something like 'AddModel("address"); RenderAll(); ' or whatever. This doesn't do a great deal of teaching OpenGL.

And for the model format, I think it makes sense to keep them as an .obj file. You can edit them with a modelling program, and you learn how to load models universally, rather than just on iPhone.

# Answer
> 1 votes
Using .h files for your model is really only useful for something *really* quick and dirty. Every time you change anything about your model you need a rebuild. I could see it done for something that is crucial (say if you have a 3d loading image that has to be there even if loading fails) but apart from that it's even too oldskool for my liking (and I'm a dinosaur in most departments).
While I would hardcode a cube while getting to grips with an environment, I'd swap to loading models as soon as I got my prime renderer up and running as it's only a fraction harder to read the models and then index the data than it would be too reference hardcoded models.
Loading them also sets you up a lot better for reusing the engine because if you hardcode your models the rest of your code will probably end up following the same hardcoded philosophy and will be quite unreusable.

# Answer
> 0 votes
OBJ models are not an ideal format for OpenGL, since they use separate indexes for positions, normals and texture coords. Using OBJ with OpenGL means you have to preprocess the data when loading it to create either new vertices and indices, or use non-indexed arrays to render.

A similarly simple to parse but more efficient format is IQM and its text-based companion format IQE. IQM also supports basic skeletal animation and vertex colors.

http://lee.fov120.com/iqm/

---
Tags: iphone, opengl-es, models
---


# Question
Title: Looking for a library to create a grid based first person game online
Before I go and build it myself, I have been looking for a library that may help making a grid based first person view similar to:

https://www.youtube.com/watch?v=GwmZoCFd4Us

I plan to make a web based version of this in a hackathon I am organizing. Would there be something for this in python?

# Answer
What you are looking for (i guess) is a technique called raycasting. Good examples of the use of raycasting is of course the Doom series or Wolfenstein 3D.

Since it's not used that much anymore (for rendering at least), i'm not sure if you will be able to find a library/engine that would do this for you out of the box.

You may have to do it yourself, what you want to pick then is a standard rendering library such as SFML, SDL etc. The process of raycasting is very simple. If i would have to recommend only one reading about raycasting i would choose this one.

---

Also if you want to use Python be careful of what tools you decide to use. I would recommend avoiding PyGame for this kind of things. I made a Wolfenstein 3D clone in C that i tried to port in Python using PyGame, the game was terribly slow.
> 1 votes

---
Tags: html5, python, raycasting
---


# Question
Title: How do I draw a scene with 2 nested frames
I have been trying for long time to figure out this: I have loaded a model from a directx file (I am using opengl and Java) the model have a hierarchical system of nested reference frames (there are not bones). There are just 2 frames, one of them is called x3ds\_Torso and it has a child frame called x3ds\_Arm\_01. Each one of them has a mesh. The thing is that I can't draw the arm connected to the body. Sometimes the body is in the center of the screen and the arm is at the top. Sometimes they are both in the center. I know that I have to multiply the matrix transformation of every frame by its parent frame starting from the top to the bottom and after that I have to multiply every vertex of every mesh by its final transformation matrix. So I have this:

```
public void calculeFinalMatrixPosition(Bone boneParent, Bone bone) {
    System.out.println("-->" + bone.name);
    if (boneParent != null) {
        bone.matrixCombined = bone.matrixTransform.multiply(boneParent.matrixCombined);
    } else {
        bone.matrixCombined = bone.matrixTransform;
    }

    bone.matrixFinal = bone.matrixCombined;
    for (Bone childBone : bone.boneChilds) {
        calculeFinalMatrixPosition(bone, childBone);
    }

```

}

Then I have to multiply every vertex of the mesh:

```
public void transformVertex(Bone bone) {

    for (Iterator<Mesh> iterator = meshes.iterator(); iterator.hasNext();) {
        Mesh mesh = iterator.next();

        if (mesh.boneName.equals(bone.name)) {
            float[] vertex = new float[4];
            double[] newVertex = new double[3];
            if (mesh.skinnedVertexBuffer == null) {
                mesh.skinnedVertexBuffer = new FloatDataBuffer(
                        mesh.numVertices, 3);
            }
            mesh.vertexBuffer.buffer.rewind();
            while (mesh.vertexBuffer.buffer.hasRemaining()) {
                vertex[0] = mesh.vertexBuffer.buffer.get();
                vertex[1] = mesh.vertexBuffer.buffer.get();
                vertex[2] = mesh.vertexBuffer.buffer.get();
                vertex[3] = 1;

                newVertex = bone.matrixFinal.transpose().multiply(vertex);
                mesh.skinnedVertexBuffer.buffer.put(((float) newVertex[0]));
                mesh.skinnedVertexBuffer.buffer.put(((float) newVertex[1]));
                mesh.skinnedVertexBuffer.buffer.put(((float) newVertex[2]));

            }

            mesh.vertexBuffer = new FloatDataBuffer(
                    mesh.numVertices, 3);
            mesh.skinnedVertexBuffer.buffer.rewind();
            mesh.vertexBuffer.buffer.put(mesh.skinnedVertexBuffer.buffer);

        }

    }

    for (Bone childBone : bone.boneChilds) {

        transformVertex(childBone);

    }

```

}

I know this is not the more efficient code but by now I just want to understand exactly how a hierarchical model is organized and how I can draw it on the screen.

Thanks in advance for your help.

# Answer
> 1 votes
Ok. This is what I mean by frames, I'm talking about a Directx file (.x extension) which contains something like this:

```
Frame x3ds_Torso {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000001, 25.891449, -0.982366, 1.000000;;
}
Mesh Torso {
  //Vertex list
}

Frame x3ds_Arm_01 {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
-10.000001, 2.436886, 0.982366, 1.000000;;
}
Mesh Arm_01 {
    //Vertex list
}

```

}

As you can see every frame is a node in the hierarchical system and each one of them can contain meshes and a transformation matrix which define the position of mesh in the model space. I already know how to load this structure and when the file just contain only one mesh there is no problem, the problem comes when there is more than on mesh, in the above example there is a body (frame x3ds\_Torso) and its child the arm (x3ds\_Arm\_01), because the arm should be drawn connected to the body but this is no happening.

---
Tags: opengl, java
---


# Question
Title: Portal 2 mapping dimensions and measurments
I am wanting to start building a portal 2 map for single player mode.

I have used the hammer world editor before but not for portal.

As far as portals are concerned will the distance I drop vertically be equal to the distance I am thrown horizontally?

So a 16 unit drop throws me 16 units forward?

# Answer
> 2 votes
Portal does not model Air Resistance (this is why you can alternate between two ground-based portals indefinitely, without losing height), though there does appear to be a terminal velocity.

But below that terminal velocity threshold, vertical distance remains the same -- fall 16 units, get shot up 16 units\*.

\*Assuming both portals are on the ground.

If you're mixing horizontal and vertical portals (or 45\* angle portals), the distance will *not* be the same; as Jonathan Hobbs mentions in the comments, projectile motion comes into play, and you will go less high if your exit portal is at 45\*, and less far if your exit portal is vertical (unless you also have room to fall downwards at the same time; hitting the ground cancels your momentum immediately).

# Answer
> 0 votes
It depends on how high above the ground you exit the portal. If you exit at ground level you're not going to go far at all. If you exit well above ground level you could move horizontally much further. Like the comments say though, looking into projectile motion will help too.

---
Tags: level-design
---


# Question
Title: Move Background in AndEngine for a Racing Game
I am new to game development and AndEngine. I have small query about racing game. I am going to develop a bike racing game. For bike racing game we will move the background or the player. I am tried with andengine autoparallax background. But I didn't got the correct answer.

I need to do a background like these screenshots in SpeedMoto.

Can anyone help me to set the background.

# Answer
> 1 votes
You can set the camera to chase the Sprite object which is, in your case, the car.

```
mCamera.setChaseEntity(entity);

```

note that you will need to bigger background or zoom the camera.

---
Tags: android, game-design, andengine
---


# Question
Title: Is there a site where people discuss game concepts and questions in general?
I like making game concepts for fun, as a hobby. I don't think that all my game concepts are amazingly awesome and have to be created and would revolutionize the industry. I just want some people to talk to that have the same hobbies as I do. To be able to discuss ideas and point out the pros and cons.

# Answer
> 12 votes
Hobbyists, independent developers, and prospective developers discuss these things on this site, Gamedev.net, and various forums such as TigSource and Indiegamer. These are pretty much only the places where this sort of discussion happens.

By comparison, professionals tend to carry out their high-level discussion of game design in a similar way to much academia: they publish books, papers, articles, give conference talks, and post blog entries, which are then discussed and cross-referenced. There's no reason why you couldn't start your own blog about your ideas, but you'll have trouble getting any traffic, because the average person's game concept is not going to be of much interest to the wider community. This is why typically you'd go for the first route, of game development forums.

The reason there isn't anything more for this is partly because the professionals do a decent enough job of exchanging and discussing ideas, and partly because the ideas and concepts that a typical prospective developer comes up with are considered nearly worthless in the professional arena. (And as such, only of interest to one's peers on forums and the like.) This perception of worthlessness is because most professional game developers already have more of their own pet ideas than they have time to create (making ideas far too abundant for the average one to be worth much), and because the quality of a game is almost never intrinsic to the concept itself, meaning it can be almost useless in isolation without a full prototype or technical specification behind it - and usually the only people capable of making such a prototype or specification are already either in the industry, or are able to make the game themselves without presenting it to others.

# Answer
> 7 votes
There's a design board on the TIGSource forums. It seems pretty full and diverse.

# Answer
> 3 votes
There are game development communities on http://www.gamedev.net/ and http://www.indiegamer.com/

# Answer
> 2 votes
You might try the GDSE Chat Room. It's occasionally pretty well-populated, and has proven to be a pretty good sounding-board.

# Answer
> 2 votes
GDNet also has a Game Design forum.

# Answer
> 2 votes
I have a website myself that I am using for game design discussion called Ascension Protocol. You can visit it at: http://www.ascensionprotocol.com, be sure to visit us on facebook as well!

---
Tags: game-design
---


# Question
Title: Rendering another screen on top of main game screen in fullscreen mode
my game runs in fullscreen mode and uses active rendering. The graphics are drawn on the fullscreen window in each game loop:

```
    public void render() {
    Window w = screen.getFullScreenWindow();
    Graphics2D g = screen.getGraphics();
        renderer.render(g, level, w.getWidth(), w.getHeight());
    g.dispose();
    screen.update();
    }

```

This is the screen.update() method:

```
public void update(){
    Window w = device.getFullScreenWindow();
    if(w != null){
        BufferStrategy s = w.getBufferStrategy();
        if(!s.contentsLost()){
            s.show();
        }
    }
}

```

I want to display another screen on my main game screen (menu, inventory etc). Lets say I have a JPanel inventory, which has a grid of inventory cells (manually drawn) and some Swing components like JPopupMenu. So i tried adding that to my window and repainting it in the game loop, which worked okay most of the time... but sometimes the panel wouldn't get displayed. Blindly moving things around in the inventory worked, but it just didn't display. When i alt-tabbed out and back again, it displayed properly.

I also tried drawing the rest of the inventory on my full screen window and using a JPanel to display only the buttons and popupmenus. The inventory displayed properly, but the Swing components keep flickering. I'm guessing this is because I don't know how to combine active and passive rendering.

```
    public void render() {
        Graphics2D g = screen.getGraphics();
        invManager.render(g);
    g.dispose();
    screen.update();
    invPanel.repaint();
    }

```

Should i use something else instead of a JPanel? I don't really need active rendering for these screens, but I don't understand why they sometimes just don't display. Or maybe I should just make my own custom components instead of using Swing? I also read somewhere that using multiple panels/frames in a game is bad practice so should I draw everything on one window/frame/panel?

If I CAN use JPanels for this, should I add and remove them every time the inventory is toggled? Or just change their visibility?

# Answer
From Java Passive vs. Active Rendering instructions:

> If you use lightweight components, such as Swing components, you may have to fiddle with them a bit so that they draw using your Graphics, and not directly as a result of calling the paint method. Feel free to call Swing methods such as paintComponents, paintComponent, paintBorder, and paintChildren directly from your rendering loop.

Also check if some other Root pane besides Content pane would fit better for your purposes: How to Use Root Panes.
> 1 votes

# Answer
Instead of using another panel, I would use the same game container. I would load a semi transparent image and keep it in center. Then, I would draw the inventory etc., on the transparent image so that the game's previous screen is visible at the background.

## Rendering Swing Components

Suppose you have a JPanel and you wan't to render it. Set the panel to be double buffered and don't add it to the container.

Instead, every time you draw, translate the graphics and call the `paint()` method of the component.

Don't forget to resize the background image to the container size. Now you can set the layout of the panel and add your other swing components directly to it.
> 0 votes

---
Tags: java, rendering, screen, swing
---


title: In-Game Encyclopedias

text:
# Question
Title: In-Game Encyclopedias
There are some games where there is an in-game encyclopedia where you can know many things about characters and settings of the game. For example, the Codex in Mass Effect. I want to know if it is exclusive to Bioware, and get inspired about other encyclopedia systems.

What are some other examples of in-game encyclopedias? How effective is it? I also want some examples where the in-game encyclopedia is not effective at all or an ignored feature

# Answer
> 3 votes
**Metroid Prime** games uses mechanism called scanning. The player can scan objects and enemies in the game for more information, which is saved in a log book. The background story of the game is also scattered as scannable text in the game world. If the player scans enough in the game or even everything that is possible, a small additional ending video is shown when completing the game. See http://metroid.wikia.com/wiki/Scan\_Visor

**Pikmin 2** has similiar log book called Piklopedia, but the content is filled automatically. See http://pikmin.wikia.com/wiki/Piklopedia

In both of these games filling the missing entries to the encyclopedias is a challenge on it's own.

---
Tags: game-design
---


# Question
Title: 2D Tile Game - Smooth Biome Terrain Transitions
While working on my 2D tile based game, I encountered a problem. I use Perlin Noise to generate the terrain. Some biomes (Desert, Forest, etc) have different flatness values depending on terrain, which causes the end/start of a new biome to have a big cliff because the terrain is different. When 2 biomes have the same flatness, they are fine, but if they are different, this can happen. Is there any way to keep this from happening?

Example (In programmer art)

# Answer
When I had this problem in 3D, i solved it by blending values from both noise generators near seam. I blended not only height, but everything: textures, terraint details, etc.

Here's how it worked out: http://nevermind.wdfiles.com/local--files/\_unity%3Aroentgen/WebPlayer.html (unity web player). As you can see, blending works almost perfectly.
> 6 votes

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


title: Which purpose do armor points serve?

text:
# Question
Title: Which purpose do armor points serve?
I have seen a mechanic which I call "armor points" in many games: Quake, Counter Strike, etc. Generally, while the player has these armor points, he takes less damage.

However, they act in a similar fashion that health points do: you lose them by taking said damage.

Why would you design such a feature? Is this just health 2.0, or am I missing something?

To me, armor only makes sense in, for example, RPG games, where it is a constant that determines your resistance. But I don't see why would it need to be reduceable during combat.

# Answer
Well, look at the Quake system.

In Quake, you have 3 different kinds of armor: Green, Yellow, and Red. With Green armor, the armor absorbs 1 point of damage for every point of damage the player takes. In that way, it acts like doubling health. However, consider the complexities of that situation.

If you have 10 health, and you pick up a 100 health powerup, you go back up to full 100 health. However, if you pick up 100 Green armor, you now effectively have... 20 health. Remember: you die when you run out of *health*, not armor.

**Point #1**: It can reward you for maintaining a state of high health.

Consider the same situation: you have 10 health. You come across 100 health, and then you come across a 50 health pickup. You still have 100 health. Joy.

However, if you have 10 health and come across 100 Green armor, and later get a 50 health pickup, you now have effectively 120 health.

**Point #2**: It provides a way of breaking the health cap, while still allowing the cap to exist and matter.

Now look at the Red armor. For every 6 damage you take, 5 goes to the Red armor, and 1 to you. Red armor comes in lots of 200. Even if you are at 10 health, you effectively have 60.

**Point #3**: Different grades of armor allow for different qualities of effects. Some can provide more of a reward in certain situations, while others are more situational rewards.

Thus leading into:

**Point #4**: It allows you to provide more rewards for player exploration. It's a different kind of reward from health, weapons, ammo, and other powerups.

Remember: Quake is not a modern-style hyper-linear FPS. It's more of an adventure game where you shoot people. Rewarding exploration is important, so you need a good set of viable powerups of different qualities. Armor is merely another quality to choose from.

This is why modern FPS games don't use it. They don't need it, since they're very linear games.
> 39 votes

# Answer
A lot of good answers, so here's one that restates the situation from a different perspective: Armor lets your health go above 100%. Many games which have armor also have special rare health items that raise your health total to 150 or 200, but generally speaking your health starts at 100, "Healthy," and can only go down from there. Medkits raise it back up to a maximum of 100.

Armor gives the player a chance to increase their combat readiness above their starting state. Having 100 health and armor that mitigates 100 damage gives you 200 effective health, but explains that additional damage-soaking ability in a way that makes sense in the fiction.
> 6 votes

# Answer
Looking at it from the perspective of non-FPS games (say, RPGs or Roguelikes), you see that armour has two major purposes:

* Damage absorption (player can tolerate high-damage enemies)
* Gradation of difficulty

When you have many, many types of armour (like in RPGs), it provides a different gradation of difficulty -- as enemies get stronger, you can trade cash (which is abundant) for incremental armour updates. Beats grinding to level up lots.

In all cases, armour (especially powerful armour) provides damage absorption. If combined with a mechanic like destructable armour, this can create interesting tactical elements -- you search hard for high-powered armour, but it blows up on a horde of weak enemies.
> 4 votes

# Answer
If game have mechanism that on eg. 50% health character gets some kind of debuff, having more armor or health is something different. And armor in good enough state can provide some kind of buff (eg. reducing damage by constant, improving mobility etc.)

Other aspect (more FPS oriented) is that armor protects only some part of body. So hitting unprotected part (eg. face) can go right to health where hitting torso goes first/partialy to armor.
> 3 votes

# Answer
Conceptually, the armor points are considered separate from health points purely to add another perceived element or resource in the game. Mathematically and mechanically speaking, yes, they are identical, but they convey to the player an understandable real-world separation between something that gives the player extra protection (e.g. armor) and something that increases the player's health (e.g. medicine).

It works out because it's expected that armor would wear out over time, or as it takes a beating from damage. Armor value that don't decrease from damage (such as those in RPG games as you mentioned), choose to remove the complication of armor deteriorating over time, probably in order to cut down on the number of elements and values the player needs to keep track of (since there are a lot more statistics and bufs in an RPG compared to an FPS).

Separating the armor from health also gives the option to tweak the damage values exerted on armor vs. health from various damage-dealing elements in the game, if such mechanics are desired.
> 2 votes

# Answer
It can be a valid argument that this type of mechanic just replicates something that's already there, and as such is superfluous, and I've had a similar discussion with someone relating to ammo (the thrust of which was: beyond a certain level you may as well make ammo infinite as either way you're never going to run out anyway).

However, this does have implications beyond just raw mechanical function.

Armour, and indeed ammo beyond a certain level, serves an additional purpose. It's a form of payoff for the player; they defeat the boss, or find a secret area, or navigate a nasty trap, or whatever you have, and as payoff they get to stockpile up on extra goodies. So it's a risk/reward thing (even if the risk is not always optional) that operates on a psychological level as well as on a purely mechanical one.

Players like getting extra goodies. The specific case of armour that may be mechanically identical to extra health is just a variation on goodies that breaks the monotony of stuffing a map with extra health. Ammo you know the player is never going to use because they already have plenty - so what? It functions on that level as a reward so it does it's job.
> 2 votes

# Answer
When you separate armor and health, you not only add the option of getting more effective health-points, it also adds a new mechanic to work with.

In a shooter game like Unreal-Tournament, you would have ubiquitous health-pickups which heal for 20 points of health and your health is capped at 100. When you're at 100 health, the health-pickups become useless. *But*, you can effectively double your health by getting armor/shield powerups.

It's clear that this adds more variation and requires some more strategy by the player to keep health and armor at the highest level possible. It also gives map-designers more options to play with. If I recall correctly, armor was scarce in Unreal Tournament and also placed well hidden (hard to reach, you needed to go to areas outside of your usual walking path) or at very exposed areas where you risked to get gunned down before reaching it. So some map designers used it has high-skill/high-reward powerup. It's obvious that this only works with two types of power-ups (health alone wouldn't add this layer of complexity).

So armor isn't just health 2.0. It's a new resource which can be used for more variations in level-design and creates new gameplay strategies.
> 2 votes

---
Tags: game-design
---


# Question
Title: How to rotate camera centered around the camera's position?
Currently I am using gluLook at like so:

```
gluLookAt(position.x, position.y, position.z,
          viewPoint.x, viewPoint.y, viewPoint.z,
          upVector.x, upVector.y, upVector.z);

```

with the above, don't know if you need more information, how could I change it so that the camera acts like its rotating around itself, instead rotating around its viewpoint. You can see the current code at https://github.com/dchhetri/OpenGL-City/blob/master/opengl\_camera.cpp, that class was adapted from codecolony.com.

# Answer
I'm not so sure if I understood your problem right, but I'll try to answer anyways.

`gluLookAt()`, as its name implies, creates a view matrix for a camera, and takes three vectors as parameters.

The first one is the camera's position. This is where your camera will be located. If you want your camera to rotate around itself, you most likely don't want this parameter to change.

The second one is the location of the point of interest, or where your camera will be pointed at.

The third one is a vector that represents where 'up' is.

So, as you mentioned, you want your camera to rotate around itself. There are actually three meanings of "rotation" in three-dimensional space:

Suppose this lovely plane donated to us by Wikipedia is your camera:

Doing yaw (yawing?) is pretty simple. You keep your 'up' vector to (0, 1, 0), and change the point of view to rotate around the XZ plane, by setting it to (cos(theta), 0, sin(theta)).

For simplicity, I'm supposing your camera is located at (0, 0, 0), but if not, you can simply add the location of your camera to your point of interest.

Rolling is also quite simple. You keep the point of interest static, and change the 'up' vector to rotate around the XY plane, by setting it to (cos(theta), sin(theta), 0).

Once again, for simplicity, I'm supposing you're looking at (0, 0, 1) or (0, 0, -1).

Finally, pitching is slightly more complicated, since you will be simultaneously changing your point of interest and 'up' vectors, but it's not so complicated either.

Let's start by changing the point of interest to rotate around the YZ plane, by setting it to (0, sin(theta), cos(theta)). This will take care of rotating the camera.

Now, to stabilize the camera, we need to set the 'up' vector to be orthogonal to both the point of interest vector, and the X axis. You can also build it with trigonometric functions, or you can use the facilities of the cross product, which does exactly that. So you set the 'up' vector to cross(point\_of\_interest, (1, 0, 0)). If your camera ends up upside down, reverse the parameters or do the cross product with (-1, 0, 0) instead.

This covers the three main rotations. Doing more complicated rotations involves using quaternions. Quaternions is a slightly more complicated topic I can't cover in a simple answer, but I'm sure there are many tutorials around online, so go ahead and google it.

Have a nice day.
> 5 votes

# Answer
The simple example is for rotating in xy-plane (up = z).

In order to circle around the object (at origin) at distance R, you use `LookAt = 0,0,0; Position = R*cos(a),R*sin(a),0;`

To rotate camera instead, the equations are `LookAt = x + cos(a), y + sin(a), 0`; Position = x,y,0;\`

It's basically vector math, where the vector origin and target change place.
> 3 votes

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


title: Sending A Class Packet

text:
# Question
Title: Sending A Class Packet
How would I be able to send a class through the internet like this.

```
class Player
{
    public int Health;
    public Player Copy()
    {
        return this;
    }
}

```

And do this.

```
SendPacket(new Player);

```

Well something like that?

# Answer
> 2 votes
You have to do two things.

First you have to be able to serialize your object. The definition, according to MSDN is:

> Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

You can find many ways to do this in C# but I would recommend to use the built in binary serialization techniques in .NET. You can start reading up on that here http://msdn.microsoft.com/en-us/library/vstudio/ms233843.aspx

Then you have to make some sort of connection. Between two computers. One way to do this is using sockets. Microsoft has made this quite easy in .NET (although I think in Java it is slightly easier but less flexible). To keep it simple I would suggest using Synchronous Sockets first. Synchronous means that the program 'hangs' until all the data has been received by the other party. See http://msdn.microsoft.com/en-us/library/6xt5x5zw.aspx

If you don't want the program to hang while sending the data you can use Asynchronous Sockets. They are a lot harder to use because you have to explicitly tell the other end how much data to expect and you have to handle the several steps the sending takes. I found the MSDN tutorial on this a bit unclear but you can find them for client and server here and here. I also wrote my own tutorial which you can find here and if you try Google you will see there are a lot more so skim a few and then pick the one that you find explains it best.

Recap

1. Serialize the object
2. Send the bytes using a socket
3. Receive the bytes on the other end
4. Deserialize and we have reconstructed the object on another computer :)

---
Tags: c#, networking, multiplayer
---


# Question
Title: Problem with Ogmo Editor (is Tiled Editor a solution?)
I made a level editor for a puzzle game with Ogmo Editor and gave it to our designer/level designer. When he downloaded and started Ogmo, his CPU went to 100%. I looked at my CPU usage while Ogmo is running, and it goes from 20% to 30% (which is also high for an application alike Ogmo). He has a Windows 7 VM running on his Mac and I have a normal Windows PC, can this be a problem?

I found a thread on FlashFunk forum that confirms that Ogmo has CPU usage issues. Has anybody maybe solved this issue?

The solution seems to use Tiled Editor, but I never used it before. Is it difficult to change a level editor from Ogmo to Tiled? Can they export in the same format (XML with CSV elements for my puzzle game)?

**EDIT**

I ended up re-making the level editor with Tiled. It wasn't difficult and the only problem was that the exported XML is slightly different. In Ogmo the layers names are exported as XML element names, and in Tiled all layers are exported as elements with the layer name as the name attribute of the layer element.

My first question still remains: has anybody managed to solve the high CPU usage of the new version of Ogmo?

# Answer
> 1 votes
20-30% is plenty normal. It's far from being too CPU dependent. You also have to remember that the numbers inside taskmanager not only represent a single application but your whole system. So Ogmo alone might not be what is using 20-30% of your CPU's overall performance capacity.

As for your level designer's performance issues. He's running the application from within a simulated/virtual environment, so it's pretty obvious that he would take a major. performance hit.

---
Tags: tiles, tools, level-design, map-editor
---


title: Server for online browser game

text:
# Question
Title: Server for online browser game
I am going to be making an online single player browser game. The online element is needed so that a player can login and store the state of their game. This will include things like what buildings have been made and where they have been positioned as well as the users personal statistics and achievements. At this point in time, I am expecting all of the game logic to be performed client side

So far, I am thinking I will use flash for creating the client side of the game. I am also creating a MySQL database to store all the users information.

My question is how do I connect the two. Presumably I will need some sort of server application which will listen for incoming requests from any clients, perform the SQL query and then return the data.

Does anyone have any recommendations of what technology/language to use?

# Answer
I recommend you to try Jelastic. I really like it: the GUI is awesome! I heard that they had added VDS feature, so maybe this will be useful in your case.
> 3 votes

# Answer
If you don't have much experience with server-side programming and/or don't want to host your own server machine I can recommend Google App Engine \- it's easy to use for this kind of application (see the datastore documentation) and scales nicely. The App Engine SDK allows you to run a test server locally in a simple manner.

I don't have any experience with Flash, but this blog entry gives an overview on how to connect with App engine.
> 1 votes

# Answer
I'd check out this article. You'll find a lot of specific information on client and server. It talks about HTML5 (which you should consider) and other fun, server bits using Node.js.
> 1 votes

# Answer
You can have a look at http://www.smartfoxserver.com/ It's specifically designed for multiplayer applications, and if you have less than 100 concurrent connections, you even have a free Comunity Edition license.

Cheers!
> 1 votes

---
Tags: flash, server, browser-based-games
---


# Question
Title: 2D game collision response: SAT & minimum displacement along a given axis?
I'm trying to implement a collision system in a 2D game I'm making. The separating axis theorem (as described by metanet's collision tutorial) seems like an efficient and robust way of handling collision detection, but I don't quite like the collision response method they use. By blindly displacing along the axis of least overlap, the algorithm simply ignores the previous position of the moving object, which means that it doesn't collide with the stationary object so much as it enters it and then bounces out.

Here's an example of a situation where this would matter:

According to the SAT method described above, the rectangle would simply pop out of the triangle perpendicular to its hypotenuse:

However, realistically, the rectangle should stop at the lower right corner of the triangle, as that would be the point of first collision if it were moving continuously along its displacement vector:

Now, this might not actually matter during gameplay, but I'd love to know if there's a way of efficiently and generally attaining accurate displacements in this manner. I've been racking my brains over it for the past few days, and I don't want to give up yet!

~~(Cross-posted from StackOverflow, hope that's not against the rules!)~~

# Answer
> 13 votes
Here's the method I found. It might be flawed, but I haven't found any problems with it yet in my cursory analysis. It also works for arbitrary polygons with a few minor modifications.

In the illustrations below, the blue object is moving and the red object is stationary. **Step 1:** For each polygon, find the two farthest points along the projection of that polygon onto the line perpendicular to the motion vector. **Step 2:** Divide each polygon along the line connecting these points. The half of the polygon that faces the other polygon along the motion vector is the "forward hull". This is the only part of the polygon that can possibly collide. **Step 3:** Project a vector from each point on each polygon's "forward hull" along the motion vector towards the opposite polygon, and check it for intersection with each edge of the opposite polygon's "forward hull". (Possibly slow, but computers are pretty fast nowadays -- right?) (Sorry about the tilted arrow. All the arrows should be parallel.) **Step 4:** Take the shortest vector. This is the exact collision distance. **Step 5:** Voila!

# Answer
> 7 votes
Check out this similar question: Collision Resolution

And also, from http://www.metanetsoftware.com/technique/tutorialA.html#section5 (which you posted a link to :) )

> SECTION 5: Fast-Moving Objects
>
> As mentioned above, small and/or fast-moving objects can produce problems when using a static collision test. There are several approaches that can be taken to handle such objects -- the simplest is to constrain your game design so that such objects aren't needed.
>
> If you absolutely must have them, there are two common methods to deal with small and/or fast-moving objects: swept-collision tests, and multisampling.
>
> --= sweep tests =--
>
> Instead of testing for intersection between two static shapes, we can instead create new shapes by sweeping the original shapes along their trajectory, and testing for overlap between these swept shapes.
>
> The basic idea is described in \[Gomez\], for circle-circle and AABB-AABB sweep tests.
>
> --= multisampling =--
>
> A much simpler alternative to swept tests is to multisample; instead of performing a single static test at the object's new position, perform several tests at several positions located between the object's previous and new position. This technique was used to collide the ragdoll in N.
>
> If you make sure that the samples are always spaced at distances less than the object's radius, this will produce excellent results. In our implementation, we limit the maximum number of samples, so very high speeds will sometimes result in problems; this is something that can be tweaked based on your specific application.

**EDIT**

In summary and AFAIK, there are a few solutions

1. Limit your game to never have a small and/or fast moving object that can even cause this
2. Implement a system that stops collisions from actually happening, as described in the first link I posted
3. Increase your sampling rate for fast and/or small moving objects
4. ... possibly more, but I'm not an expert.

# Answer
> 1 votes
It depends if you only want linear movement, or if you need to cope with angular movement as well.

An alternative to using SAT:

In the case of linear only you can ray-cast against the Minkowski Difference of the two polygons from the origin in the direction of the delta linear velocity of the objects.

If the ray hits the MD, the two objects will collide and the hit point will tell you the time t at which they collided.

Now, if the objects are moving **and rotating** it gets more difficult, but you can still use a similar technique. Conservative Advancement will allow you to deal with this case. This technique is iterative; each iteration will generate a new MD and bring you closer to the time of intersection.

Here is the original draft paper on Conservative Advancement:

Continuous Collision Detection and Physics

I wrote an article explaining the technique in some detail here:

Collision detection for dummies

Hope these help!

---
Tags: collision-detection, physics, platformer, separating-axis-theorem
---


title: UDK and C++, is it possible?

text:
# Question
Title: UDK and C++, is it possible?
I've never used the UDK before and I am wondering: is it possible to use the UDK through C++ instead of UnrealScript?

I saw it's possible to bind external C++ DLL's to UnrealScript, but I don't know if it's possible to call engine functions from inside C++ code.

# Answer
> 5 votes
As you've spotted yourself, it's possible to use C++ within the UDK thanks to `DLLBind`. But there's no way you will be able to call engine functions from C++, you'll have to glue everything together using UnrealScript.

# Answer
> 1 votes
With UDK 4.0 and higher, definitely, since UnrealScript is being replaced with direct C++ APIs. UDK 3.0 and lower, unlikely.

---
Tags: c++, udk
---


# Question
Title: Cross & dot product using ASSIMP's aiVector3t vector class
I'm using ASSIMP's built in aiVector3t class but I can't find any mention of dot product or cross product in the class documentation.

Are these operations defined? If so what is the syntax?

# Answer
> 3 votes
These operations are defined, but not documented correctly by the auto documenting tool (doxygen) because they are not members of the aiVector3t class.

You can find them by looking through the ASSIMP source file "vector3.inl"

```
// cross product
template <typename TReal>
AI_FORCE_INLINE  aiVector3t<TReal> operator ^ ( const aiVector3t<TReal>& v1, const aiVector3t<TReal>& v2)   {
    return aiVector3t<TReal>( v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x);
}

```

The dot product is also in there, although it took me longer to find it as it was mislabelled "scalar product" in the comment

```
// scalar product
template <typename TReal>
AI_FORCE_INLINE TReal operator * (const aiVector3t<TReal>& v1, const aiVector3t<TReal>& v2) {
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

```

Also useful, not in the docs is a typedef for a vector of floats ;

```
typedef aiVector3t<float> aiVector3D;

```

So you can all of these them as follows;

```
    aiVector3D up(0.0f,1.0f,0.0f);
    aiVector3D forward(0.0f,0.0f,1.0f);

    aiVector3D right=forward^up; //get cross product

    float d=forward*up; //get dot product

```

---
Tags: assimp
---


# Question
Title: Will I have an easier time learning OpenGL in Pygame or Pyglet? (NeHe tutorials downloaded)
I'm looking between PyGame and Pyglet, Pyglet seems to be somewhat newer and more Pythony, but it's last release according to Wikipedia is January '10. PyGame seems to have more documentation, more recent updates, and more published books/tutorials on the web for learning.

I downloaded both the Pyglet and PyGame versions of the NeHe OpenGL tutorials (Lessons 1-10) which cover this material:

lesson01 - Setting up the window lesson02 - Polygons lesson03 - Adding color lesson04 - Rotation lesson05 - 3D lesson06 - Textures lesson07 - Filters, Lighting, input lesson08 - Blending (transparency) lesson09 - 2D Sprites in 3D lesson10 - Moving in a 3D world

What do you guys think? Is my hunch that I'll be better off working with PyGame somewhat warranted?

# Answer
Pygame doesn't even have OpenGL bindings; you'd need to use PyOpenGL with it.

If your goal is to learn OpenGL, my suggestion would be to use PyOpenGL, with Pygame. The API is closer to actual OpenGL. (I'd also recommend *not* using NeHe and using the SuperBible instead.)

If your goal is to make a quick game, I'd recommend pyglet. It has all the annoying OpenGL higher-level wrapper stuff written in more Python-friendly ways, e.g. batch for VBOs, groups for render state sorting.

If your goal is to make a high-quality game, I'd recommend neither. Python and OpenGL really don't go together unless you put lots of layers of C in the middle; ctypes is too slow, function calls are too slow, neither Pygame nor pyglet offers very good interfaces for audio, and neither library is really well-maintained.
> 8 votes

# Answer
I would recommend PyGlet, it has both GL and GLU built in, you can also use PyOpenGL(if you're ready to type a million OpenGL calls) for the best result, download it at CheeseShop: http://pypi.python.org/pypi
> 2 votes

# Answer
The actual problem with opengl or directx is that it requires you to learn how to use matrices, which are another subject apart from programming. From what I'm reading, you dislike pointers and don't want C++, then I recommend you to use Panda3D, which has been made to be used with Python. It's in my opinion the best complete 3d game engine for non-programmers who like to do some gameplay as fast as possible.

Learning opengl primitives can be quite easy, but learning how to make something with it is a whole other problem. Programming is one topic, programming graphics involve to learn how to use another kind of processor with another memory, which will be harder to handle if you don't know how to use basical things like pointers.

Don't forget that python is a very good programming language because it's more on the side of the programmer, which is not the case of system language like C or C++. I don't even think we can call python a programming language, since it's more a scripting language: it's too high level.
> 0 votes

---
Tags: 3d, opengl, python, pygame, pyglet
---


# Question
Title: Box2dWeb positioning relative to HTML5 Canvas
I'm new with HTML5 canvas and Box2DWeb and I'm trying to make an Asteroids game. So far I think I'm doing okay, but one thing I'm struggling to comprehend is how positioning works in relation to the canvas. I understand that Box2DWeb is only made to deal with physical simulation, but I don't know how to deal with positioning on the canvas. The canvas is 100% viewport and thus can vary size. I want to fill the screen with some asteroids, but if I hardcore certain values such as bodyDef.position.x = Math.random() * 50; the asteroid may appear off canvas for someone with a smaller screen? Can anybody help me understand how I can deal with relative positioning on the canvas?

# Answer
> 1 votes
To expand on Markus's comment, here is some code from my game. In this code, princeData.width & princeData.height are the width& height of my character in BOX2D.

`pos` is the position of character body in the box2d world .

I keep all dimensions (sizes and positions) in the game as coordinates in the Box2d world, I only need to convert when drawing.

The on-screen size & position will need to change as the browser window gets bigger or smaller. I have some other code which keeps the aspect ratio of the canvas constant, so I only need to worry about one scaling factor (screenScale).

```
screenScale=canvasWidth/box2DWidth;

pos=this.physBody.GetPosition();

canvasContext.drawImage(images.spriteSheet,
            226, 871, //sourceImgX, sourceImgY
            100, 80,  // sourceImgWidth, sourceImgHeight
            pos.x*screenScale,
            (pos.y-this.princeData.height)*screenScale, // canvasX, canvas Y
            this.princeData.width*screenScale,
            this.princeData.height*screenScale); // width, height

```

---
Tags: game-design, box2d, html5, html-canvas, web
---


# Question
Title: Infinite detail inside Perlin noise procedural mapping
I am very new to game development but I was able to scour the internet to figure out Perlin noise enough to implement a very simple 2D tile *infinite* procedural world.

Here's the question and it's more conceptual than code-based in answer, I think. I understand the concept of "I plug in (x, y) and get back from Perlin noise p" (I'll call it p). P will always be the same value for the same (x, y) (as long as the Perlin algorithm parameters haven't changed, like altering number of octaves, et cetera).

What I want to do is be able to zoom into a square and be able to generate smaller squares inside of the already generated overhead tile of terrain.

Let's say I have a jungle tile for overhead terrain but I want to zoom in and maybe see a small river tile that would only be a creek and not large enough to be a full "big tile" of water in the overhead. Of course, I want the same net effect as a Perlin equation inside a Perlin equation if that makes sense? (aka. I want two people playing the game with the same settings to get the same terrain and details every time).

I can conceptually wrap my head around the large tile being based on an "zoomed out" coordinate leaving enough room to drill into but this approach doesn't make sense in my head (maybe I'm wrong). I'm guessing with this approach my overhead terrain would lose all of the cohesiveness delivered by the Perlin. Imagine I calculate (0, 0) as overhead tile 1 and then to the east of that I plug in (50, 0). OK, great, I now have 49 pixels of detail I could then "drill down" into. The issue I have in my head with this approach (without attempting it) is that there's no guarantee from my Perlin noise that (0,0) would be a good neighbor to (50,0) as they could have wildly different "elevations" or p/resultant values returning from the Perlin equation when I generate the overhead map.

I think I can conceive of using the Perlin noise for the overhead tile to then reuse the p value as a seed for the "detail" level of noise once I zoom in. That would ensure my detail Perlin is always the same configuration for (0,0), (1,0), etc. ad nauseam but I'm not sure if there are better approaches out there or if this is a sound approach at all.

# Answer
I believe the process you're talking about is something like a fractal landscape. Fractals allow infinite zoom. Perlin noise, without modification, is not appropriate for a fractal. You also typically want some minimum level of detail when dealing with landscape. Natural landscape doesn't really follow a fractal because the large scale landscape shape is defined by things like tectonic plate movement, glaciers, rivers and such. While the small scale features are defined by weather, erosion and such.

As for ensuring that zoomed out neighbors are good fits for each other. You just need to blend between values. Look into LOD (level of detail) algorithms to see how they work. This is essentially what you would implement for zooming out.
> 2 votes

---
Tags: 2d, procedural-generation, perlin-noise, level-of-detail, fractal
---


# Question
Title: can't spot the error. Trying to increment
I really can't spot the error, or the misspelling. This script should increase the variable currentTime with 1 every second, as long as i am holding the Space button down.

This is Unity C#.

```
using UnityEngine;
using System.Collections;

public class GameTimer : MonoBehaviour {

    //Timer
    private bool isTimeDone;
    public GUIText counter;
    public int currentTime;
    private bool starting;

    //Each message will be shown random each 20 seconds.
    public string[] messages;
    public GUIText msg;

    //To check if this is the end
    private bool end;

    void Update () {
        counter.guiText.text = currentTime.ToString();

        if(Input.GetKey(KeyCode.Space)) {
            if(starting == false) {
                starting = true;
            }

            if(end == false) {
                if(isTimeDone) {
                    StartCoroutine(timer());
                }
            } else {
                msg.guiText.text = "You think you can do better? Press 'R' to Try again!";
                if(Input.GetKeyDown(KeyCode.R)) {
                    Application.LoadLevel(Application.loadedLevel);
                }
            }
        }

        if(!Input.GetKey(KeyCode.Space) & starting) {
            end = true;
        }
    }

    IEnumerator timer() {
        isTimeDone = false;
        yield return new WaitForSeconds(1);
        currentTime++;
        isTimeDone = true;
    }

}

```

# Answer
Unless there's other ocde you're not showing us, `isTimeDone` is never initialized to `true` (bools are `false` by default), so your `StartCoroutine(timer());` never gets called.

When you're running into issues like this, the best thing to do is attach the debugger to it. Barring that, put debug prints on lines you think should be getting hit with the values of variables as they currently are so you can see the program flow.
> 1 votes

# Answer
Well I'm not exactly sure what \`StartCoroutine\` does (I assume it is a form of asynchronous function execution) so I'll skip that. It looks like your problems stem from the fact that you never set \`starting\` back to false. You should probably add that to your second if statement.

On top of that. you never actually set the value \`isTimeDone\` to true outside of the method that only gets called inside the if statement that relies on the true value. You should initialize this value to true in your behaviors constructor.
> 0 votes

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


# Question
Title: Is it ok to initialize an RB_ConstraintActor in PostBeginPlay?
I have a KActorSpawnable subclass that acts weird. In PostBeginPlay, I initialize an RB\_ConstraintActor; the default is not to allow rotation. If I create one in the editor, it's fine, and won't rotate. If I spawn one, it rotates.

Here's the class:

```
class QuadForceKActor extends KActorSpawnable
    placeable;

var(Behavior) bool bConstrainRotation;
var(Behavior) bool bConstrainX;
var(Behavior) bool bConstrainY;
var(Behavior) bool bConstrainZ;

var RB_ConstraintActor PhysicsConstraintActor;

simulated event PostBeginPlay()
{
    Super.PostBeginPlay();

    PhysicsConstraintActor = Spawn(class'RB_ConstraintActorSpawnable', self, '', Location, rot(0, 0, 0));
    if(bConstrainRotation)
    {
        PhysicsConstraintActor.ConstraintSetup.bSwingLimited = true;
        PhysicsConstraintActor.ConstraintSetup.bTwistLimited = true;
    }
    SetLinearConstraints(bConstrainX, bConstrainY, bConstrainZ);

    PhysicsConstraintActor.InitConstraint(self, None);
}

function SetLinearConstraints(bool InConstrainX, bool InConstrainY, bool InConstrainZ)
{
    if(InConstrainX)
    {
        PhysicsConstraintActor.ConstraintSetup.LinearXSetup.bLimited = 1;
    }
    else
    {
        PhysicsConstraintActor.ConstraintSetup.LinearXSetup.bLimited = 0;
    }
    if(InConstrainY)
    {
        PhysicsConstraintActor.ConstraintSetup.LinearYSetup.bLimited = 1;
    }
    else
    {
        PhysicsConstraintActor.ConstraintSetup.LinearYSetup.bLimited = 0;
    }
    if(InConstrainZ)
    {
        PhysicsConstraintActor.ConstraintSetup.LinearZSetup.bLimited = 1;
    }
    else
    {
        PhysicsConstraintActor.ConstraintSetup.LinearZSetup.bLimited = 0;
    }
}

DefaultProperties
{
    bConstrainRotation=true
    bConstrainX=false
    bConstrainY=false
    bConstrainZ=false

    bSafeBaseIfAsleep=false
    bNoEncroachCheck=false
}

```

Here's the code I use to spawn one. It's a subclass of the one above, but it doesn't reference the constraint at all.

```
local QuadForceKCreateBlock BlockActor;

BlockActor = spawn(class'QuadForceKCreateBlock', none, 'PowerCreate_Block', BlockLocation(), m_PreparedRotation, , false);
BlockActor.SetDuration(m_BlockDuration);
BlockActor.StaticMeshComponent.SetNotifyRigidBodyCollision(true);
BlockActor.StaticMeshComponent.ScriptRigidBodyCollisionThreshold = 0.001;

BlockActor.StaticMeshComponent.SetStaticMesh(m_ValidCreationBlock.StaticMesh);
BlockActor.StaticMeshComponent.AddImpulse(m_InitialVelocity);

```

I used to initialize an RB\_ConstraintActor where I spawned it from the outside. This worked, which is why I'm pretty sure it has nothing to do with the other code in QuadForceKCreateBlock.

I then added the internal constraint in QuadForceKActor for other purposes. When I realized I had two constraints on the CreateBlock doing the same thing, I removed the constraint code from the place where I spawn it. Then it started rotating.

Is there a reason I should not be initializing an RB\_ConstraintActor in PostBeginPlay? I feel like there's some basic thing about how the engine works that I'm missing.

EDIT: I found roughly the same initialize code in Whizzle, the Psyonix game made purely with UDK for which the source is available: http://developer.download.nvidia.com/udk/Whizzle\_Creation\_Document\_1\_2.pdf

EDIT 2: The constraints are intialized by PostBeginPlay when loading the level, and that works for the placed objects. Just not for spawned objects.

# Answer
This line

```
BlockActor.StaticMeshComponent.SetStaticMesh(m_ValidCreationBlock.StaticMesh);

```

Invalidates the constraint. Doing

```
BlockActor.StaticMeshComponent.SetStaticMesh(m_ValidCreationBlock.StaticMesh);
BlockActor.PhysicsConstraintActor.InitConstraint(BlockActor, none);

```

Fixes the issue.
> 1 votes

# Answer
I'm not sure of the order that things happen with KActors. It's possible that by PostBeginPlay() the KActor's physics haven't been fully initialized yet. As a test, you could try delaying creation of the constraint until the next Tick.

Alternatively, instead of spawning constraints you could try creating them in the defaultproperties section of your KActor. See UTVehicle\_Hoverboard and its Content subclass for an example.
> 0 votes

---
Tags: udk
---


# Question
Title: How to get the Exact Collision Point and ignore the collision (from 2 "ghost bodies")
I have a very basic problem with Box2D.

For a arenatype game where you can throw scriptable "missiles" at other players I decided to use Box2D for the collision detection between the players and the missiles. Players and missiles have their own circular shape with a specific size (varying). But I don´t want to use dynamic bodies because the missiles need to move themselve in any way they want to (defined in the script) and shouldnt be resolved unless the script wants it. The behavior I look for is as following (for each time step):

* velocity of missiles is set by the specific missile script
* each missile is moved according to that velocity
* if a collision accurs now, I want to get the exact position of impact, and now I need a mechanism to decide if the missile should just ignore the collision (for example collision between two fireballs which shouldnt interact) or take it (so they are resolved and dont overlap anymore)

So is there a way in Box2D to create Ghost bodies and listen to collisions from them, then deciding if they should ignore the collision or should take them and resolve their position? I hope I was clear enough and would be happy about any help!

# Answer
Using a physics engine like Box2D, there is no way to do precisely what you want to do, which is decide at collision time whether the collision should be ignored or whether impulses should be applied. However, you problem is still perfectly solvable.

As far as ensuring certain objects don't collide with each other, what you're looking for are called collision masks (bitmasks), or, as Box2D calls them, filters. That link will bring you to the Box2D manual. Navigate to Chapter 6, Fixtures, and scroll down a page or two to find the Filtering section.

In a nutshell, you specify the category bits for a particular fixture, and then you specify its mask bits. Before Box2D checks for a collision between two objects, it first checks if a collision is allowed by ANDing the category and mask bits of each object together. If the results are non-zero, the objects are allowed to collide. So if you set the category and mask bits of your fireball fixtures to different values, they will not collide with each other.

Now, if the collision masks alone are not enough to do what you want (I'm pretty sure they should be), then Box2D fixtures also have a flag on them indicating whether that fixture is a sensor or not. There is more information available in the manual, but essentially a sensor is a fixture that will cause collisions, but not act as a solid physical structure in the world; other objects will simply pass right through it.
> 2 votes

---
Tags: c++, box2d
---


# Question
Title: How to create a reasonably sized urban area manually but efficiently
I have a game concept that only really works in an urban area that is of reasonable scale and diversity. In terms of what it should look like, think GTA, in terms of the size think more like a small neighbourhood with residents and a few local shops, perhaps a supermarket.

I'm mostly experienced in programming and not at all with modelling, texturing or drawing, but I've found that SketchUp allows me to design interesting looking buildings that I model after real world buildings in my own neighbourhood.

Designing these buildings and other objects can take from a few tens of minutes to a few hours. My question is: what is the best approach for a one man army like me who does manage to model buildings to create an interesting city environment in a reasonable amount of time? My game will not be based on procedural generation, the environment will actually be modelled like GTA cities.

# Answer
> 8 votes
Even with a manual process of model generation, there are some tricks you can use to maximize your output. We can follow the same basic rules for real life conservation. The three R's:

* **Reuse** \- Take the same model and apply a different texture to it. This can save you the time it takes to generate a model. And will give a convincing "that's a different building" feel. But generating textures can be time consuming too, so the savings here are not great.
* **Reduce** \- Is there some part of the city that isn't likely to be visited? You could just use billboard sprites for houses/buildings. From afar, this will look good enough to fool some. The fastest, but least visually appealing way of growing your city.
* **Recycle** \- Use the same model and texture, in a different part of the city. Since you're placing these manually, you can ensure that the same models will be far away from each other. This is the fastest method for growing your city where players will interact with it, but keen-eyed gamers will notice these buildings and you may lose some of the immersive value of your game. (Though with some of the subdivisions I've seen in real life, you could probably get away with this).

---
Tags: models, content-generation, world-design, time-management
---


# Question
Title: Need a good quality bitmap rotation algorithm for Android
I am creating a kaleidoscopic effect on an android tablet. I am using the code below to rotate a slice of an image, but as you can see in the image when rotating a bitmap 60 degrees it distorts it quite a lot (red rectangles) – it is smudging the image! I have set dither and anti-alias flags but it does not help much. I think it is just not a very sophisticated bitmap rotation algorithm.

```
canvas.save();
canvas.rotate(angle, screenW/2, screenH/2);
canvas.drawBitmap(picSlice, screenW/2, screenH/2, pOutput);
canvas.restore();

```

So I wonder if you can help me find a better way to rotate a bitmap. It does not have to be fast, because I intend to use a high quality rotation only when I want to save the screen to the SD card - I would redraw the screen in memory before saving.

Do you know any comprehensible or replicable algorithm for bitmap rotation that I could programme or use as a library? Or any other suggestion?

**EDIT:** The answers below made me think if Android OS had bilinear or bicubic interpolation option and after some search I found that it does have its own version of it called FilterBitmap. After applying it to my paint

```
pOutput.setFilterBitmap(true);

```

I get much better result

# Answer
I have seen term "rotation by shearing" mentioned in several times. I have not tried it myself but it doesn't look impossible to implement

http://www.ocf.berkeley.edu/~fricke/projects/israel/paeth/rotation\_by\_shearing.html

http://www.codeproject.com/KB/graphics/rotatebyshear.aspx
> 2 votes

# Answer
Instead of applying a better rotation algorithm you could improve the image quality by using multisampling instead. That is you make everything say four times bigger, then reduce the final result back down to the required size by averaging pixels.

This will obviously increase your memory requirements, but it should be simple to implement, and it works with transforms other than rotation. You should also be able to get the graphics hardware to do it for you.
> 2 votes

# Answer
I don't know if this will help anyone, but I use this algorithm to pre-rotate all my sprites while I'm loading my resources. In essence I create one sprite, and then the code caches the rotated versions of the sprites for use in the game.

You could also use this to rotate your larger bitmap, but I don't know if this will give you better results or not. It's easy enough to use however, so give it a try.

```
private Bitmap rotate(Bitmap src, int Degrees) {
    double width = src.getWidth();
    double height = src.getHeight();

    double sine = MathEx.sind(Degrees);
    double cosine = MathEx.cosd(Degrees);

    double px1 = width * cosine;
    double px2 = width * cosine - height * sine;
    double px3 = -height * sine;
    double py1 = height * cosine;
    double py2 = height * cosine + width * sine;
    double py3 = width * sine;

    int minx = (int) Math.min(0, Math.min(px1, Math.min(px2, px3)));
    int miny = (int) Math.min(0, Math.min(py1, Math.min(py2, py3)));
    int maxx = (int) Math.max(px1, Math.max(px2, px3));
    int maxy = (int) Math.max(py1, Math.max(py2, py3));

    int dw = Math.abs(maxx) - minx;
    int dh = Math.abs(maxy) - miny;

    int w = 2;
    int h = 2;
    while (w < dw)
        w *= 2;

    while (h < dh)
        h *= 2;

    int xoff = 0;
    int yoff = 0;

    if (w > dw)
        xoff = (int)((w - dw) / 2.0F + 0.5F);
    if (h > dh)
        yoff = (int)((h - dh) / 2.0F + 0.5F);

    Bitmap map = Bitmap.createBitmap(w, h, Config.ARGB_8888);
    map.eraseColor(0x00000000);

    for (int x = 0; x < dw; x++) {
        for (int y = 0; y < dh; y++) {
            int sx = (int) ((x + minx) * cosine + (y + miny) * sine);
            int sy = (int) ((y + miny) * cosine - (x + minx) * sine);

            if (sx < 0 || sx >= width || sy < 0 || sy >= height)
                continue;

            map.setPixel(x + xoff, y + yoff, src.getPixel(sx, sy));
        }
    }

    return map;
}

```
> 2 votes

# Answer
This looks similar to when you have a vector model and you rotate it, and rotate the result, and rotate the result, etc. Eventually the model will be noticeably distorted due to rounding. The solution is have a read-only source and always transform from that. Not sure how that applies to your android kaleidoscope effect (it looks great to me), but I hope that's helpful.
> 1 votes

---
Tags: android, rotation, image
---


# Question
Title: Rotate object Up/Down/Left/Right in any orientation
I'm rendering model at the origin with a fixed camera looking at it positioned on the z axis.

I want to be able to rotate the model up/down and left/right. Currently I have 2 variables, `HorizontalRotation` and `VerticalRotation`. When calculating the world matrix I rotate about the Y axis by `HorizontalRotation` and about the X axis by `VerticalRotation`.

The `..Rotation` variables are controlled by pressing up/down/left/right arrow keys.

The problem I'm having is that the rotations are happening relative to the object.

Lets say it's a model of the world. Pressing Up a bit would let me look at the north pole.
Currently when i press right the earth spins infront of the camera on its axis; I'm still looking at the north pole.

How can i get it so that no matter what rotations are currently applied i can always rotate my model relative to the camera/world axis?

# Answer
> 3 votes
First of all, you cannot describe an arbitrary rotation obtained by such combinations of left/right and up/down rotations using only two angles. You need either a third angle somewhere, or another method to describe rotations.

* Third angle: using a third angle will not necessarily be easy. You would probably use Euler angles (using three angles but only two axes) or Tait-Bryan angles (using three angles around three axes, in some cases called yaw-pitch-roll). (Note: Tait-Bryan angles are often confused with Euler angles, sometimes deliberately because they are very similar after all).
* Rotation matrix: If you use Euler angles, you will find out that computing the new angle values when the user presses left/right etc. is not trivial at all. In fact this is often done by computing the resulting matrix transformation and going back to Euler angles. So why not **directly store a rotation matrix and just ditch the angle variables?**.
* Quaternions: If you feel comfortable with quaternions, you could try storing the camera orientation using a unit quaternion, which will be more efficient both in storage and in computation. However you should first try to get comfortable with the matrix way.

So what should you do? The way I see it, you start with an identity matrix:

```
Matrix ModelMatrix = Matrix.Identity;

```

When the user presses left/right, you compute a rotation matrix around the vertical axis and you multiply `ModelMatrix` by it:

```
ModelMatrix = ModelMatrix * Matrix.CreateRotationX(angle);

```

And when the user presses up/down, you do the same around the horizontal axis:

```
ModelMatrix = ModelMatrix * Matrix.CreateRotationY(angle);

```

The key here is the **multiplication order**. The new rotation must be performed *after* the already applied rotation.

# Answer
> 1 votes
Creating the desired behaviour using quaternions would look something like that (using XNA built-in Matrix and Quaternion structures):

```
    Quaternion rotation = Quaternion.Identity

    /// <summary>
    /// Moves the camera in specified direction around an arbitrary axis.
    /// </summary>
    /// <param name="direction">The direction to move to.</param>
    /// <param name="amount">The amount to move in radians around the sphere's origin.</param>
    public void Move(Vector2 direction, float amount)
    {
        if (direction != Vector2.Zero)
        {
            Rotation *= Quaternion.CreateFromRotationMatrix(
                Matrix.CreateRotationX(direction.Y * amount) *
                Matrix.CreateRotationY(direction.X * amount));
        }
    }

```

As with matrices, it is important to multiply the new rotation after the current rotation is applied!

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


# Question
Title: How to have operations with character/items in binary with concrete operations?
I have the next problem.

A item can have a lot of states:

```
NORMAL  = 0000000
DRY     = 0000001
HOT     = 0000010
BURNING = 0000100
WET     = 0001000
COLD    = 0010000
FROZEN  = 0100000
POISONED= 1000000

```

A item can have some states at same time but not all of them

> * Is impossible to be dry and wet at same time.
> * If you COLD a WET item, it turns into FROZEN.
> * If you HOT a WET item, it turns into NORMAL
> * A item can be BURNING and POISON

Etc.

I have tried to set binary flags to states, and use AND to combine different states, checking before if it is possible or not to do it, or change to another status.

Does there exist a concrete approach to solve this problem efficiently without having an interminable switch that checks every state with every new state?

It is relatively easy to check 2 different states, but if there exists a third state it is not trivial to do.

# Answer
When I need to use flags I usually do something along these lines.

```
enum obj_state
{
    NORMAL      = 0x00000;
    DRY         = 0x00002;
    HOT         = 0x00004;
    BURNING     = 0x00008;
    WET         = 0x00010;
    COLD        = 0x00020;
    FROZEN      = 0x00040;
    POISONED    = 0x00080;
};

int objFlags;

void DryOn() { objFlags |= DRY; }
void HotOn() { objFlags |= HOT; }
// etc...

void DryOff() { if (FlagOn(DRY)) objFlags ^= DRY; }
void HotOff() { if (FlagOn(HOT)) objFlags ^= HOT; }
// etc...

bool isDryOn() { return FlagOn(DRY); }
bool isHotOn() { return FlagOn(HOT); }
// etc...

// If the given Bit is on this will return true.
bool FlagOn(obj_state s) { return (objFlags & s) == s; }

// returns -1 if failed, 1 if successful
int apply_cold(Object obj)
{
    if (obj.isWetOn())
    {
        obj.ColdOff();
        obj.WetOff();
        obj.FrozenOn();
    }
    else
        return -1;

    return 1;
}

//---------------------------------
// alt way of doing DryOn and WetOn
// since these conditions can not be
// active at the same time.
void DryOn()
{
    if (isWetOn())
        return;
    else
        objFlags |= DRY;
}

void WetOn()
{
    if (isDryOn())
        return;
    else;
        objFlags |= WET;
}

```

This makes using them for stuff like apply\_cold() very easy and you can obviously build in your state conditions like dry and wet.
> 6 votes

# Answer
Two observations:

1. Your condition system seems to have two orthogonal axes: temperature and poison. Represent them as such.
2. When thinking about this you should separate *transitions* from *states*. `COLD` and `HOT` are transitions in the way you mention them, not states.

Combining those observations would result in something like this:

```
// These is the representation of the two axes.
int temperature; // can be between -2 and +2, 0 is normal, 1 is hot, 2 is burning, -1 is cold, -2 is frozen
bool poisoned;

// These methods represent state transitions.
void applyHeat() {
    if ( temperature <= 2 ) {
        ++temperature;
    }
}

void applyCold() {
    if ( temperature >= -2 ) {
        --temperature;
    }
}

void applyPoison() {
    poisoned = true;
}

void removePoison() {
    poisoned = false;
}

```
> 7 votes

# Answer
Representing your states as bitmask like you write, you can just translate your descriptions of the constraints into code:

```
if ( (state & HOT) && (state & COLD) ) {
    state &= ~HOT;
    state &= ~COLD;   // reset both HOT and COLD flags if both are set
}

if ( (state & COLD) && (state & WET) ) {
    state &= ~WET;    // cold items can't be wet
    state |= FROZEN;  // instead, they're frozen
}

if ( (state & HOT) && (state & WET) ) {
    state &= ~WET;    // hot and wet items dry up...
    state &= ~HOT;    // ...and cool down
}

// add other constraints here...

```

You could wrap that into an `makeStateConsistent()` that you can call before testing the state bits to ensure that the state makes sense.

However, one limitation of this approach is that it can't account for the order of state changes. For example, if you want to have a different outcome for hot items that become wet than for wet items that become hot, you can't do it like this: all the `makeStateConsistent()` method sees is a hot and wet object, with no information about how it got to be that way.

Instead, what you could do is make the item state private (at least conceptually) and manipulate it through a set of methods like `coolItem()`, `heatItem()`, `wetItem()`, `dryItem()` and so on. That way, the state change methods themselves can take care of any additional changes. For example, the `heatItem()` method might look something like this:

```
if ( state & COLD ) {
    state &= ~COLD;    // cold items become normal temp when heated
    if ( state & FROZEN ) {
        state &= ~FROZEN;  // ...and melt if they were frozen
        state |= WET;
    }
} else if ( state & WET ) {
    state &= ~WET;    // wet items dry up when heated, stay normal temp
} else {
    state |= HOT;     // dry normal temp items become hot
}

```

Of course, you may still want to also have a `makeStateConsistent()` method as a backup, just in case you have a bug in your state change methods.

Also, in some cases you may be able to simplify your code by eliminating unnecessary states. For example, do you really need a separate `FROZEN` state, or would it be enough to just treat any cold and wet items as frozen?
> 3 votes

---
Tags: c++, rpg, design-patterns, binary
---


# Question
Title: Starting a Java activity in Unity3d Android
I wrote a small Java activity extension of UnityPlayerActivity similar to what is described in the Unity docs. It has a method for displaying a song picking interface using an ACTION\_GET\_CONTENT intent. I start this activity using startActivityForResult() and it absolutely kills the performance of my Unity game when it is finished, it drops to about .1 FPS afterwords. I've changed removed the onActivityResult function and even tried starting the activity from inside an onKeyDown event in Java to make sure my method of starting the activity from Unity was not the problem. Heres the code in a basic sense:

```
package com.company.product;

import com.unity3d.player.UnityPlayerActivity;
import com.unity3d.player.UnityPlayer;
import android.os.Bundle;
import android.util.Log;
import android.content.Intent;

public class SongPickerActivity extends UnityPlayerActivity {

    private Intent myIntent;
    final static int PICK_SONG = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("SongPickerActivity", "OnCreate");
        myIntent = new Intent(Intent.ACTION_GET_CONTENT);
        myIntent.setType("audio/*");
    }

    public void Pick() {
        Log.i("SongPickerActivity", "Pick");
        startActivityForResult(myIntent, PICK_SONG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

```

This is causing me a bit more of a headache than it should and I would be thankful for any sort of advice. Does anyone have any experience with using custom activities in Unity Android or any insight on why this is happening or how to resolve this?

# Answer
> 2 votes
I don't think an Activity is what you are looking for.

Activities are meant to be shown to the user, one at a time. If you're looking to play music in the background of your app you probably want to create a class that handles audio files.

Here's a few android classes that are useful in managing playback of sound.

```
android.content.res.AssetManager
android.media.AudioManager
android.media.SoundPool

```

---
Tags: java, android, unity, performance
---


# Question
Title: Should I be worrying about limiting the number of textures in my game?
I am working on a GUI in XNA 4.0 at the moment. (Before you point out that there are many GUIs already in existance, this is as much a learning exercise as a practical project). As you may know, controls and dialogs in Windows actually consist of a number of system-level windows. For instance, a dialog box may consist of a window for the whole dialog, a child window for the client area, another window (barely showing) for the frame, and so on. This makes detecting mouse hits and doing clipping relatively easy. I'd like to design my XNA GUI along the same lines, but using overlapping Textures instead of windows obviously.

My question (yes, there's actually a question in this drivel) is: am I at risk of adversely affecting game performance and/or running low in resources if I get too nuts with the creating of many small textures? I haven't been able to find much information on how resource-tight the XNA environment actually is. I grew up in the days of 64K ram so I'm used to obsessing about resources and optimization.

Anyway, any feedback appreciated.

# Answer
> 3 votes
Any slowness in this situation would be caused by the switching of texture states, as another poster also mentioned.

If you are finding that you have performance problems you can combine all of your small textures into a larger sprite sheet texture to eliminate the switching of which texture is on the GPU. You will just need to use a rect to access the correct portion of the sprite sheet when you make the call to ContentManager.Load().

# Answer
> 1 votes
Well no, generally not. Only thing is that changing the texture state is somewhat slow. So using less textures can make the rendering of the GUI a whole lot faster (~a few milliseconds). But it won't impact anything outside of the GUI rendering code. We are talking about really tiny amounts of memory here and also tiny amount of indices. That wouldn't even have made a impact 10 years ago.

# Answer
> 0 votes
> I'd like to design my XNA GUI along the same lines, but using overlapping Textures instead of windows

This is a bit of a tangent on your actual question, but bear with me.

I may be taking your wording a bit too literally but in the event I am not, I would suggest that you do not represent your GUI elements with a series of `Texture2D` instances, but rather, a collection of `Rectangle` instances. You could then wrap the `Rectangle` with something such as `BaseWindow` class, where each base window class holds both a rectangle and a texture, as well as other tidbits that you will need to manage the object. This will allow you to have windows that are not the same size as your texture, so that you can employ a few tricks (such as a 1x1 pixel texture being stretched to entirety of the window to simply fill with a solid color).

Now on to your real question.

> am I at risk of adversely affecting game performance and/or running low in resources if I get too nuts with the creating of many small textures?

If you are loading up all of your textures via the `ContentManager`, then your chances of adversely affecting performance is minimal. The reason being that the content manager class handles duplicate texture loading for you, by simply returning a reference to the original loaded texture, should you try to load the same texture all over again. This makes it very easy for you, since you really don't have to worry about managing duplicate resources.

However, common sense and good programming practice still applies.

---
Tags: xna, gui, assets
---


# Question
Title: Quaternion based rotation and pivot position
I can't figure out how to perform matrix rotation using Quaternion while taking into account pivot position in OpenGL.What I am currently getting is rotation of the object around some point in the space and not a local pivot which is what I want. Here is the code \[Using Java\]

Quaternion rotation method:

```
  public void rotateTo3(float xr, float yr, float zr) {

    _rotation.x = xr;
    _rotation.y = yr;
    _rotation.z = zr;

    Quaternion xrotQ = Glm.angleAxis((xr), Vec3.X_AXIS);
    Quaternion yrotQ = Glm.angleAxis((yr), Vec3.Y_AXIS);
    Quaternion zrotQ = Glm.angleAxis((zr), Vec3.Z_AXIS);
    xrotQ = Glm.normalize(xrotQ);
    yrotQ = Glm.normalize(yrotQ);
    zrotQ = Glm.normalize(zrotQ);

    Quaternion acumQuat;
    acumQuat = Quaternion.mul(xrotQ, yrotQ);
    acumQuat = Quaternion.mul(acumQuat, zrotQ);

    Mat4 rotMat = Glm.matCast(acumQuat);

    _model = new Mat4(1);

   scaleTo(_scaleX, _scaleY, _scaleZ);

    _model = Glm.translate(_model, new Vec3(_pivot.x, _pivot.y, 0));

    _model =rotMat.mul(_model);//_model.mul(rotMat); //rotMat.mul(_model);

    _model = Glm.translate(_model, new Vec3(-_pivot.x, -_pivot.y, 0));

   translateTo(_x, _y, _z);

    notifyTranformChange();
   }

```

Model matrix scale method: public void scaleTo(float x, float y, float z) {

```
    _model.set(0, x);
    _model.set(5, y);
    _model.set(10, z);

    _scaleX = x;
    _scaleY = y;
    _scaleZ = z;

    notifyTranformChange();
  }

```

Translate method: public void translateTo(float x, float y, float z) {

```
    _x = x - _pivot.x;
    _y = y - _pivot.y;
    _z = z;
    _position.x = _x;
    _position.y = _y;
    _position.z = _z;

    _model.set(12, _x);
    _model.set(13, _y);
    _model.set(14, _z);

    notifyTranformChange();
   }

```

But this method in which I don't use Quaternion works fine:

```
  public void rotate(Vec3 axis, float angleDegr) {
    _rotation.add(axis.scale(angleDegr));
    //  change to GLM:
    Mat4 backTr = new Mat4(1.0f);

    backTr = Glm.translate(backTr, new Vec3(_pivot.x, _pivot.y, 0));

    backTr = Glm.rotate(backTr, angleDegr, axis);

    backTr = Glm.translate(backTr, new Vec3(-_pivot.x, -_pivot.y, 0));

    _model =_model.mul(backTr);///backTr.mul(_model);
    notifyTranformChange();

   }

```

# Answer
The above is the implementation of the world rotation matrix using OpenTK.

```
Matrix4    m_worldMatrix;
Quaternion m_rotation;
Vector3    m_scale;
Vector3    m_translation;

void RotateBy(float radians, Vector3 rotation_axis)
{
    GL.MatrixMode(ModelView);

    m_rotation = Quaternion.FromAxisAngle(rotation_axis, radians) * m_rotation;

    m_worldMatrix = Matrix4.Scale(m_scale) *
                    Matrix4.Rotate(m_rotation) *
                    Matrix4.CreateTranslation(m_translation);

    GL.MultMatrix(ref m_worldMatrix);
}

```

Notice that you must always multiply the world matrix in this order: Scale * Rotate * Translate. I hope this helps.
> 2 votes

# Answer
Is the point in space that is used for the rotation known to you? Or can you find out what point it is?

If you can find this point do a translation from that point to your local point, then do the rotation and after that do a translation back.
> 0 votes

---
Tags: opengl, mathematics, quaternion
---