# Question
Title: Showing Parallax entity and AutoParallax entity on same scene in AndEngine
How do I create both a parallax background and an autoparallax background in the same scene using ?

The problem is, I want one entity to move at a constant speed regardless of the camera's movement, and I want another entity to move depending on the camera's movement.

To do it, I created a parallax background and an autoparallax background. The problem is, I can show these two background separately by doing mScene.setBackground(background); But I want these two backgrounds to show at the same time.

# Answer
Instead of using `mScene.setBackground(background)` take a look at `background.attachParallaxEntity()`. The AndEngine example for autoparallax is a good example on how to do this. Here's the critical part:

```
final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack, vertexBufferObjectManager)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid, vertexBufferObjectManager)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront, vertexBufferObjectManager)));
scene.setBackground(autoParallaxBackground);

```

In that example, you can see it's using three different relative "speeds" relative to the camera movement. An alternative approach, in light of your comment that you'd like something to move at a constant speed, is to not think of it as officially a "background," but just treat it as a sprite, with a z-index behind your "foreground" entities, and use a MoveModifier to move the sprite at a constant speed. Here's what I mean:

```
private void moveBackground() {
    //create your sprite
    Sprite background = new Sprite(params);

    //Give it movement.
    background.registerEntityModifier(new MoveModifier(params...));

    //Set its z-index to behind your entities.
    background.setZIndex([some number lower than your foreground]);

    //attach it to your scene.
    scene.attachChild(background);

    //tell the scene to sort itself so the Z indices are correct.
    scene.sortChildren();
}

```

Don't forget when attaching or removing sprites that it must be done in one of the main threads.
> 1 votes

---
Tags: andengine, parallax-scrolling, scene
---


# Question
Title: Client Side Logic vs Server Side Logic for HTML5 Game
I'm writing an HTML5 game that takes place in a single screen and does not have any data that would need to be saved (except for a score). I am writing all of my canvas logic on the front end. because it seemed like the easiest way to program interactions. However Ive been reading on r/gamedev that the best way to organize games is to sent client input to the server and have the server render the results on the client. I have a couple questions about this:

1.) If my game takes place on a single screen (meaning no changes in background, enemies, etc. Think Space Invaders), is it worth putting my game logic on the server?

2.)If I do put my logic on the server, how can i facilitate clean communication with the client? Web sockets? or plain HTTP? Using a WebSocket seems straightforward for this kind of task, but they are not supported by all browsers. On the flip side I'm kind of hazy on how HTTP could be used to send and receive data from the client.

Any advice would be great.

# Answer
> 7 votes
Generally, this advice is given not because of abstraction or code cleanliness but rather because gameplay logic that is sensitive must be simulated by an authorative server to prevent cheating and hacking. Long story short: If you don't particularly care about players hacking their score - don't bother.

If your game is multiplayer, then you should looking into making the client nothing but a "dumb terminal" and display for the game. Generally, this involves the client only sending inputs and actions to the server, and the server sends the results back to the entities that may be interested in his result. You can look at this article for getting started with socket.io.

It's a broad topic and tough to cover in this answer but the gist of the idea is that. For example, instead of just moving and telling every other player "I got 100 points"... you instead send "I shot", and the server simulates your shot. Then, when the server sees someone was "shot" then it sends a result back to all other players who may be interested that this object was shot, so something can explode, the killer can get points etc.

# Answer
> 1 votes
it depends on what game you're trying to make and do you care about cheating in your game.

if you don't care about cheating, it will be much more easier to just do everything on client and simply relay the actions/results via the server to other clients.

if you do care about anti-cheating, and depending on game type, you might want to make some predictions on client side so that your game dont suffer from round-tip delay. in short, your client need to have the logic and also send the actions to the server to be simulated, but your client will only trust the results from the server.

---
Tags: html5, html-canvas
---


# Question
Title: How to create simple acceleration in a 2D sprite?
So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all.

```
if (KeyboardState.IsKeyDown(Keys.Right))

            while (motion.X < 1)
                motion.X += 0.001f + motion.X;

```

I want to know why exactly it won't work, and any possible alternate algorithms.

# Answer
To implement basic acceleration you need to know a little physics. The basics you need to know about are the relationships between:

* **Position** \- Where your object is
* **Velocity** \- The direction and rate your object is changing its **position**
* **Acceleration** \- The direction and rate your object is changing its **velocity**

So, to add acceleration, you need to have Position and Velocity already implemented. I'll assume you're doing that already, since you're asking about Acceleration.

Since you have velocity already implemented, I'll assume you have something like:

```
player.x += player.velocity.x * dt;
player.y += player.velocity.y * dt;

```

Where `dt` is the time since the last update. Now if we want to change the velocity with respect to time, we just need to add a line like this:

```
player.velocity.x += player.acceleration.x * dt;
player.velocity.y += player.acceleration.y * dt;

```

Now, if we want to modify that acceleration with the keyboard, we can do something simple like:

```
if (KeyboardState.IsKeyDown(Keys.Right))
    player.acceleration.x += .01f;

```
> 13 votes

# Answer
You should get rid of the while loop. Your game is stalling in that loop since it can't escape the loop until motion.X is \>= 1. You should just use the the statement within the loop and experiment with larger float values such as .01 or .1 .
> 3 votes

# Answer
you need to make the acceleration happens over time (per game tick) gradually.

you need to time the acceleration in such that every N seconds, it make your character moves faster until a limit is reached.

your while statement make it happen in a single tick, it make no difference than assigning X = 1.
> 0 votes

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


# Question
Title: How to detect screen boundary using AndEngine GLES1?
I am using the `AnalogOnScreenControl` to move my sprite around the screen. I would like to restrict the sprite so it can not move outside the screen boundaries.

I have tried putting a line at the top of the screen and checking collisions between the sprite and the line, but the effect is that the sprite sticks to the top line. It does not move at that point. So I tried the `onAccelerometerChanged()` method as an alternative, but that also doesn't work.

How do I detect the screen boundary and prevent the sprite from going beyond it?

# Answer
> 3 votes
What you're asking for is a subset of collision handling. Essentially, when you've moved the player outside of the scene, you want to move the player back into the scene, and you want to do that in the same update as you've moved the player, immediately after moving the player, so the out-of-scene location never gets rendered.

Lets assume you do something like this to move the sprite:

```
physicsHandler.setVelocity(pValueX*100, pValueY*100);

```

Now you want to move them back into the scene if they're outside it. So we're going to need a new method. Lets throw in a method call right after moving the sprite (we'll call it "adjustToSceneBinding()" so you have this:

```
physicsHandler.setVelocity(pValueX*100, pValueY*100);
adjustToSceneBinding(player);

```

Sidenote, you can do the adjustToSceneBinding() method from inside or outside the Sprite. Doing it from inside (i.e., have sprite be a class that extends sprite) is probably more proper, but for our purposes doesn't matter. Now the adjustToSceneBinding code:

```
public boolean adjustToSceneBinding(Sprite player) {

    // Correct the X Boundaries.
    if (player.getX() < 0) {
        player.setX(0);
    } else if (player.getX() + player.getWidth() > CAMERA_WIDTH) {
        player.setX(CAMERA_WIDTH - player.getWidth());
    }
}

```

If the sprite's X coordinate is less than zero, move them back to zero. If the sprite's X PLUS the player's width is more than the camera width, move them back to the camera width minus the player width. Don't forget the player X coordinate represents the left side of the sprite. That's why I'm taking into account the width in addition to the position for calculating the right side.

The above code only addresses left/right movement, but I'm going to let you extrapolate how to do the same for up down.

---
Tags: android, collision-detection, andengine, collision-resolution
---


title: How to make a map

text:
# Question
Title: How to make a map
For school my group and I are going to make a 2d turn based strategy game on android.

We are trying to make a simple version of Advanced Wars (Gameplay).

But we don't really know how to make the map and what the best way is to divide the map in tiles.

We found an example, that each tile is a canvas but that was only with 9 tiles.

Ideally, we would like to have a map that is bigger than the screen and you can move around it just like when an image is too big for the screen.

We only have 5 weeks, so we can't afford it to experiment a lot.

# Answer
> 6 votes
You've noted down Android on your answer, so I'm going to centralize certain aspects of this answer according to that but it's universally applicable despite your platform.

First and foremost, what you see here and in Advance Wars is a process calling tile mapping. Segement of the maps are split into layered tiles, as shown here:

With this out of the way, there's a lot of tools you can find that will help you map out your game and apply different effects. A popular one with decent parsers available to you will be Tiled. With Tiled, you can create tilesets (chunked images you can use to compose a map), as shown here:

And then use those chunked up bits to create your world / battle zone maps. If you're curious how Advance Wars set there tileset up, I've included a reference image:

Once you've layed our your maps, created tileset and set objects to define game behavior with objects in Tiled (they're just tiles with certain behaviours and properties - you can use these to define monsters, items and other stuff) and you can use tile properties to define terrain tags.

Once you've completed this, you can then import them into your game and start doing some processing on them to really make your game. If you use something LibGDX you will gain access to a camera component and Tiled map loader - which will allow you to have the panning effect you want along with the ability to load the maps from Tiled with realitively little effort.

Good luck - if you have any questions just leave a comment!

# Answer
> 0 votes
there is an easier way to deal with the 'map', tiles based map were originally invented during the time where RAM and data storage were expensive and very little. if the map isn't too big, you can just make an image with any image editor and make it proportion to the grid size of your game. for the grid, you can just make a text file, and use csv (or any format you familiar with) to represent moveable slots and decorations.

let's say 0 is declaration, 1 is moveable slot.

https://i.stack.imgur.com/udncD.png

for the text file, it will look something like this

0,0,0,1

0,0,1,1

0,0,1,1

of cause this method has its down side, you cant reuse the assets as much as tiled based map and it will cost more resources to load the map. However it will save you a lot of time trying to produce nicely divided tiles!

---
Tags: 2d, android, tiles, maps
---


# Question
Title: Tips and Tools for creating Spritesheet animations
I am looking for a tool that I can use to create sprite sheet easily.

Right now I am using Illustrator, but I can never get the center of the character in the exact position, so it looks like it is moving around(even though its always in one place), while being loop through the sprite sheet. Is there any better tools that I can be using?

Also what kind of tips would you give for working with a sprite sheet? Should I create each part of the character in individual layers (left arm, right arm, body, etc.) or everything at once? any other tips would also be helpful! thank you

# Answer
From the problems that you are having I recommend that you do the following:

First, work with layers and folders. It really does help, Group individual sprites together in folders so that you can move the whole of them around and parts that are replicated should exist on seperate layers.

(So if there is a sword or something it should be on a layer, eyes should be on a layer, etc). Thats where the real power of these type of applications are for such a task. If you mess something up, you don't mess it all up just that layer.

Then, enable the ruler and enable the grid. (Also take the time to set them up correctly in the preferences menu). If click the ruler and drag away from it, you can create guidelines. Setting up your own limits using the guidelines will allow you to snap the sprites (which should now be in folders) to the grid lines allowing you to position them far better.

Then finally, if things still seem a bit out of phase when the animation is playing. If you zoom all the way in (you may need to make sure this is enabled in the preferences menu) you can see an individual per-pixel grid. Which should allow you to place things exactly where you need them to be.
> 14 votes

# Answer
If you have 3D models there is a program made by EnvyGames, **SpriteWorks**, which will make 2D sprite sheets out of the models for you. Allows you to play animations and customize a bunch of stuff.

I think it's a bit pricey for what it is, $49.99.

Here is a tutorial on how to use SpriteWorks

**Creating Sprites from 3D Models - EnvyGames**
> 4 votes

# Answer
Spritesheets? Mac? Take Zwoptex: http://zwoptexapp.com/
> 4 votes

# Answer
Your question sounds a lot like the one I answered here: What is a good tool for producing animated sprites?

You can basically create your animations in whichever program you prefer. When using Illustrator I suggest you create the animation-steps on layers or even import the artwork into Flash for animation (since Flash CS4 you can also create bones in flash. See here for a tutorial).

Once you have your animations done, just export the frames to images and then use the method described in my answer (above) to create a sprite-sheet.
> 3 votes

# Answer
http://www.darkfunction.com/editor/

Whoops: Apologies for sneaky self promotion. But this might be just what you are looking for.

EDIT: Just an update that I have made this tool free and opensource. https://github.com/darkFunction/darkFunction-Editor
> 3 votes

# Answer
If you have a bunch of images, here's a tool you can use to create sprite sheets:

http://www.retroaffect.com/blog/159/Image\_Atlas\_Packer/#b

It's completely free, and will pack a bunch of images into N number of sprite sheets.
> 2 votes

# Answer
You might end up loving this tool:

http://www.bottomap.com/Software/A4B/A4B.html
> 2 votes

# Answer
Sprite Animation Software automatically creates a sprite sheet that contains an ordered sequence of all frames of sprite animation. This software doesn't work with already created sprite sheets - it creates a sprite sheet with prescribed orientation(vertical, horizontal or table) and prescribed size.

Sprite animation is created by the same tool using hinged 2d-bones models and textures. watch video on youtube
> 1 votes

# Answer
I've been using Texture Packer to create sprites from a folder of PNG images. I'm porting a game originally developed in Flash, so I'm simply exporting each frame of the MovieClip to png and then importing those images in Texture Packer.

Another similar tool is Zwoptex

(The latter is Mac software, but TP has a version for Windows too.)
> 0 votes

---
Tags: graphics, animation, art, sprites, spritesheet
---


# Question
Title: Making The Player Stop Bouncing And Stop Sinking In The Ground In A Platformer XNA
Heres a problem i've been having. I have a platformer, and whenever my player hits the ground he keeps bounding. Here's the falling code

```
iceBoy.moveY++;
iceBoy.position.Y += moveY;

```

Now heres the collision code

```
if (HitGround())
{

    iceBoy.moveY = -4;

    if (gamepadState.IsButtonDown(Buttons.A))
    {
        iceBoy.moveY = -25;
    }

    touchGround = false;
}

```

i tried lowering the iceBoy.moveY = -4, or iceBoy.moveY -= 1, but then ice boy just falls through the ground never to be seen again. How to i make it so he stops bouncing and without him falling staright through a block?

**UPDATE 1:** At just -4, he bounces little enough too make it look kind of good, but he sinks through the ground first then floats back up and it looks really bad. How can i fix this easily, with just a few lines of code

# Answer
> 3 votes
Correlating the bounce to the fall speed will help you. When you detect a collision and need to bounce, try setting the bounce this way:

```
iceBoy.moveY = -(iceBoy.moveY * .7);
if(abs(iceBoy.moveY) < BOUNCE_MIN_VALUE)
   iceBoy.moveY = 0;

```

Assuming the `moveY` value is positive from iceBoy's decent (you may want to add some checks for that), this code will reduce the bounce speed every time. So there won't be as much time to build up speed on the way back down, so the next time the reduced bounce is even smaller and so on. You'll want to cut this off at some point so you're not bouncing forever.

More complicated would be to implement a *real* bounce. Either using a physics engine, or extending your simple implementation. Then make sure to add drag to the equation so that the bouncing settles.

Find out more about implementing that here. (Apply a lot of drag if you want to come to a stop quickly).

# Answer
> 0 votes
It looks like you have 2 variables with the same name. iceBoy.moveY which you set in the HitGround() routine and a local variable called simply moveY which is what actually is getting added to the position of your object and never gets changed in the HitGround() routine.

---
Tags: xna, 2d, xna-4.0, physics, platformer
---


# Question
Title: How can I efficiently create/store/implement animations as I add to my game?
My game's characters are made up of different parts (head/body/legs/etc), and whatever items they have equipped. As I'm creating the animation system for my game, I want to try to anticipate a large number of combinations for different pieces for each character. Originally, I had planned on having a frame-by frame animation for each piece for each animation, and then layer them to combine them into a character, but this seems like it would be a lot of work for my artist, and that the memory/disk size would start to add up as well since we would need a sprite for *every* frame, of *every* customization of *every* piece, in *every* animation, for *every* character.

What efficient ways are there to create/implement these animations as we add more and more configurations to our game?

**Edit:** I'll also point out that my artist is using flash to make the graphics and animations, but the game is in Java (libgdx, but I can also hard code OpenGL if I need to).

# Answer
> 1 votes
I'd never found an answer to this question until recently with the Kickstarter project Spine.

It looks like it will do exactly what I'm asking :)

# Answer
> 1 votes
You could create a structure of points where you can "attach" images. Then you could set these points according to the current frame. For example a simple hero character which can have different helmets and different melee weapons and has the animations "move" and "strike", for these animations you have a sprite sheet with everything except the weapon and the helmet, now you can take these sprite sheet and a text editor and note for each frame where the helmet and the weapon is, including rotation and maybe size too. Using this data you can dynamically compose the character.

Example code for better understanding:

```
heroSprite.drawFrame(curFrame);

int[] coordinatesX={4, 5, 6,  7, [...]};
int[] coordinatesY={8, 9, 10, 9, [...]};
int[] rotation={10, 15, 20, 15, [...]};
weaponSprite.setPosition(coordinatesX[curFrame], coordinatesY[curFrame]);
weaponSprite.setRotation(rotation[curFrame]);

weaponSprite.draw();

```

# Answer
> 1 votes
Have your artist create template animations using generic parts that can be swapped out.

If possible with libgdx, find each generic part (eg, with an instance name), and set visible=false for the generic part and addChild() the replacement part with copied position/rotation from the generic part.

Alternatively, have the artist save the generic animation with Choose File \> Save As \> Save as Type \> uncompressed XFL. The XFL file format is a way to represent a Flash Professional document as an XML-based, open folder of files.

From the XFL folder, look at the positions and rotations in XML to build the tables as suggested by Mr. Beast. After you figure out the format, you could write a tool to do this automatically so that when animations are updated, you can quickly get them into the game.

---
Tags: architecture, graphics, animation
---


# Question
Title: 3Ds Max is exporting model with more normals than vertices
I made a simple teapot with the "Create Standard Primitives" option and exported it as a collada file, ended up with this:

\< float\_array id="Teapot001-POSITION-array" **count="1590"**\>

\< float\_array id="Teapot001-Normal0-array" **count="9216"**\>

For what I know there should be only one normal per vertex, am I wrong? What am I supposed to do with that much normals? Just put them on the normal buffer all at once normally?

# Answer
> 2 votes
At least one case that this can happen is when you have multiple smoothing groups on an object. So a vertex can have as many normals as it has faces with different smoothing groups sharing it.

http://wiki.polycount.com/SmoothingGroups

# Answer
> 1 votes
Its the way Collada indexes things, Collada indexes the vertices, normals and other information separately, to save space in some cases. For example when you store a plane with allot of vertices and also allot of normals all pointing to the same direction, In the way collada stores the information it only has to give you a array of normal indices all point to the same normal vector pointing up in this case.

# Answer
> 1 votes
This is a common problem with many formats exported from modeling tools. It shows up in FBX as well. The simple truth is that you need to take the triangle list as master, unwind the individual indices, and construct a completely unindexed mesh. You can either leave it that way or recompute the indices by vertex deduplication. There's no way around this step and it's yet another reason that people avoid using interchange formats like FBX and Collada directly as game assets.

IMO the easiest way to reconstruct new indices is to create a Vertex struct with an operator\<, and then insert all the vertices into a std::map(Vertex, unsigned int). Then you can scan over the vertices again, looking up their indices from the map, and create an index buffer that way. I'm sure this isn't the fastest way, but it's very straightforward to write.

---
Tags: opengl, 3dsmax, normals, collada
---


# Question
Title: Where should I put my mob rendering code?
I'm making a simple LWJGL game. However, I'm a bit confused about rendering. So I have a Mob class and a TriangleMob is a basic enemy.

```
package daniel.entity.Mob;

public class TriangleMob {
        public void render(){
        }
        public void move(){
        }
}

```

Now I'm wondering do I put a render method in the TriangleMob or do I put some render method in graphics bit.

I'm really confused as I thought you needed to put all rendering in it's own bit. Then, all game logic like movement in another bit. Essentially, I want to spawn a TriangleMob in the SpawnMob class and then render it. I could put the render method in the TriangleMob class, however I want logic and rendering to be in different parts.

# Answer
> 19 votes
Put it wherever you can to make it work. Anything else is design paralysis and just going to slow down your progress.

When you start seeing patterns emerge, refactor your code.

Lots of people will give you advice about the One True Way to do something, but without a breadth of experience to draw from, you'll just be parroting ideas without a true understanding of the reasoning behind it.

---
Tags: java, architecture, rendering, lwjgl
---


# Question
Title: Knob in DigitalOnScreenControl not moving. Why?
I have set up a `DigitalOnScreenControl` in my game but the knob does not move. The base and the knob are drawn on the screen but the latter doesn't move as per the AndEngine example here.

Here is a snippet of my code:

```
this.mDigitalOnScreenControl = new DigitalOnScreenControl(300, 300, ResourceManager.getCamera(), ResourceManager.joystickControlBase,
                ResourceManager.joystickControlKnob, 0.1f, ResourceManager.getActivity().getVertexBufferObjectManager(),
                new IOnScreenControlListener() {

            @Override
            public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX,
                    final float pValueY) {
                    Log.v(TAG, "onControlChange");
            }
        });

        final Sprite controlBase = this.mDigitalOnScreenControl.getControlBase();
        final Sprite knob = this.mDigitalOnScreenControl.getControlKnob();
        controlBase.setAlpha(0.5f);
        controlBase.setOffsetCenter(0, 0);
        controlBase.setScaleCenter(10, 10);
                    controlBase.setScale(1.25f);
        knob.setScale(1.25f);
        this.mDigitalOnScreenControl.refreshControlKnobPosition();
        ResourceManager.getEngine().getScene().attachChild(this.mDigitalOnScreenControl);

```

The `mDigitalOnScreenControl` is a `DigitalOnScreenControl` object defined previously. I use a `ResourceManager` class to obtain texture regions and other game resources such as the camera amongst others. **Note**: Since the base and the knob are drawn, the `ITextureRegions` returned by the `ResourceManager` are valid. When I execute the program, there are no errors in *DDMS*.

The knob just doesn't move. Does anybody have an idea?

Thank you!

# Answer
> 1 votes
The `DigitalOnScreenControl` cannot be attached as a *child* to a scene. It must be attached as a `childscene` to the Engine's current Scene.

```
ResourceManager.getInstance().engine.getScene().setChildScene(joystickControl);

```

In the above code, `joystickControl` extends a `DigitalOnScreenControl` object. After that, depending on how your game is organised, you may need to sort the scenes, in case the `DigitalOnScreenControl` does not appear.

```
ResourceManager.getInstance().engine.getScene().sortChildren();

```

Also, read *Cameron Fredman*'s comment why it is sensible to add the `DigitalOnScreenControl` object as a `childscene`.

---
Tags: andengine, joystick
---


title: Create Random Platformer-Gameworld

text:
# Question
Title: Create Random Platformer-Gameworld
Evening.

I created a xna-game like the iOS Platformer game "Banana Kong". The level-layers are currently saved as XML files.

Example:

```
<level>
    <layer1>
        <tile type="0" x="50" y="70"></tile>
        .. And so on
    </layer1>
    .. And so on
</level>

```

Its a temporary solution, yes, but when I sell/release it, static levels are not very good.

So How I could create levels randomly?

The engine would have to pay attantion, to not create tiles, the player can't reach, or create tiles an other tiles.

My current concept is, that the engine could create random tiles as long a tile fits every condition - but there is a unlikely chance that this will never happen and I think there are better methods to do this.

So, I hope anybody could give me some resources, theories or anything, what can help me.

# Answer
You may want to give this paper a read. It is about constructing platformer level based on jumping rythm.

The simplest approach would be to define rules for each layer and match the tiles agains it. You may define a range the character can jump with single (and maybe double ) jump. Then evaluate possible next tiles in this range and pick one at random.
> 2 votes

---
Tags: xna, algorithm, procedural-generation, platformer
---


# Question
Title: Move a 2D sprite into an irregular terrain
With a tile based engine, in my knowledge, is not possible to move a sprite into an irregular terrain. So which are the techniques to use for implementing that? Maybe an hexagonal tile based engine?

# Answer
It remember me an interesting guide i saw: http://www.gamedev.net/page/resources/\_/technical/game-programming/the-guide-to-implementing-2d-platformers-r2936

"The Tile based smooth" subject explain how it works for a game like Megaman. Hope it help!
> 2 votes

# Answer
(I agree with Eric B -probably not best to make it a tile game - but thought i would answer anwyay)

If the amount of variation is less then one tile, then you could have tiles that allow user movement through them, and a corresponding table of heights for those tiles. SO lets say you divide each tile up in to 16 px portions, (64px wide tiles / 16px parts = 4 per tile), then as the center of the player moves over the tile, you could determine which of the 4 parts your player was currently on, and adjust the height. If the player was wider or had wheels, you could do the same thing for each wheel, get the height and then rotate the player to match.

But, you still need to have tiles for each shape, so you would need a lot of tiles for this. Just an idea.
> 1 votes

# Answer
I'm sorry i cannot give credits : i can't remember where i saw this gem, but here's one technique that is worth mentionning :
imagine the floor of the game is drawn on a separate layer. The floor might be any shape.

1) how do you know the sprite is on the floor ?
easiest way is to pixel test one point (or two points, one for each foot) , to see if we touched something.
Obviously first optimisation is too see wether the player is in an 'empty' tile or not. Then to have, for each non empty tiles, a few contiguous segments \[ {x: , y: } , {x:, y: } \] (sorted on x) describing the slope with a settable precision. So you can quickly test a point against those segments. The segments needs to be computed once per tile *type*.

2) how do i know the normal to the point of contact ?
this normal is required to compute the rotation of our player.
If we have the list of segment, you can use the slope of the current segment to compute the normal. And you have tu use neighboring segments to smoothen the changes. Could be tricky with arbitrary length (x2-x1) segments. And how to be precise enough ? not too slow ? work whatever the game's scale/resolution ?
That's where comes the gem :
1) take the 3X3 pixel array surrounding the point of contact.
2) now sum up every vectors coming from center point (1,1), but only if the corresponding pixel is not transparent.
3) norm the resulting vector, reverse it ( {x: -x, y; -y } ) and here we go ! we have our estimation of the normal.
Yes : the end : Magic !

Rq1) you might want to use a 5X5 or 7X7 grid. In fact in the article i saw that a 3X3 was perfect for a game with gentle slopes ( \< Pi/8 ).
Rq2) get the image with getImageData or webkitGetImageDataHD, then iterate through the image.data. You might want to test a pixel for being null in *one* read if you set up a 32 bits view on the image.data, ( which is originaly a UInt8ClampedArray ) :

```
var my32BitView = new Int32Array(image.data.buffer);
var pixelIndex = 0,
var isPixelEmpty = ( my32BitView[pixelIndex] == 0 );
pixelIndex+=;

```

Rq3) if you go for a 5X5 matrix, compute first the norm of the 3X3, then end the matrix computation to get the 5X5 norm. if you compare the two norms you can know about a near edge : another magic !!!
Rq4) if you have two points of contact... do it twice !! :-)
Rq5) you can precompute the (x-xcenter) (y-ycenter) of the vectors within an array (of { x :, y: }) or two (of numbers) then you can go and add linarly sum the x and y if there's a pixel in corresponding image data array. One while (--) loop !
> 1 votes

---
Tags: sprites, tilemap
---


# Question
Title: Rendering performance in FlasCC + UDK when compared to Stage3d and UDK on Windows?
Adobe recently released the Flash C++ Compiler, which UDK uses to target Flash Player.

Developers can now access UDK for browser applications. Does this mean greater performance than using a Stage3D engine (Away3D 4) and how much of a noticeable difference in performance would it make in rendering speeds?

Is there any benchmark you could propose that would allow to compare them fairly? I am asking this to help myself understand the consequences in performance for deciding to use UDK in a browser based game. I would also like to know how it compares with UDK running natively in Windows?

I am not asking which technology to use or which is better. Only interested in optimizing rendering speed in a 3d browser game with flash.

# Answer
> 1 votes
Rendering speed for 3D FlasCC games/apps is likely to be similar to C++ apps for obvious reasons - the actual rendering takes place on the GPU. Flash includes a cross-platfrom shader language (AGAL) to describe GPU kernels (programs run per pixel on the GPU).

For CPU/computing speeds however, my tests have shown that the Alchemy toolkit at its best reaches 15% the speed of MS VC++ on Windows (with a simple encryption function operating on an array of bytes). Since Alchemy is now FlasCC, there may be improvements. Some benchmarks for the latest FlasCC are available here, that compare a set of C++ programs running as an EXE and in Flash Player.

This essentially comes down to:

* Anything you can move to the GPU can possibly be done close to native speeds. This includes rendering, lighting, mip-mapping, and to some extent physics operations (depends on the library)
* Anything still done on the CPU will be a few *times* slower than C++, so don't expect to have a million moving objects on screen with full physics even if you can do that with the native (C++) library.
* Flash vector graphics does not use the GPU and is rendered fully on the CPU. So if you need HUDs (heads up displays) with high-performance 3D vector rendering like what Scaleform provides for C++ apps, don't expect that to be easily possible in Flash Player, unless you're willing to roll your own 3D vector renderer that takes advantage of the GPU to composite vector shapes.

# Answer
> 2 votes
i'm the author of the benchmarks spreadsheet.

The algorithms i used for benchmarking are from a set of opensource compiler benchmarking code from Adobe themselves. I also runned some of the netlib benchmark algorithms.

Blog post : http://www.heliereric.com/fr/article/adobe-alchemy-benchmarks

Sources : https://github.com/ricovitch/FlasCC-Benchmarks

---
Tags: c++, flash, molehill, flascc, stage3d
---


# Question
Title: Compress / make Blender .obj file smaller
I have been learning the basics of blender for the best part of the day, and I still cannot figure out how to make models(imported) smaller in file size(where their original file size is 2MB+).

The reason why I want to make the files smaller is because I am trying to use them in my iPhone application, however the app crashes when the .obj files are over 1MB.

Could anybody please help me I have been at this for hours..

# Answer
AFAIK, there's no native IOS support for .obj format (referring to IOS OpenGL APIs). So either you use some IOS app that can import .obj format or you've made your own such parser.

If it's a 3rd party app, check and see if it cannot read zipped versions of the .obj files. If it does (and is properly implemented) this will use less memory when parsing your .obj file(s)

If it's your own parser, update it so that it can read zipped .obj files.

There are also .obj optimizers, which make your .obj file smaller by either rounding up values or removing vertices (if they're too close together etc).
> 3 votes

# Answer
Very few kinds of assets are expressed effectively in text-based formats.

In the case of `.obj` meshes, the data in the file is not suitable for direct consumption in a 3D API either, as it has multiple indices per vertex and the possibility of more than three vertices per face.

Consider making a very simple binary file format suitable for direct use with your target platform. It would essentially consist of a header outlining the vertex and index counts for each geometry, followed by solidly packed blobs of vertex and index data.

Again, text formats for bulk data rarely make much sense, at least not at the deployment end of your pipeline. The closer to the end consumer a file format is, the more specific and optimized it should be.
> 1 votes

---
Tags: blender, compression
---


# Question
Title: How to force playing attack animation until the end?
I rework the code to make it more easier to manage. How can I force the player cannot change the sprite animation by pressing any keys until the attack animation completely ends?

```
class Player
{
    Animation playerIdle;
    Animation playerRun;
    Animation playerAtk;

    public void Load(ContentManager content)
    {
        playerIdle = new Animation(content, "idle", 144, 128, 8, 30);
        playerRun = new Animation(content, "run", 160, 112, 8, 30);
        playerAtk = new Animation(content, "atk", 154, 131, 2, 30);

        playerIdle.EnableRepeating();
        playerRun.EnableRepeating();
        playerAtk.EnableRepeating();
    }

    public void Update(GameTime gameTime)
    {
        playerIdle.Update(gameTime);
        UpdateControl(gameTime);
    }

    #region Update Control
    string selectSpriteSheet;

    KeyboardState mPreviousKeyboardState;
    SpriteEffects spriteEffects = SpriteEffects.FlipHorizontally;

    Vector2 feetPosition = new Vector2(0, 350);
    Vector2 mSpeed = Vector2.Zero;
    Vector2 mDirection = Vector2.Zero;
    Vector2 mStartingPosition = Vector2.Zero;

    int CHARACTER_SPEED = 50;
    int MOVE_LEFT = -5;
    int MOVE_RIGHT = 5;
    int MOVE_UP = -5;
    int MOVE_DOWN = 5;

    enum State
    {
        Running,
        Jumping,
        Attacking,
    }

    State mCurrentState = State.Running;

    public void UpdateControl(GameTime gameTime)
    {
        KeyboardState aCurrentKeyboardState = Keyboard.GetState();

        feetPosition += mDirection * mSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        selectSpriteSheet = "idle";
        UpdateMovement(aCurrentKeyboardState, gameTime);
        //UpdateJump(aCurrentKeyboardState, gameTime);

        mPreviousKeyboardState = aCurrentKeyboardState;
    }

    private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime)
    {
        if (mCurrentState == State.Running)
        {
            mSpeed = Vector2.Zero;
            mDirection = Vector2.Zero;

            if (aCurrentKeyboardState.IsKeyDown(Keys.Left) && !aCurrentKeyboardState.IsKeyDown(Keys.Right))
            {
                playerRun.Update(gameTime);

                selectSpriteSheet = "run";
                spriteEffects = SpriteEffects.None;
                mSpeed.X = CHARACTER_SPEED;
                mDirection.X = MOVE_LEFT;

            }
            else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) && !aCurrentKeyboardState.IsKeyDown(Keys.Left))
            {
                playerRun.Update(gameTime);

                selectSpriteSheet = "run";
                spriteEffects = SpriteEffects.FlipHorizontally;
                mSpeed.X = CHARACTER_SPEED;
                mDirection.X = MOVE_RIGHT;
            }

            if (aCurrentKeyboardState.IsKeyDown(Keys.Z) && mPreviousKeyboardState.IsKeyUp(Keys.Z))
            {
                mCurrentState = State.Attacking;
            }
        }

        if (mCurrentState == State.Attacking)
        {
            playerAtk.Update(gameTime);

            selectSpriteSheet = "hit";
            mCurrentState = State.Running;
        }
    }
    #endregion

    public void Draw(SpriteBatch spriteBatch)
    {
        //playerIdle.Draw(spriteBatch, feetPosition, (float)MathHelper.ToRadians(0), 1.0f);
        if (selectSpriteSheet == "idle")
            playerIdle.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f);
        else if (selectSpriteSheet == "run")
            playerRun.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0),1.0f);
        else if (selectSpriteSheet == "hit")
            playerAtk.Draw(spriteBatch, feetPosition, spriteEffects, (float)MathHelper.ToRadians(0), 1.0f);
    }
}

```

# Answer
> 1 votes
The player class should have a `currentAnimation` and a `nextAnimation`.

If the `currentAnimation` is flagged as `uninterruptible`, then any attempts to change `newAnimation` are applied to `nextAnimation` and the `currentAnimation` is set to not repeat. Then, when the `currentAnimation` ends, `nextAnimation` will take its place.

---
Tags: xna, xna-4.0
---


title: Shooting Bullets Around a Sphere

text:
# Question
Title: Shooting Bullets Around a Sphere
I currently have a ship that can orbit around a sphere freely controlled by a joystick. There is a separate joystick that controls the gun and starts shooting when it is touched.

Right now the bullets start shooting and then orbit the sphere until their lifetime has elapsed. Instead of having them orbit the sphere I want them to orbit for maybe the first half of their life and then shoot off into space. Does that make sense?

It would give the effect of a kind of glancing off the atmosphere, instead of staying in orbit for the whole time.

I am working in Unity3D and using the `RotateAround()` method to get the bullets to orbit. I'm thinking I need to take a snapshot of there position at half life, and then figure out the vector that would shoot them off into space. If someone could help me get going in the right direction with that, that would be great!

# Answer
> 2 votes
I assume you have a separate routine that handles the behavior of the bullet, in which case you keep a timer variable(your halflife) that you reduce in the FixedUpdate method, and once it reaches zero then you change the behavior from doing a RotateAround to simply translating it according to the tangent to the planet multiplied by the current speed of the bullet, both of which you store at the instant that the timer ticks down to zero.

The tangent vector should be essentially the current transform.forward vector of the bullet gameobject whereas the speed would be the arclength traversed divided by the delta time of the FixedUpdate(unless of course you already have some constant speed in radians/second that you multiply by the FixedUpdate elapsed time). Arclength/sec would be the angle(in radians) that the bullet rotates/second * the distance from the center of the planet to the center of your bullet(the radius).

Edit: I should mention that this will not work if you currently are utilizing the physics engine to handle any aspects of the motion which it seems you aren't from the way you phrased the question.

Implementation: 1)Create a public variable in the bullet routine to store 'speed' so that it can be set in the prefab of the bullet gameObject. Also have an escape time(or distance if you prefer) variable and a boolean to determine if it is still rotating or translating.

2)In the rotate phase of your update the radians to RotateAround should be (speed * elapsedTime) / radius of sphere

3)Once the escape timer(or distance) is reached, set the boolean flag to indicate that you are no longer rotating. Now simply use the transform.forward vector multiplied by the speed * elapsed time to translate the bullet.

---
Tags: c#, android, unity, game-mechanics, vector
---


title: Objects not Colliding

text:
# Question
Title: Objects not Colliding
I have been having a problem doing 3D collision detection in a game I have been trying to make for several weeks now. What I am trying to do is prevent a PlayerModel object from colliding with Obstacle(cube) objects. The code I have right now works perfectly fine but it only works correctly with the first Obstacle in the list of Obstacle objects I have. I have tried using a foreach and for statement to try and go through each object in the list but neither method worked. Also putting breaks and continue statements did not work either. The first code block that I want to post is the code in the player model object that checks for the collision.

I decided to leave in the comments I had from when I was debugging the code. Also this code block is all happening in the PlayerModel class.

```
//update future bounding sphere based on input
        this.futureBoundingSphere = new BoundingSphere(this.futurePosition.Translation, 10.5f);

        //collision checking last
        //What i think is going on - At first only one cube was being checked, so i just break out of the statement if we hit soemthing.,
        //i think that was the only way i could get the collision to get checked on multiple objects.
        //Also, i must take note of the bounding spehers, It is likely that the spacemans collision sphere is being drawn waaaay to large, suggest scaling spacemodel to test
        foreach (BasicModel obstacleModel in game.obstacles.models)
        {

            if (this.wholeCollidesWith(futureBoundingSphere, obstacleModel, obstacleModel.GetWorld()))
            {
                //note - First object in the list does second statement, last object does first statement
                game.aColor = Color.AliceBlue;
                futurePosition.Translation = this.world.Translation;
                //break; ////- adding in break will cause all but the first object to do the first statement
            }
            else
            {
                game.aColor = Color.Orange;
                this.world.Translation = futurePosition.Translation;
            }
        }

       //update actual bounding sphere last
        this.myBoundingSphere = new BoundingSphere(this.GetWorld().Translation, 10f);

```

The second code block I have is the wholeCollidesWith method that I use to check collision between single objects. Please keep in mind that I am not currently using the otherWorld parameter, I had used it once before but stopped using it because I am updating each object's bounding sphere whenever its update method is called.

```
//Whole model collision, not checking individual meshes
    public bool wholeCollidesWith(BoundingSphere futureBoundingSphere, BasicModel otherModel, Matrix otherWorld)
    {
        //Check if one object collides with another
        if(futureBoundingSphere.Intersects(
            otherModel.myBoundingSphere))
        {
            return true;
        }
        return false;
    }

```

I am not sure what is going on but I am hoping that it is a simple syntax error that I am overlooking with my foreach loop. In any case I hope there will be someone who might be able to find the error that I could not find, please request for any more code/information if needed.

# Answer
> 0 votes
You are modifying the `world.Translation` before you have a chance to check for collisions with the rest of the objects.

In the case where the first object is not colliding you set the `world.Translation` to be the `futurePosition.Translation`, then no matter what happens after that you are stuck with the `futurePosition.Translation` because you are essentially saying `futurePosition.Translation = futurePosition.Translation` (`this.world.Translation`) in the first part of the if statement.

Just set a `flag _collisionHappened` to `false` before entering the loop, then set it to `true` if you hit something. At the end of the loop check the flag and only update the translate if there was no collision.

---
Tags: xna, c#, 3d, collision-detection, debugging
---


title: Is gameswf usable?

text:
# Question
Title: Is gameswf usable?
The project page indicates that it's pre-alpha code, and suggests the actionscript support is weak. Flash UIs are nice, so I was wondering if anyone has experience getting gameswf to the point where it will embed nicely in C++ (e.g. nice function bindings) and properly play a swf that uses typical modern actionscript.

Is there an alternative that doesn't carry the pricetag of a commercial product?

# Answer
I'm not personally familiar with gameswf, so I can't comment on how capable it is, however if your target platform is Windows only (for now), I can point you towards Hikari.

It was originally built for Ogre3D but it should be fairly straightforward to port, and it's been used in commercial titles such as Zero Gear.

Best of all, it will play everything you can play with the most recent Flash player (just replace the ocx that comes with the SDK with a more recent version).

In the future, Hikari will simply become an Ogre3D wrapper for the cross-platform Akarui.
> 3 votes

# Answer
Having had personal experience of GameSWF (the version made by tulrich) I can tell you that it only supports as1.

It isn't especially complicated to utilise and could be said to be better in terms of direct functionality than some other commercial solutions that can cost thousands of dollars.

If you can do what you need your menus to do using as1 then it's not a bad choice.
> 4 votes

# Answer
I'v tried to use GameSWF in one of my projects. As far as the rendering goes, it seems solid. The problem appears in the action script part. Some simple scripts work, but more complex ones fails. The main problems are in the actions script virtual machine implementation, its not working exactly as the one in Flash. It has some problems with garbage collection too. (or has back then when I was trying to use it)

From my personal experience: if you need it for just few buttons with no more than very basic action script and non fancy graphics, it may be ok. But for more advanced UI in a commercial projects, there are better solutions like ScaleForm or Iggy. But ofc they are not for free.
> 2 votes

---
Tags: gui, flash
---


# Question
Title: C++/OpenGL Game - How to Make it Compatible with Screen Recorders?
I'm developing a 3D tower defense-like game in C++/OpenGL on Windows.

The problem I'm having isn't about the game itself (the game runs fine), but it's about using screen recording software to record gameplay.

For some reason, whenever I try to record the screen (I've tried both Camtasia Studio 8 and Fraps 3.5.9), it slows down the game (I'm not talking about just an FPS drop; the actual game timers run slower).

To show an example of what I mean, see the following screenshot: I ran two instances of my game at once (side by side), and recorded the righthand one using Fraps. As you can see in the image below, Fraps is causing the game time for the recorded instance to increase almost twice as slowly as it should.

I'm getting around 800-1000 FPS when running the game without Fraps recording, and around 300-400 FPS with Fraps recording. But playing the game with recording causes everything to happen in slow-motion, despite it running smoothly rendering-wise.

For timing I've tried using both the `QueryPerformanceCounter()` and `timeGetTime()` approaches - the slowdown still occurs using either.

Does anyone have an idea what might be causing this? Could it be because of the way I'm rendering with OpenGL?

# Answer
FRAPS actually reads from the OpenGL and DirectX video buffers to record videos. The good news is that in order to make FRAPS work is use OpenGL/DirectX. The bad news is that there will be some overhead as the computer has to do one more thing with the video buffer as apposed to the usual read/draw operations.

Also consider FRAPS will clobber your Hard-Drive with Video data. If your game needs the hard drive, or your system is big on virtual memory, you will notice a large performance hit.

To make your game work regardless, consider time-locking your program loops. Sprites should only move the distance based off the velocity times the time since the last loop, Frames should only change if the seconds per frame (1/FPS) has been met or exceeded since the last frame change.
> 3 votes

# Answer
You timing code should look something like this. Does this function work correctly if you put it in your code somewhere and call it every frame?

```
void PrintTimeRemaining(void)
{
    // This static is just a hack to simplify the code. You'd normally put it in a class member.
    static int target = timeGetTime() + 100 * 1000; // 100 seconds

    char string[256];
    int remaining = target - timeGetTime();

    sprintf(string, "Time remaining: %d.%03d seconds\n", remaining / 1000, remaining % 1000);

    // Print the string out to the debug output window for testing
    OutputDebugString(string);
}

```
> 0 votes

---
Tags: c++, opengl, timer
---


# Question
Title: Best way to have a body with 1 dimensional linear only movement in Box2D
I have a body that I am using as a paddle, it is expected to move in a vertical fashion and other objects should "bounce off it". The paddle itself should never move horizontally.

According to the docs this sounds like what I want...

> A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces.

but reading further....

> Static bodies do not collide with other static or kinematic bodies.

So I create two Static Body lines and a box in between. How do I handle the box's movement? I don't think I want a dynamic object because I am only interested in linear moves (I.E. don't want wabbling).

What is the best way to handle this scenario?

# Answer
Unless I'm misunderstanding the second half of your question, it sounds like you still want a kinematic body. Other *dynamic* objects will react to the kinematic body you have created, but the paddle will remain unaffected by colliding with whatever is supposed to bounce off of it. Check out the example found here.
> 2 votes

---
Tags: box2d
---


# Question
Title: PHP keeping track of how many online rooms exist
I'm making an online card game project but now I have a minor issue:

In my game there are rooms that users can join. How do I find out how many created rooms there are? I thought about using a static counter but it didn't work. (I thing that the reason it didn't work is because every process is run on a separated thread so using static keyword wont help me solve this problem.) Also I thought about saving it to the database but than when someone cancels a room, for others, it wont be visible.

Do you know any solution how to do this?

# Answer
If it's just a handful of rooms, I'd use a flat file, otherwise you'll need to post some code of what you tried using a database... This should be a very simple request.

Here's a flat file solution. Save this as a file on your server and call it with `?do=add` or `?do=sub` to add or subtract the count respectively. If you don't specify `do` then it will print the current number-

```
<?php
if($_GET['do']=="add"){
    $new = intval(@file_get_contents("count.txt"))+1;
    $fp = fopen("count.txt", "w");
    fwrite($fp, $new);
    fclose($fp);
}else
if($_GET['do']=="sub"{
    $new = intval(@file_get_contents("count.txt"))-1;
    if($new < 0){$new = 0;}
    $fp = fopen("count.txt", "w");
    fwrite($fp, $new);
    fclose($fp);
    }else{
    print @file_get_contents("count.txt");
}

?>

```
> 1 votes

---
Tags: php, online
---


# Question
Title: How to translate from Slick2d coordinates to jBox2d
I read through this question to try and get a grasp on the topic, but I can't figure out how to apply this to my Slick2d window.

I'm trying to do something as simple as place an edge on the bottom of the screen, so I had been thinking of something like

```
bottomEdge.setAsEdge(new Vec2(0f, SCREEN_HEIGHT), new Vec2(SCREEN_WIDTH, SCREEN_HEIGHT))

```

...but I have no idea how move from my pixel system to the MKS system of jBox2d. In fact, the `body.getPosition().x` of a movable body I am drawing returns a decimal value between 100 and 101, but I have no idea how it's deciding on this value. As I move off screen to the left, it decreases down to 99, 98, and so on.

How should I go about making this conversion and thereby also being able to support different screen sizes & resolutions? My instinct is to somehow use the LWJGL underneath Slick, but I'm lost.

# Answer
The box2d faq may help you out, one of the Q&As reads:

**How do I convert pixels to meters?**

Suppose you have a sprite for a character that is 100x100 pixels. You decide to use a scaling factor that is 0.01. This will make the character physics box 1m x 1m. So go make a physics box that is 1x1. Now suppose the character starts out at pixel coordinate (345,679). So position the physics box at (3.45,6.79). Now simulate the physics world. Suppose the character physics box moves to (2.31,4.98), so move your character sprite to pixel coordinates (231,498). Now the only tricky part is choosing a scaling factor. This really depends on your game. You should try to get your moving objects in the range 0.1 - 10 meters, with 1 meter being the sweet spot.

As a basic example (snippet):

```
/** 100 Pixels = 1m in Physics jbox2d */
private static final float SCALE = 0.01f;   // 1/100 pixels

// Convert a Slick 2D screen x coordinate to a JBox2D x coordinate
public static float toPosX(float posX)
{
    float x = posX * SCALE;
    return x;
}

// Convert a Slick 2D screen y coordinate to a JBox2D y coordinate
public static float toPosY(float posY)
{
    // As the physics world uses a 2d cartesian coordinate system
    // and slick uses screen coordinates with top-left being (0,0)
    // flip y
    float y = -posY * SCALE;
    return y;
}

/**
 * Convert a JBox2D x coordinate to a Slick 2D screen x coordinate
 *
 * @param posX The JBox2D x coordinate
 * @return The Slick 2D x coordinate
 */
public static float toScreenX(float posX)
{
    // convert back to screen coordinate
    float x = posX / SCALE;
    return x;
}

public static float toScreenY(float posY)
{
    // convert back to screen coordinate
    float y = -posY / SCALE;
    return y;
}

public void example()
{
    BodyDef bd = new BodyDef();
    bd.type = BodyType.STATIC;
    Body body = world.createBody(bd);
    PolygonShape shape = new PolygonShape();

    // Note: v1X, v1Y, v2X, v2Y are in screen coordinates
    // Point A of the edge
    Vec2 v1 = new Vec2(toPosX(v1X), toPosY(v1Y));
    // Point B of the edge
    Vec2 v2 = new Vec2(toPosX(v2X), toPosY(v2Y));
    shape.setAsEdge(v1, v2);
    body.createFixture(shape, 1.0f);
}

```

Also, someone gives a great explanation here:
https://stackoverflow.com/questions/9997006/slick2d-and-jbox2d-how-to-draw

There are many different ways of doing the conversion, this is just one example. If you take a look at the jbox2d testbed code, it uses an OOBB structure to do the conversion. I'm still getting my head around it myself, I haven't touched jbox2d for a while now so if anyone has any input, I would be glad to hear/see it.
> 0 votes

# Answer
There is actually something that does this for you in the library, called OBBViewportTransform. It will handle all view-to-world and world-to-view transformations, and even allows rotation, skewing, etc (anything that can be done with a 2x2 matrix).
> 0 votes

---
Tags: box2d, lwjgl, slick, jbox2d
---


# Question
Title: Fastest pathfinding for static node matrix
I'm programming a route finding routine in VB.NET for an online game I play, and I'm searching for the fastest route finding algorithm for my map type.

The game takes place in space, with thousands of solar systems connected by jump gates. The game devs have provided a DB dump containing a list of every system and the systems it can jump to. The map isn't quite a node tree, since some branches can jump to other branches - more of a matrix.

What I need is a fast pathfinding algorithm. I have already implemented an A\* routine and a Dijkstra's, both find the best path but are too slow for my purposes - a search that considers about 5000 nodes takes over 20 seconds to compute. A similar program on a website can do the same search in less than a second.

This website claims to use D\*, which I have looked into. That algorithm seems more appropriate for dynamic maps rather than one that does not change - unless I misunderstand it's premise.

So is there something faster I can use for a map that is not your typical tile/polygon base? GBFS? Perhaps a DFS? Or have I likely got some problem with my A\* - maybe poorly chosen heuristics or movement cost? Currently my movement cost is the length of the jump (the DB dump has solar system coordinates as well), and the heuristic is a quick euclidean calculation from the node to the goal.

In case anyone has some optimizations for my A\*, here is the routine that consumes about 60% of my processing time, according to my profiler. The coordinateData table contains a list of every system's coordinates, and neighborNode.distance is the distance of the jump.

```
    Private Function findDistance(ByVal startSystem As Integer, ByVal endSystem As Integer) As Integer
    'hCount += 1
    'If hCount Mod 0 = 0 Then

    'Return hCache
    'End If

    'Initialize variables to be filled
    Dim x1, x2, y1, y2, z1, z2 As Integer

    'LINQ queries for solar system data
    Dim systemFromData = From result In jumpDataDB.coordinateDatas
                           Where result.systemId = startSystem
                           Select result.x, result.y, result.z

    Dim systemToData = From result In jumpDataDB.coordinateDatas
                             Where result.systemId = endSystem
                             Select result.x, result.y, result.z

    'LINQ execute
    'Fill variables with solar system data for from and to system

    For Each solarSystem In systemFromData
        x1 = (solarSystem.x)
        y1 = (solarSystem.y)
        z1 = (solarSystem.z)
    Next

    For Each solarSystem In systemToData
        x2 = (solarSystem.x)
        y2 = (solarSystem.y)
        z2 = (solarSystem.z)
    Next
    Dim x3 = Math.Abs(x1 - x2)
    Dim y3 = Math.Abs(y1 - y2)
    Dim z3 = Math.Abs(z1 - z2)

    'Calculate distance and round
    'Dim distance = Math.Round(Math.Sqrt(Math.Abs((x1 - x2) ^ 2) + Math.Abs((y1 - y2) ^ 2) + Math.Abs((z1 - z2) ^ 2)))

    Dim distance = firstConstant * Math.Min(secondConstant * (x3 + y3 + z3), Math.Max(x3, Math.Max(y3, z3)))

    'Dim distance = Math.Abs(x1 - x2) + Math.Abs(z1 - z2) + Math.Abs(y1 - y2)
    'hCache = distance
    Return distance

End Function

```

And the main loop, the other 30%

```
'Begin search
    While openList.Count() != 0
        'Set current system and move node to closed
        currentNode = lowestF()
        move(currentNode.id)

        For Each neighborNode In neighborNodes

            If Not onList(neighborNode.toSystem, 0) Then

                If Not onList(neighborNode.toSystem, 1) Then

                    Dim newNode As New nodeData()
                    newNode.id = neighborNode.toSystem
                    newNode.parent = currentNode.id

                    newNode.g = currentNode.g + neighborNode.distance
                    newNode.h = findDistance(newNode.id, endSystem)
                    newNode.f = newNode.g + newNode.h
                    newNode.security = neighborNode.security

                    openList.Add(newNode)

                    shortOpenList(OLindex) = newNode.id
                    OLindex += 1

                Else

                    Dim proposedG As Integer = currentNode.g + neighborNode.distance

                    If proposedG < gValue(neighborNode.toSystem) Then
                        changeParent(neighborNode.toSystem, currentNode.id, proposedG)
                    End If

                End If

            End If

        Next

        'Check to see if done
        If currentNode.id = endSystem Then
            Exit While
        End If

    End While

```

If clarification is needed on my spaghetti code, I'll try to explain.

# Answer
Without looking at your spaghetti code, I can say you are doing something drastcically wrong. I have adapted Eric Lippert's C# A-star algorithm to a hex map of ~ 420x750 hexes (~ 133,000 hexes total), and the longest diagonal path determination takes about 3 sec.

A profile analysis would almost certainly identify the performance culprit quickly, as you are off by at least an order of magnitude. Likely candidates are your closed list, so check your hashing algorithm. I used **x\<\<16 ^ y**.

Hmm! Where is your closed-list lookup? I can't find it. **That wold explain poor performance.**
> 1 votes

---
Tags: path-finding
---


# Question
Title: How to get a large quantity of photographs in an app while being memory efficient??
There have been a lot of word games (apps) lately and some use graphics but others use photographs and I was hoping that someone could explain how these games manage to get so many photos in an app without taking up huge amounts of memory?

The easiest example I can give is an app called '4 pics 1 word' it has over 350 levels and obviously 4 pics on each level and the photos are good quality on retina screens but the memory of the app is less than 40mb, if I have remembered correctly. I was curious as to how this works, is it each photo being optimized in photoshop (save for web and devices) (png or jpeg) or is it something to do with the code or something else?

I know this question is quite broad but any answers, help, links to anything would be greatly appreciated.

# Answer
> 4 votes
It's probably mostly a matter of being smart with 1) unloading of assets when no longer needed and 2) threaded loading of assets (if necessary, sometimes you can hide loading hitches behind "loading" screens). You likely don't have all the images loaded in memory at once.

That being said, the on-disk space is pretty irrelevant when it comes to in-memory size. See this answer: https://gamedev.stackexchange.com/a/48311/51

# Answer
> 1 votes
One other possibility: The game has network communication access. Here's the Google Play store page for 4 Pics 1 Word. It has the following permissions:

> NETWORK COMMUNICATION FULL NETWORK ACCESS Allows the app to create network sockets and use custom network protocols. The browser and other applications provide means to send data to the internet, so this permission is not required to send data to the internet.

So maybe it's downloading images while you play.

# Answer
> 0 votes
If you mean download size when you say "memory" then the answer is that jpegs at that size can be quite small, especially if you don't use the maximum quality setting.

It's also possible they share images between levels to save space.

# Answer
> 0 votes
I see a few possibilities here. You mentioned that the app is less than '40MB in memory' which implies you know the amount of memory its consuming - but I'm going to go ahead and assume you actually meant the package is 40MB.

Without knowing the exact internal workings, I'd take a gander at the fact that a simple JPG of only 200px200px can be quite small - around 30 kilobytes if optimized properly. If we do a bit of math, this doesn't seem so unreasonable.

350 levels * 4 per level * 50 size of pictures per level = 70000 kilobytes

70000 / 1000 = 70 megabytes uncompressed

This is uncompressed which of course when it's shoved into a package will shrunk from all sorts of fancy tricks.

50 kilobytes can be quite large however, and it's defintely not a fair representation neccesairly. Take this picture:

http://upload.wikimedia.org/wikipedia/en/d/d0/Ofa\_logo\_low\_res.jpg

It's approximately 44KB - now run it through Photoshop with some optimizations.

Whoa, 6 kilobytes!

Lets run through our math again... yup. The entire thing would fit into 8.4MB (350 * 4 * 6 / 1000). This trick can apply to even higher resolution images as well - the game in particular relies on a lot of photographs which JPGs can compress well as it's lossy and still look great.

---
Tags: iphone, optimization, memory-efficiency
---


title: Strange rendering in Direct3D 10

text:
# Question
Title: Strange rendering in Direct3D 10
I'm writing an application which renders graphics on the screen. The application can switch between Direct3D9 and Direct3D10 graphics modules (I wrote DLLs that wrap both D3D9 and D3D10). When trying to render a test mesh (a torus which comes as a stock mesh in D3DX9 and in DXUT library you can find in DirectX10 samples), Direct3D10 module behaves rather weird. Here's what I get.

D3D9:

D3D10:

The view, projection and world matrices are the same for both cases. The only thing that differs is the device initialization code, and the HLSL effect files (for simplicity I only apply ambient colors and don't use advanced lighting, texturing etc). Can this be because of wrong device initialization or because of bad shaders? I would appreciate any hint. I can post any code pieces by request.

Thanks in advance.

# Answer
Thanks to everyone for trying to help. I figured it out. The reason for that was because somehow the **position** variable in vertex shader had garbage in its **w** component. After assigning 1.0f to that the shader worked as expected.
> 1 votes

---
Tags: directx, shaders, 3d-meshes, directx10
---


# Question
Title: Can threads be used to run resource consuming methods without -ever- freezing UI?
Until recently I was sure that running expensive operations in threads can prevent UI freezing, but now I'm not.

Is it not guaranteed that a threaded operation will not hog the main thread's resources? If not, then how can I run a method in a way that it will never ever drain resources from UI thread (until told to)?

# Answer
> 2 votes
> Is it not guaranteed that a threaded operation will not hog the main thread's resources?

You are running on a computer that's playing host to a preemptive multitasking Operation System. ***Nothing*** guarantees your thread resources. There is *nothing* you can do on a computer that will guarantee that your thread's computational resources won't get taken away. Either by your own threads or some other processes.

That's life in a preemptive multithreading environment. Best live with it. The only thing you can do is minimize the chance of something happen; you can't eliminate it.

Without knowing anything about your inter-thread communication system, or how much work you're doing in this other thread, or any of the particulars of your situation, no solution can be offered here.

---
Tags: gui, multithreading
---


title: Diplomacy Systems

text:
# Question
Title: Diplomacy Systems
I'm wondering if there's any authoritative literature out there on diplomacy systems. I'm at the very beginning of my research, for instance I just found out through gamedev, that the term diplomacy describes what I'm looking for.

Before that, I was looking for `alliance systems` without much success.

**1)** Could someone point me in the right direction for further research into the topic?

Initiailly, I was looking for something like in eve online, where people are organized into individuals, fleets, alliances, all of which can, as far as I know, declare war or peace on each other.

**2)** Is there open source code I can study on the subject?

and finally:

**3)** What are some considerations when comparing diplomacy systems?

I mentioned Eve Online, but at this point, I'm open to inspiration from all genres. What are some interesting ones out there?

# Answer
I'd strongly suggest picking up a copy of the board game *Diplomacy*; there are freeware versions around, as well as paper copies:

http://en.wikipedia.org/wiki/Diplomacy\_(game)

It's been very good at using diplomacy as its gameplay element for over fifty years. But don't take my word for it:

> In its catalog, Avalon Hill advertised Diplomacy as John F. Kennedy's\[5\] and Henry Kissinger's favorite game. Kissinger described it as his favorite in an interview published in a games magazine.\[6\] American broadcast journalist Walter Cronkite was also reported to be a fan of the game.\[7\]

I feel like Henry Kissinger and John F. Kennedy probably know a thing or two about this sort of thing.
> 1 votes

---
Tags: strategy
---


title: How to convert a silhouette to a blob?

text:
# Question
Title: How to convert a silhouette to a blob?
Using ShapeShop you draw a silhouette and it converts the silhouette to a "blob", which gives a nice game character. Using 3DSMAX 2012 you draw a line and close the spine. How do you convert it to a "blob" there? Extrude gives sharp edges, BlobMesh only converts the lines to a blob, I want it to be the organic "blob" structure it is in ShapeShop.

# Answer
> 2 votes
Step by step as requested... (although this is from memory as I don't have the software to hand)

1. Place your image/silhouette in the background of your view port (there are millions of tutorials for this google is your friend)
2. Create the plane - Command Panel \> Standard Primitives \> Plane \> Click and drag in the view port to create it - make it a bit bigger than your silhouette.
3. Look in the Plane's Stack (or modifier list) and make sure the plane is made of 1 width and 1 length segment.
4. Right click the name of the plane - and select Collapse to editable poly.
5. With the object selected press Alt + X - this will turn the object semi-transparent so you should be able to see you view port image.
6. Open up the editable poly and proceed to use the edge tools to slice, connect and cut the plane so that you have more vertices (remember keep 4 sides polygons ), then push and pull the vertices so they follow the edge of your silhouette (this doesn't need to be 100% right as the later steps will be harder if you over do it at this stage)
7. When the silhouette is complete select poly mode, and select all the polygons and press extrude.
8. Adjust the 3D block so that it looks correct in terms of depth and proportion.
9. Apply a mesh smooth modifier to your stack, you can increase iterations to get a smoother appearance but I wouldn't go over 3 unless you have a really powerful computer.
10. Then with the 'Show End Result' button selected you should be able to go in to the editable poly and edit the shape in real-time to get a more desired finish. Again you may need to add more geometry at this stage.

That should be it, but what I failed to mention is if you want to use this for a game it will be horribly high-poly and will generally be inefficient to use in a game. Therefore it would be good to use this blob as a high poly mesh to then bake a normal map onto a lower poly mesh - again google is your friend here too.

*Original Answer*

> I would create plane then add geometry trace the silhouette, always maintaining quads, then extrude. Adjust the depth accordingly, then add a meshsmooth modifier, this may/will destroy a lot of the shape depending on how you have distributed the geometry, you can either add more reinforcement loops or adjust the shape in real-time using the preview button.

---
Tags: 3dsmax
---


title: creating a UI menu in c++

text:
# Question
Title: creating a UI menu in c++
Im currently working on a 2D Game where the users can interact with specific nodes and are able to edit certain bits of information and I also plan for the users to be able to click buttons to set specific information.

My problem is that I do not know how to write code to create a side menu/UI system where information can be passed to it and displayed and also be edited by the system.

If anyone has any tutorials or material that they would be able to point me towards that they think would be helpful with this would be very appreciated as I do not know where to begin with this. Note that at the moment I am willing to swap from DirectX to OpenGL if that would be easier though I would prefer to stick to DirectX if possible

Thanks

# Answer
It really depends what you want to do and with what technology:

* If it's a Win8 Metro game you could use XAML.
* You can also use a DirectX 2D overlay. This example shows how to make UI with it and handle interaction with it.
* If you want to enable interaction with 3D objects in your game (on click), this tutorial from Microsoft should help.

These are all Win8 app resources, but this should give you an idea for what to search for if you're targeting Win32.
> 4 votes

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


title: Messed up UVs in Unity3D for Android

text:
# Question
Title: Messed up UVs in Unity3D for Android
All of my quads appear correctly textured on the Unity3D editor, a Motorola Xoom Android tablet, and on an iPad 2:

But on our Samsung Galaxy Mini 2 smartphone they kinda look like this:

I wrote a debug shader that outputs the texture coordinates U and V to the R and G channels respectively, and results were consistent:

What could be causing this difference between devices?

# Answer
> 2 votes
Found the problem. Apparently I *needed* to assign a vertex color to each vertex of the quad, even when the shader was not using that information. In other words:

```
var colors = new[] {
    Color.white,
    Color.white,
    Color.white,
    Color.white
};
mesh.colors = colors;

```

Assigning these colors solved the UV problem, although I'm not sure why it did.

---
Tags: unity, graphics, shaders
---


# Question
Title: Why does my sprite animation sometimes runs faster?
I don't know why each time I call the `Update_Animation` function, my sprite animation runs faster. Is it caused by `gameTime`? How to fix it?

Here's the relevant code:

```
class Character
{
    // <SNIP>

    public void Update_Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime)
    {
        if (nextFrame >= frameInterval)
        {
            currentFrame.X++;

            if (currentFrame.X >= sheetSize.X)
            {
                currentFrame.X = 0;
                currentFrame.Y++;
            }

            if (currentFrame.Y >= sheetSize.Y)
                currentFrame.Y = 0;

            nextFrame = TimeSpan.Zero;
        }
        else
        {
            nextFrame += gameTime.ElapsedGameTime;
        }
    }

    // <SNIP>

    private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime)
    {
        if (mCurrentState == State.Walking)
        {
            action = "stand";
            Update_Animation(sheetSize_Stand, frameInterval_Stand, gameTime);

            mSpeed = Vector2.Zero;
            mDirection = Vector2.Zero;

            if (aCurrentKeyboardState.IsKeyDown(Keys.Left) && !aCurrentKeyboardState.IsKeyDown(Keys.Right))
            {
                action = "run";
                effect = SpriteEffects.None;

                mSpeed.X = CHARACTER_SPEED;
                mDirection.X = MOVE_LEFT;

                Update_Animation(sheetSize_Run, frameInterval_Run, gameTime);
            }
            else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) && !aCurrentKeyboardState.IsKeyDown(Keys.Left))
            {
                action = "run";
                effect = SpriteEffects.FlipHorizontally;

                mSpeed.X = CHARACTER_SPEED;
                mDirection.X = MOVE_RIGHT;

                Update_Animation(sheetSize_Run, frameInterval_Run, gameTime);
            }

            if (aCurrentKeyboardState.IsKeyDown(Keys.Z) && mPreviousKeyboardState.IsKeyUp(Keys.Z))
            {
                mCurrentState = State.Hitting;
            }
        }

        if (mCurrentState == State.Hitting)
        {
            action = "hit";

            Update_Animation(sheetSize_Hit, frameInterval_Hit, gameTime);
            mCurrentState = State.Walking;
        }
    }

    // <SNIP>
}

```

# Answer
> 2 votes
Your description is a bit vague, and you pasted way too much code... but I think the problem lies in the `Update_Animation` method:

You increase the value of `nextFrame` multiple times in an update if your character is running or 'hitting'.

Either make sure you call the `Update_Animation` method only once in an update, or just don't use the same variable (`nextFrame`) for all calls.

# Answer
> 0 votes
It seems like your `Update_Animation` method is called every `Update` or `Draw` call. That means that your animation speed *depends on your computer's speed.* On slow computers, animation is slow; on fast computers, animation is slow.

What you probably want with XNA is the game (and as much as possible, the UI) to run independently of the actual speed the game is executed.

What this boils down to (and the way I solved this in the past -- for animation, velocity/physics, etc.) is to update on a certain interval, i.e.

```
if ((DateTime.Now - lastFrameUpdate).TotalSeconds <= updateInterval) {
  Update_Animation(...)
  lastFrameUpdate = DateTime.Now;
}

```

In my case, I used a configurable interval like `TimeSpan.FromSeconds(0.1).TotalSeconds` to indicate frames should be updated every tenth of a second.

---
Tags: xna, xna-4.0, animation, sprites, debugging
---


# Question
Title: Textures loading too large on smaller monitors
I have an XNA game, and when i run the game the textures load all good on my computer and on my tv and they're all bring drawn in the right position. But on my laptop, which screen is smaller then both my othe computers monitor and my tv screen, all the textures are being drawn way to large. Example: i have a background which is just grass, and a stone path, and the image size is 1920x1080. It loads fine and is centered on my other computer and TV, but on my laptop, its drawn way too big and where the center should be is in about the bottom right corner of the laptop screen. Is it possible to edit the code to make it resize better on smaller screens, or is it just my laptop and my laptop's screen size is messed up. I believe that my laptop is in the 16:9 aspect ratio.

**Update 1**

I have noticed that the textures load fine when the window is not in full screen, but in full screen the textures have problems. How should i change this Draw Method to fix this problem, and draw this in the right spot in a full screen 1920x1080 window?

```
spriteBatch.Draw(backgroundTexture, Vector.Zero, Color.White);

```

(keep in mind the backgroundTexture is 1920x1080)

# Answer
> 4 votes
Depending on what function you call, you can probably resize the image correspondingly to diffrent resolution. This is a common problem, and is often solved with dynamic screen scalings. To just take this problem one step futher, you need to do dynamic correction with your GUI to maintaint the correct layout over all possible screens.

and assuming you are using the Spritebatch::Draw function, there is a parameter called rectangle. The width & height i suppose will be equal to the device screen cordinates. not to the texture size.

# Answer
> 0 votes
I provided a answer to a similar question XNA - move camera over tilemap

you need to pass the resultant Matrix to the spritebatch.Begin()

---
Tags: xna, xna-4.0, textures, spritebatch, aspect-ratio
---


# Question
Title: Detecting Screen Resolution in Android/AndEngine to display high or low quality images
I am developing a game with 1024x600 resolution. I can't target smaller resolution devices at this resolution, so I intend to use two graphics for the game. How do I detect which graphics to use for which device?

# Answer
In your main activity, you can call:

```
DisplayMetrics displayMetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

```

displayMetrics will then give you a bunch of data, for example:

> displayMetrics.density;
>
> displayMetrics.densityDpi;
>
> displayMetrics.heightPixels;

And so forth. In the comments below, there is a request for sample code to handle variable screen resolutions (i.e., to eliminate letterboxing). Sample code to accomplish this is available here.
> 2 votes

# Answer
I have found other solution for this and test it my self.

Dealing with all the device resolutions scattered around the globe. The existing resolution policies offer either a stretch-to-fit scale, black bars or leave it to you to do the scaling.

The class I have here is another option that scales your screen up to fill the screen, whilst retaining the 1:1 assets ratio of your graphics.

```
public class CroppedResolutionPolicy extends BaseResolutionPolicy
{

    private final float mCameraWidth;
    private final float mCameraHeight;
    private float mMarginVertical;  // Pixels from top of canvas to visible area, and from bottom of canvas to visible area
    private float mMarginHorizontal;        // Pixels from left of canvas to visible area, and from right of canvas to visible area

    public CroppedResolutionPolicy(final float nCameraWidth, final float nCameraHeight)
    {
            this.mCameraWidth = nCameraWidth;
            this.mCameraHeight = nCameraHeight;

            this.mMarginVertical = 0;
            this.mMarginHorizontal = 0;
    }

    // ===========================================================
    // Getter & Setter
    // ===========================================================
    public float getMarginVertical()
    {
            return this.mMarginVertical;
    }

    public float getMarginHorizontal()
    {
            return this.mMarginHorizontal;
    }

    @Override
    public void onMeasure(RenderSurfaceView pRenderSurfaceView, int pWidthMeasureSpec, int pHeightMeasureSpec)
    {
            BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec);

            int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec);
            int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec);

            final float nCamRatio = (float)mCameraWidth /  (float)mCameraHeight;
            final float nCanvasRatio = (float)measuredWidth /  (float)measuredHeight;

            if(  (float)measuredWidth /  (float)measuredHeight < nCamRatio )
            {
                    // Scale to fit height, width will crop
                    measuredWidth = (int) ( measuredHeight * nCamRatio);
                    this.mMarginHorizontal = ( this.mCameraWidth - ( (float) this.mCameraHeight * nCanvasRatio ) ) / 2.0f;
            }
            else
            {
                    // Scale to fit width, height will crop
                    measuredHeight = (int) ( measuredWidth / nCamRatio );
                    this.mMarginVertical = ( this.mCameraHeight - ( (float) this.mCameraWidth / nCanvasRatio ) ) / 2.0f;
            }

            pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight);
    }
}

```

Use this class in engine creation in the following manner.

```
final CroppedResolutionPolicy canvasSurface = new CroppedResolutionPolicy( CAMERA_WIDTH, CAMERA_HEIGHT );
final EngineOptions engineOptions = new EngineOptions( true, ScreenOrientation.LANDSCAPE_FIXED, canvasSurface, new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT) );

```
> 0 votes

---
Tags: android, graphics, andengine, resolution, aspect-ratio
---


title: Art style - setting - gameplay

text:
# Question
Title: Art style - setting - gameplay
I'm looking for resources describing art style - setting - gameplay relationship (from game design perspective).

For example, Fallout's colour palette most often is the dark one, models - realistic and not cartoonish. Setting - post nuclear holocaust. Auditory - mature players.

I could also take a different example like Borderlands. Art style is cartoonish, comic but not childish. Setting - vault raiding/monster killing on an alien planet. Auditory - mature players, but still appealing to teenagers (I suppose 13 and up).

Pixar and Nintendo games tend to be both cartoonish and childish. Setting - simple or movie based. Auditory - definitely kids, yet can be entertaining for adults for a limited time.

GTA - cartoonish, comic and somehow childish (especially the first one), yet auditory is definitely mature. Setting - working for crime syndicate/free roaming.

Let's say I create and epic fantasy game (setting). How should I choose most appropriate art style for my game? Are there any canons in art style like there are canons in literature (western, eastern, etc...) How does art style alone suggest what kind of gameplay one should expect? One can release concept art, but setting is generally kept secret so that player could uncover it while playing.

# Answer
Gamasutra is always a good online resource for in-depth articles on this kind of topic. One article that seems to particularly match your request is the following:

Another article from a different perspective, slightly related:

About canons in video games: the Library of Congress established a list of games which started a genre, which is now known as the Game Canon. This attempt has been criticized (also on Gamasutra: *Canon 2.0*, by Gareth Mensah). This article led to an entire website called the Video Game Canon
> 3 votes

---
Tags: game-design, art
---


title: AABB-AABB sliding collision response

text:
# Question
Title: AABB-AABB sliding collision response
I have many objects with AABBs and a player surrounded in an AABB. If I represent my player with a point everything works smooth with detection and wall sliding as a response (for example what wall sliding is, see this video).

If I represent my player with an AABB I first check if there is any AABB - AABB collision which works fine but I want the same sliding effect with this AABB box. I worked out a little trick to find the normals of both faces that collide but only works when I'm moving in one axis so that shouldn't be how it's done.

Below you'll see my scene. You'll see cubes surrounded with an AABB with a small offset and my camera that is at the center of an AABB (red lines).

How does one provide a good seamless AABB - AABB collision response algorithm that is not too hard to implement (like the one in the youtube video). I couldn't find anything useful on the web.

# Answer
You say you have found the collision normal. Since the shapes are AABBs, the normal will always be along one axis (six directions). All you need to do, then, is modify the player state as follows:

1. set the velocity component *along that axis* to zero.
2. set the position component along that axis to the “just exactly touching” distance, which is easy to calculate from the dimensions of the AABBs.

Further details:

* Make sure that you do this with respect to the box the player collides with *first* (which you can determine by dividing the penetration depth by the velocity), otherwise you might penetrate it by adjusting the position for the second.
* Adjusting the position might cause yet more different collisions. Check for those and respond to them too. If you have many close surfaces (narrow corridors made out of boxes) then it's hairy to ensure you can never have a conflict, and you might have to switch to 'soft' collisions, but for mostly wide separated boxes like in your screenshot this is sufficient.

This is just the special case of collision response for axis-aligned surfaces; non-axis-aligned surfaces would need dot products and projections with the surface normal, but here they all simplify to modifying a single axis. It's a special case of the same thing.
> 4 votes

# Answer
What you are referring to is known as a collide and slide algorithm. This is frequently used for player controllers, and cameras. The following links may be able to help you.

http://www.peroxide.dk/papers/collision/collision.pdf http://www.gamedev.net/topic/556184-character-controller/
> 2 votes

---
Tags: c++, 3d, collision-detection, aabb
---


# Question
Title: How to remove a node from a scene imported with Assimp?
I need to remove one object from the scene graph imported by Assimp and I can't. I've tried to change aiScene.h including a method called DelNode and I can´t. How can I do it - is it possible?

# Answer
> 4 votes
No, it is not.

You are not permitted to modify the scene that assimp returns to you (it is `const` for this reason).

Assimp's data structures should not be used for rendering etc. instead, you should copy their contents to your own data structures appropriate to your environment.

When designing Assimp, we explicitly designed it to be only usable for importing. It's not a scenegraph library.

\[That said, if you `const_cast` the scene, add that `DelNode` method to `aiScene` and NULL the slot where the node to be removed originally had been it would work as intended, but this would be a hack\].

---
Tags: c++, assimp
---


# Question
Title: Are .sln / .csproj usefull for sharing the Unity project?
We are experiencing some problems with GIT and Unity. It occurs pretty often that file .sln / .csproj give us some trouble, so after searching for a while on the web I've found that maybe this files are not necessary to push. Someone have any feedback for this? https://gist.github.com/hw/1234398 There for example are included into the .gitignore, but I honestly don't know what this kind of files does.

Can I exclude they from my repo or this file are relevant for some references in my game?

# Answer
> 22 votes
From my personal experience, I noticed it is better to exclude \*.csproj and \*.sln from source control: Unity generates these files each time you open a project or add/delete source files anyway, so you won't miss them. You can also do it manually via "Sync MonoDevelop Project" menu item.

It is especially useful to exclude them if there is more than one developer on the project, because the auto-generated content of these files can be different for each user (that depends on Unity installation path and probably some other factors), which may cause a lot of unnecessary file changes committed to the repository.

# Answer
> 2 votes
I never check in the .sln or csproj. I only check in the actually unity project. Let unity manage the solution files for you. It can be a headache if some forgets to check in only one of the .csproj from the editor folder or something. So if a new coder comes in, they check out the repo and double click a file with mondevelop or vs.

I also make sure to do an Scn ignore on all those files too, so the artist don't check them in on accident to lol

# Answer
> 0 votes
You can safely exclude those files because they are automatically re-generated by Mono. The code inside those files is being read only from open files, not protected DLLs of, for instance, paid plugin.

---
Tags: unity, version-control
---


# Question
Title: Should I load a game map as a tile map or as an image map?
Which is better for game prototyping of a game map: a tile map or an image map? What are their respective pros and cons? Should I, in other words:

* Load the map as a png and set collision points (easy to render; less work)

or

* Load the map as tiles with tiled map editor and then set the collision points.

# Answer
> 1 votes
My recommendation would be to load the map as tiles with tiled map editor and add support for reading-in objects, not just tiles, from those xml files, so you can use the objects to define the collision points. Here's an example of what I mean:

The red rectangles are objects drawn in a defined "collision" layer. Blue rectangles are objects drawn in a defined "exits" layer. And you can see an icon of a sword there, which is actually a tile-object, not a tile, and represents in game logic (in this case, a mob). There are a few advantages of this approach:

* Lets you rapidly prototype a new level. All the collisions, mapping, mobs, etc. are in the same place.
* Since you're using tiles, you can draw a different map easily. I.e., you don't have to take an image into a photo editor, you can just draw new walls etc., and play around with it.
* Separating out the game logic from the level editor lets you have someone with no (or little) knowledge of the codebase easily create maps.
* By using objects for the collisions instead of the tiles themselves, you have more versatility. I.e., you can draw polygons that aren't square for, for example, diagonal collisions. Or you can draw lines so that an un-enterable "block" needn't be a full tile wide or tall.

As noted by the astute Benjamin "Danger" Johnson in the comments below, using a tile map does have its disadvantages, including increased load times and rendering performance. In your question you mentioned your goal was for prototyping, so my general advice is not to worry about load times and performance until you're ready to worry about load times and performance. If you develop your maps with a tiled-approach, you may decide when you're ready to optimize that it's worth migrating some or all of them from a tile approach to larger images.

---
Tags: tiles, maps, tilemap, level-design
---