# Question
Title: XNA slowly stops sprite movement on key released
I'm making a game where player moves around a spaceship pressing W,S,A,D. What I would like to achieve is that I would like to make the ship stop slightly when a key is released before it went to full stop. How can I achieve that?

Here's the moving code :

```
 kbs = Keyboard.GetState();

            if (kbs.IsKeyDown(Keys.W))
            {
                this.pos.Y -= speed;
                this.animation = "up";

                if (kbs.IsKeyDown(Keys.D))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X += speed;
                    this.animation = "upright";
                }
                else if (kbs.IsKeyDown(Keys.A))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X -= speed;
                    this.animation = "upleft";
                }

                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;

                CheckStop();
            }
            else if (kbs.IsKeyDown(Keys.S))
            {
                this.pos.Y += speed;
                this.animation = "down";

                if (kbs.IsKeyDown(Keys.D))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X += speed;
                    this.animation = "downright";
                }
                else if (kbs.IsKeyDown(Keys.A))
                {
                    if (!isDirectional)
                    {
                        frameIndex = 0;
                        isDirectional = true;
                    }
                    this.pos.X -= speed;
                    this.animation = "downleft";
                }

                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;
            }
            else if (kbs.IsKeyDown(Keys.A))
            {
                this.pos.X -= speed;
                this.animation = "left";
                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;
            }
            else if (kbs.IsKeyDown(Keys.D))
            {
                this.pos.X += speed;
                this.animation = "right";
                if (!this.isAnimating) this.isAnimating = true;
                else this.isAnimating = false;
            }
            else
            {
                this.isAnimating = false;
                this.isDirectional = false;
                frameIndex = 0;
            }

```

I have been trying to check for the ship to slowly stop with CheckStop() function, here it is (for the sake of trying, on the above code I only apply CheckStop() on the 'W' key):

```
private void CheckStop()
        {
            KeyboardState nkbs = Keyboard.GetState();

            if (!kbs.IsKeyDown(Keys.W) && nkbs.IsKeyDown(Keys.W))
            {
                speed -= fraction;
                if (speed <= 0) speed = 0;
                this.pos.Y -= speed;
            }
        }

```

Any help is appreciated, thanks.

# Answer
Something like this can be achieved by using velocity/acceleration as well as dampening.

A simplified example could be something like the following. `velocity`, `position` and `max_velocity` are supposed to be vectors, but they could be single values (for one dimension, like forward trust) as well - you'd just have to modify the movement code.

```
velocity *= 0.9; // Dampening the current velocity, the smaller this number, the faster you slow down.

if (kbs.IsKeyDown(Keys.W))
    velocity.x = max(-max_velocity.x, velocity.x - .1f); // Accelerate (by .1f)
else if (kbs.IsKeyDown(Keys.D))
    velocity.x = min(max_velocity.x, velocity.x + .1f);
// Do the same here for vertical acceleration.

// Once everything is done, actually move the ship (or whatever)
position += velocity;

```

For an Asteroids like game, you could essentially do the same. Just use the x coordinate as your angle and the y coordinate as your rotation (or similar).
> 1 votes

# Answer
I find in situations like asteroid-y type games to model position(P), velocity(V), and acceleration(A), and then when updating the positions, the following procedures are carried out:

```
V += A
P += V

```

Likely in your code it would look like:

```
V.x += A.x;
V.y += A.y;
P.x += V.x;
P.y += V.y;

```

In such a model, there are two types of acceleration.... your acceleration due to thrust and your acceleration due to "drag".

Acceleration due to thrust is easy... if your engines are "on", then you provide thrust at whatever rate you decide in whatever direction your ship is pointing, probably like so:

```
AThrust.x = Math.cos(direction) * Force;
AThrust.y = Math.sin(direction) * Force;

```

(since you are using WASD, your directions are very simple... 0, pi/2, pi, -pi/2, and you may not need trig at all);

Acceleration due to drag is based on the velocity and a constant, like so:

```
A(drag) = -V * k

```

Or rather

```
ADrag.x = -V.x * k;
ADrag.y = -V.y * k;

```

(k might be 0.1 as suggested above, but you will ultimately have to work out what it is)

Each time you update your position, you then are doing the following:

```
ADrag.x = -V.x * k;
ADrag.y = -V.y * k;
V.x += ADrag.x + AThrust.x;
V.y += ADrag.y + Athrust.y;
P.x += V.x;
P.y += V.y;

```

And this will work out fine if your time units are frames and not seconds or milliseconds or whatever other actual time unit.

Otherwise, you need the delta time between the last update and this one:

```
t = currentFrameTime-lastFrameTime;
ADrag.x = -V.x * k;
ADrag.y = -V.y * k;
V.x += (ADrag.x + AThrust.x) * t;
V.y += (ADrag.y + Athrust.y) * t;
P.x += V.x * t;
P.y += V.y * t;

```
> 1 votes

---
Tags: xna, sprites, keyboard
---


title: MonoGame Mac installation instructions

text:
# Question
Title: MonoGame Mac installation instructions
Does anyone know how to install MonoGame on Mac. I have been looking around for a while and I can't find any guides. I have Mono and MonoDevelop up and running fine, but I cannot figure out how to install MonoGame. Thanks.

# Answer
> 2 votes
I found this at their GitHub page. It tells you all the things you need in advance, as well as the basic installation instructions for MonoGame itself.

# Answer
> 2 votes
I know its late but I just joint monogame and found the solution: To make it work follow the following steps:

* Install the latest xamarin studio from **http://xamarin.com/studio**
* Next download the monogame files from **https://monogame.codeplex.com/releases/view/102870**
* choose the xamarin version on mac
* Next install the templates by opening xamarin studio. Next click on the top Mac menu "Xamarin Studio" Addin Manger and choose install from file and select your donwloaded file...
* so far so good but your png files will not be loaded from here... so solve this issue follow the next steps: visit the git page from monogame and download it: **https://github.com/mono/MonoGame**
* after Downloading and unpacking the zip file go into the folder and look open the following file by using xamarin studio **MonoGame.Framework.MacOS.sln**
* Now Xamarin studio should open up and include 2 Projects: Lidgren. ... and Monogame.Framework.MacOS
* on the top of Xamarin studio (besides the play button you should see **Debug** click on it and change it to **Release**
* now do a right click on the Monogame.Framework.MacOS project and build it new
* This should be done without any errors but you may get warnings... we do not pay attention on them :D
* next do you need to go again to the downloaded Monogame folder from where you opened the **MonoGame.Framework.MacOS.sln** project.
* But this time you need to dive more deep into the folder structure: look for the following folder --\> MonoGame.Framework/bin/MacOS/Release
* the files in the release folder are now your new libraries...
* You can copy this libraries where ever you want but you should know where they are because you need to add them to your new monogame project.
* Next open up Xamarin studio and create a new Monogame project by using the already installed templates...
* Choose the Monogame Mac Application Template

We are now almost done:

* Look for the reference "folder in the project tree inside of Xamarin studio" and do a right click on Monogame to delete the reference...
* Now you need to add new references by right click on reference.
* Access the .Net-Assemblies and add your files from the MonoGame.Framework/bin/MacOS/Release/- folder (make sure that you add all of them)

The final step now is to expand your Content folder in Xamarin studio and do a left click on the logo.png file. on the left side of the IDE you can find Properties. In the properties change 3rd from top to content instead of none. If you run now the template the graphic should be loaded without any problems :D

# Answer
> 0 votes
After installing all the prerequisites listed on their GitHub tutorial page, you'll need to add the MonoGame.Framework.MacOS and Lidgren.Network.MacOS projects from the unzipped MonoGame directory to your solution. You'll then need to add MonoGame.Framework.MacOS in your project's references.

I also ran into snags when trying to set MonoGame up on a Mac. Getting a simple program up and running took a lot longer than expected. Once I got it working, I decided to post the basic template that I use for MonoGame projects on MacOS. You can find that template here. It will likely have invalid links to the MonoGame projects, but those should be simple to fix.

---
Tags: xna, c#, macos, monogame
---


# Question
Title: Sprite Animation Using Multiple Images (XNA / C#)
all.

Right now I am currently working on a game with my Australian buddy and I just am having such a difficult time with the spriting process. As the programmer of our game, it is my responsibility to get the sprites he models drawn and animated onscreen. However, the sprites he's drawing are huge images and the animation sequences are always at least 20 images wide, which means they're too big for the FileOpen method to read... Which brings me to my question: Is there a way to use a directory as the animation sequence? Like instead of stringing all the images together in a chain and animating the sequence, can I make an animation from a collection of the images in a folder?

For this example, use Animation.png to represent the chain of images version and Image1, 2, and 3.png for individual images in a directory.

Thanks in advance!

# Answer
There are many ways to approach this problem, but first let's clear some things up:

* Why are you using FileOpen? If you're programming XNA, you should use Content.Load\<\> instead.
* Actually, it's a good idea if all your frames are stored in one big image. Just store the position for each frame in a file. For this, TexturePacker comes to mind. You might have to separate all frames and merge them all again, but it'll accomodate it a lot better, and output a nice XML (or whatever you want to use) file, with all info you'll need.
> 2 votes

---
Tags: xna, c#, animation, sprites
---


# Question
Title: Are global shader variables slower than texture look ups?
I want to send quite a bit of data to the GPU, the data will never change (or will change very rarely) after it has been created. Is there a performance impact to using global shader variables or should I pack the data into a texture to perform look ups?

# Answer
Sometimes. Maybe. Maybe not. It depends.

Early shader models had a very limited count of constant registers (I'm assuming pixel shader registers here since you're comparing to texture lookups) - 8 in SM1.x, 32 in SM2.0, and scaling the giddy heights of 224 in SM3.0. What's worse, some hardware didn't even support *any* pixel shader constants natively, and needed to patch the raw shader binary in order to emulate them (some GPU manufacturers would even recompile shaders, with - IIRC - NVIDIA for example advising that values of 0.0, 0.5 and 1.0 would trigger a recompile).

Common tricks included using textures to encode trig functions, normalization, etc (which also helped with overcoming the pathetic instruction limits that these shader models had).

If you want to support this class of hardware you need to bear all of this in mind.

More recently, it's the case that ALU operations are vastly faster than texture lookups, so straightaway you have a bottleneck if you use textures for storing your data. See the accepted answer to this question for more info.

Nowadays a constant buffer would be the optimal solution, and GPUs and drivers can be expected to be optimized for that kind of usage, but since you mention "global shader variables" that indicates to me that you're using D3D9 (also looking at your "HLSL" tag here which rules out OpenGL).

If that's the case then it depends on your definition of "quite a bit of data". Note the register limits I gave above, note that you're going to want to keep some spare for other usage, and you could very quickly find yourself bumping into those limits. So a texture would be your only real option, and available register space would be a more important determining factor than performance.
> 2 votes

# Answer
For older shader models, "global" variables are just mapped to GPU registers. They may be faster at a micro-timing level than texture lookups, but you probably won't have enough of them to sufficiently represent the data you want. Updating each constant variable would also have some overhead, but since you said updates will be quite rare, that may not be a problem. Textures are probably want you want if you are using an old model.

On newer shader models (4 and up) "global" variables (shader constants) are stored in constant buffers or texture buffers. You'd want to use whichever is more appropriate for your data and update/access patterns.
> 4 votes

---
Tags: textures, shaders, hlsl
---


# Question
Title: Simulating pressure in a grid based liquid simulation
I have a 2D grid based water system in my XNA game, we have a method using cellular automata to simulate water falling and spreading.

Example of water flowing down a slope:

Each tile can contain a mass of 0 to 255 values of liquid, stored in a byte. I do not use `floats`, the old water system I had did, however it added complications and had a performance hit.

Each water tile updates itself with a simple set of rules:

1. If the tile below has space in it, move as much as possible from the current tile to the bottom one (Flow Down)
2. If the 2 sides aren't the same and aren't zero and both are passable, we get the sum of the 3 tiles (left + current + right) and divide it by 3 leaving the rest on the middle (current) tile
3. If the rule above gave a number of 2 as sum, we should divide the tiles into the two sides (1, 0, 1)
4. If rule 2 gave 1 as the sum, choose a random side to flow into
5. If rule 2 failed, we should check if one side is passable and the other isn't. If that is true, we split the current tile in half for the 2 tiles

How can I expand this logic to include pressure? Pressure will make liquids rise over "U-Bends" and fill in air pockets.

Example on how this currently fails:

The water should flow and equalize on each side of the U-Bend. Additionally, I have created methods to find out how far down a water block is, and therefore how much pressure it is experiencing. Now I need to be able to take these numbers and apply them to the other areas to equalize the pressure.

# Answer
> 7 votes
Note that I've never done this; these are only ideas which may help. Or might be totally bogus. I'd been wanting to tackle this problem ever since Terraria but am not currently working on such a game.

A way I've considered trying is to give each *surface water block* (any block with water in it and with no water block above it) an initial pressure value equal to (or a function of) its height from the bottom of the world. The implicit pressure value of any impassable tile is `MAX_PRESSURE` (say 255), and for an open air tile is `MIN_PRESSURE` (0).

Pressure is then spread up/down/sideways from any tile with a higher pressure to tiles with a lower pressure during each tick, cellular automata style. I'd have to get an actual simulation up to figure out exactly what to equalize to. A block's pressure should be equal to its implicit pressure plus the "excess" pressure from around equalized (so you'd only need to store this excess pressure, not the implicit pressure).

If a surface tile has a pressure larger than its implicit height-based pressure would be and if the tile above has free space for water, a small portion of water is moved upward. Water only flows down if the tile both has room as has lower pressure than expected.

This roughly simulates the idea that the deeper the water "point" the more pressure it has, albeit the pressure values represent more the height than actual pressure (since higher tiles are expected to have higher "pressure"). This makes the pressure kinda sorta like the `h` term in the equation (but not really):

```
P' = P + qgh

```

The result is that if the water's pressure is higher than it should be for its depth, it'll be pushed up. It should mean that water levels in closed systems will equalize pressure across all height levels over time.

I'm unsure how to deal with or whether one even needs to deal with the "air bubbles" that would be created (where a non-surface tile will have non-full water amounts as water is pushed upwards). I'm also still unsure how'd you'd avoid loops of water pressures being unequal on one side and then after ticking being unequal on the other side, back and forth.

# Answer
> 20 votes
I created a system similar to the one you're after in 3D. I have a short video demonstrating the simple mechanics of it here and a blog post here.

Here's a little gif I made of the pressure mechanics behind an invisible wall (played at high speed):

Let me explain the data involved, to give an idea of some of the features of the system. In the current system, each block of water contains the following in 2 Bytes:

```
//Data2                          Data
//______________________________  _____________________________________
//|0    |0      |000   |000    |  |0        |0       |000      |000   |
//|Extra|FlowOut|Active|Largest|  |HasSource|IsSource|Direction|Height|
//------------------------------  -------------------------------------

```
* `Height` is the amount of water in the cube, similar to your pressure, but my system just has 8 levels.
* `Direction` is the direction the flow is going. When deciding where the water will flow next, it's more likely to continue in its current direction. This is also used to quickly back trace a flow back up to its source cube when needed.
* `IsSource` indicates if this cube is a source cube, meaning it never runs out of water. Used for the source of rivers, springs, etc. The cube on the left in the gif above is a source cube, for example.
* `HasSource` indicates if this cube is connected to a source cube. When connected to a source, cubes will try to tap the source for more water before seeking other "fuller" non-source cubes.
* `Largest` tells this cube what the largest flow between it and its source cube is. This means if water is flowing through a narrow gap, it limits the flow to this cube.
* `Active` is a counter. When this cube has active flow going through it, to it, or from it, active gets incremented. Otherwise active is randomly decremented. Once active hits zero (meaning not active), the amount of water will start to be reduced in this cube. This kind of acts like evaporation or soaking into the ground. (If you have flow, you should have ebb!)
* `FlowOut` indicates if this cube is connected to a cube that's on the edge of the world. Once a path to the edge of the world is made, water tends to choose that path over any other.
* `Extra` is an extra bit for future use.

Now that we know the data, lets look at a high level overview of the algorithm. The basic idea of the system is to prioritize flowing down and out. As I explain in the video, I work from the bottom up. Each layer of water is processed one level at a time in the y axis. The cubes for each level are processed randomly, each cube will attempt to pull water from its source on each iteration.

Flow cubes pull water from their source by following their flow direction back up until they reach a source cube or a flow cube with no parent. Storing the flow direction in each cube makes following the path to the source as easy as traversing a linked list.

The pseudo code for the algorithm is as follows:

```
for i = 0 to topOfWorld //from the bottom to the top
   while flowouts[i].hasitems() //while this layer has flow outs
       flowout = removeRandom(flowouts[i]) //select one randomly
       srcpath = getPathToParent(flowout) //get the path to its parent
       //set cubes as active and update their "largest" value
       //also removes flow from the source for this flow cycle
       srcpath.setActiveAndFlux()

//now we deal with regular flow
for i = 0 to topOfWorld //from the bottom to the top
    while activeflows[i].hasitems() //while this layer has water
        flowcube = removeRandom(activeflows[i]) //select one randomly
        //if the current cube is already full, try to distribute to immediate neighbors
        flowamt = 0
        if flowcube.isfull
           flowamt = flowcube.settleToSurrounding
        else
           srcpath = getPathToParent(flowcube) //get the path to its parent
           flowamt = srcpath.setActiveAndFlux()
           flowcube.addflow(flowamt)

        //if we didn't end up moving any flow this iteration, reduce the activity
        //if activity is 0 already, use a small random chance of removing flow
        if flowamt == 0
           flowcube.reduceActive()

 refillSourceCubes()

```

The basic rules for expanding a flow where (ordered by priority):

1. If cube below has less water, flow down
2. If adjacent cube on same level has less water, flow laterally.
3. If cube above has less water AND source cube is higher than the cube above, flow up.

I know, that's pretty high level. But it's hard to get into more detail without getting *way* into detail.

This system works pretty well. I can easily fill up pits of water, which overflow to continue outward. I can fill up U shaped tunnels as you see in the gif above. However, as I said, the system is incomplete and I haven't worked everything out yet. I haven't worked on the flow system in a long time (I decided it wasn't needed for alpha and I'd put it on hold). However, the issues I was dealing with when I put it on hold where:

* **Pools**. When getting a large pool of water, the pointers from child to parent are like a crazy mess of whatever random cube was selected to flow whatever direction. Like filling a bathtub with silly string. When you want to drain the tub, should you follow the path of the silly string back to its source? Or should you just take whatever is closest? So in situations where cubes are in a big pool, they should likely just ignore their parent flows and pull from whatever is above them. I came up with some basic working code for this, but was never had an elegant solution I could be happy with.
* **Multiple parents**. A child stream could easily be fed by more than one parent stream. But the child having a pointer to a single parent wouldn't allow that. This can be fixed by using enough bits to allow for a bit for each possible parent direction. And likely changing the algorithm to randomly select a path in the case of multiple parents. But, I never got around to it to test and see what other issues that might expose.

# Answer
> 2 votes
I sort of agree with Sean but I would do it a bit differently:

A block generates a pressure equal to it's own weight (how much water is in it) and applies it to the blocks below and beside it. I see no reason it's position in the world is relevant.

On each tick move water from high pressure to low pressure but move only a fraction of the water needed to equalize. Water can also be pushed up if the pressure in the block is too great for the pressure being applied down on the square.

You will get loops where the water pressure flows too far one way and then has to correct but since you don't move the whole amount of water per tick these will be damped. I think it's actually a good thing as you'll get surge effects as water floods into an area like you would in reality.

# Answer
> 1 votes
You can add a rule that try to go left or right (through the walls) with the tiles until you find a free spot, starting with the layers on the bottom. If you cannot find, then the tile stays on the current position. If you find, then the another rules will guarantee the replacement of the moved tile (if necessary).

# Answer
> -2 votes
why cant you define another type of block that acts as an immovable amount of pressure? Therefore when you use your way of normally moving the water blocks and checking whether it can move up, it cant.

Even better would be to add another definition to those blocks that allows the user to enter the amount of pressure per block, increasing the pressure according to the amount of water blocks adding to it.

---
Tags: xna, c#, physics, grid, water
---


title: Drawing graphics in GAE

text:
# Question
Title: Drawing graphics in GAE
I have seen a lot of questions about making a game using Google app engine. I have run into a problem that I cant seem to find any answers to. What can I actually use to draw my game? Are there any libraries that GAE supports? Any feedback is appreciated.

# Answer
> 0 votes
There is a limitation about graphics support in GAE. However, Google App Engine supports client side graphics via Google Web Toolkit (GWT) and Web Browser capabilities (like Canvas, JavaScript or SVG native support).

Link with these and more info:

http://www.tinyline.com/tinylineforgae.pdf

Hope it helps!

---
Tags: java, google-app-engine
---


title: Vector Math question

text:
# Question
Title: Vector Math question
Suppose I have two game object located at two Vector3s v1 and v2, respectively. If I wanted to locate a position between v1 ad v2, but 3 units away from v2, how would I manage that in terms of calculating the target vector (vT)? Basically, I want object 1 to translate toward object2, so that it can play an attack animation a reasonable distance away from the combat target without being on top of it.

I calculate a vector pointing from v2 to v1:

```
Vector3 heading = v1 - v2;
Vector3 headingNorm = heading.Normalize();

```

From there, how to I "add 3 units in the direction of v1 from v2" to get the target position?

Thanks in advance!

# Answer
Vector3 vT = v2 + headingNorm * 3;

Be careful though, if v2 and v1 happen to be closer than 3 units away this will put you on the far side of v1. Maybe you want this to make the unit step back to make room for the attack. But then again be careful, because that means as you approach that attack point you will overshoot then correct and overshoot the otherway over and over again!
> 10 votes

---
Tags: vector, linear-algebra
---


# Question
Title: What is the relation between the Zynga platform and facebook games?
I decided to check the Zynga platform because I heard that Zynga can now host games and one is able to play these games using a Zynga account.

After registering for a game, I noticed that it opened directly and didn't ask me to create an account (as it is using my Zynga account).

The weird thing is the game's website sends you to its facebook page, where I have to log in using my facebook account to play.

How could a facebook game allow someone to play through the Zynga platform?

# Answer
The facebook canvas game API is simply an iframe loading external content. It is perfectly conceivable that the same game software could function outside that iframe.

Any website can support using facebook's API and an authentication (log-in) mechanism. It is only a slightly different API than the canvas. There would need to be some extra work, but the port would be very straightforward.
> 1 votes

---
Tags: server, facebook
---


# Question
Title: Use FlxAnim to Animate a FlxSprite in Flixel on FlashBuilder
I am trying to animate a FlxSprite, whose image I loaded from an embedded sprite sheet. I instantiate the sprite like this:

```
// embedding a png file given a relative path
[Embed(source="../Images/BatGraphic.png")] public var Bat_Enemy:Class;
override public function create():void
{
//instantiate bat sprite
bat = new FlxSprite(FlxG.width/2-5,FlxG.width/2);
bat.loadGraphic(Bat_Enemy,true,false,30,12,false);

//add animation to bat
var frames:Array = new Array(12);
AddAnimationToSprite(bat,frames,"batAnimation",30);
//add bat enemy to screen
add(bat);

```

I use this function to add the animation to the sprite, it essentially just calls the Flixel API:

```
public function AddAnimationToSprite(sprite:FlxSprite, frames:Array,animName:String,frameRate:int):void
{
   var animation:FlxAnim = new FlxAnim(animName,frames,frameRate,true);
   sprite.addAnimation(animName,frames,frameRate,true);

}

```

Then, in the update function, I call the FlxSprite play method to animate the sprite:

```
public function update:void()
{
/*animate relevant sprites*/
bat.play("batAnimation",true);
/*end animation*/

/*update screen based on player position*/
super.update();
}

```

Yet, the sprite does not animate. Is there a step I am missing? How do you use FlxAnim to animate a FlxSprite?

Update: I altered the code so that the `FlxAnim.play()` is called in the `create` as suggested as follows:

```
//instantiate bat sprite
bat = new FlxSprite(FlxG.width/2-5,FlxG.width/2);
bat.loadGraphic(Bat_Enemy,true,false,30,12,false);

//add animation to bat
var frames:Array = new Array(12);
//AddAnimationToSprite(bat,frames,"batAnimation",30);
var batAnim:FlxAnim = new FlxAnim("batAnim",frames,30,true);

add(bat);
bat.play("batAnim");

```

However, still nothing happens. Potentially, I don't have the right number of frames, since I only wanted to use the first row of sprites in the sheet to animate. But even if the number of frames were off, it should still be animating in some fashion right? Like flickering between two sprites? What am I missing here? Is 30 the appropriate fps for Flixel animations?

# Answer
Simple, you're calling `bat.play("batAnimation",true);` in your `update` loop. That means, your animation will restart every frame, resulting in a still image.

The second parameter to the play function is a flag whether or not the animation should be forced to restart (see docs). So either call:

```
bat.play("batAnimation", false);

```

in your update loop, or what I would consider a better approach is to call `bat.play("batAnimation",true);` somewhere outside the `update` method. For example here:

```
...
//add bat enemy to screen
add(bat);
bat.play("batAnimation");

```
> 2 votes

# Answer
You're not filling your array with anything. It has to contain numbers for the FlxSprite class to understand it. Otherwise you're sending in an array of size 12 filled with all 0's.
> 0 votes

---
Tags: animation, sprites, flash, actionscript-3, flixel
---


# Question
Title: Is it a good idea to use box2d to control sprite movement in a 2D game?
I'm trying to use Box2D to control sprite movement.Some burning issues are these:

1.When I trying to move the sprite on a slope or a lean barrier. The sprite will move off the slope which is not what I want.

2.ALternatively, I could use setPosition or CCAction which provides by cocos2d-x to move the sprite and update the body position use SetTransform. But the body will lost it's physical limitation, it will passthrough other body.

Thanks for your time, if you guys got any solution?

# Answer
> 1 votes
This is a really hard question, because in the end it will depend on the kind of game you're trying to create. In most cases however, using a physics engine like Box2D might be overkill.

Especially for simple 2D platformers that don't include any physics puzzles, I'd go with doing the math on your own. It's not that hard to be honest.

To be able to stand on terrain and slopes, you just have to implement some very basic movement:

* **Movement:** When hitting left/right, just move your character to the left or right, don't worry about collision. Either move your character absolute distances or adjust his velocity.
* **Gravity:** Check to see whether there's something solid at the character's feet (depending on your implementation you might skip this check as you'll check it next anyway). If there isn't, move or accelerate him downwards.
* **Collisions:** After moving your character, verify he's not entering anything solid:
    + Move the character to the right while his left part is in something solid.
    + Move the character to the left while his right part is in something solid.
    + Move the character upwards while his bottom part is in something solid.
    + Move the character downwards while his top part is in something solid.
    + If two opposite sides of the character are stuck in something solid (left and right or top and bottom), your character is squeezed. In games like Super Mario Bros this results in your character being killed.

Back to your initial question with the slope: Using the above logic, your character won't follow the slope at first. It will essentially move "into" the slope. But thanks to the logic under **Collisions** he'll be adjusted upwards, essentially following the slope up (or down).

---
Tags: box2d, cocos2d-x
---


# Question
Title: Create a physics body with hole : bullet physics
I am writing an iOS game, using bullet for physics, blender to create models, cocos3d as the game engine.

I have a model like this

Basically there is a plane, with a hole, and a UVSphere. Both were created in blender. What I am trying is to create a physics body along the vertices of the plane. So that when the UVSphere goes over the hole, it should fall through.

I am using `btBvhTriangleMeshShape` to create physics body along the vertices of this plane. code is given below

```
//GPlane stands for groundPlane :)
CC3MeshNode* gPlaneNode  = (CC3MeshNode*)[self getNodeNamed:@"GPlane"];

/*Get Vertex and indices data out from the .pod*/
float *gVertexData       = (float*)((CC3VertexArrayMesh*)gPlaneNode.mesh)
                                .vertexLocations.vertices;
GLushort* gIndices       = (GLushort*)((CC3VertexArrayMesh*)gPlaneNode.mesh)
                                .vertexIndices.vertices;
int gIndiceCount         = ((CC3VertexArrayMesh*)gPlaneNode.mesh)
                                .vertexIndices.vertexCount;

/*Create triangle mesh*/
btTriangleMesh* gTriangleMesh = new btTriangleMesh();
for (int i = 0; i < gIndiceCount; i+=3)
{
   unsigned int index1 = gIndices[i] * 6;
   unsigned int index2 = gIndices[i+1] * 6;
   unsigned int index3 = gIndices[i+2] * 6;
   gTriangleMesh->addTriangle(
      btVector3(gVertexData[index1] , gVertexData[index1+1], gVertexData[index1+2]),
      btVector3(gVertexData[index2] , gVertexData[index2+1], gVertexData[index2+2] ),
      btVector3(gVertexData[index3] , gVertexData[index3+1], gVertexData[index3+2]));
}

/*Create  a rigid body using this triangle mesh*/
btBvhTriangleMeshShape *gTriMeshShape   =   new
                          btBvhTriangleMeshShape(gTriangleMesh,true);
gTriMeshShape->setMargin(0.1);
btDefaultMotionState *groundMotionState =
                new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1)
                                           ,btVector3(0,0.0,0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0
                   ,groundMotionState,gTriMeshShape,btVector3(0,0,0.0));
groundRigidBodyCI.m_restitution = 0.3;
btRigidBody *groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);

```

And I am adding the sphere to the scene like this

```
sphereNode    =   (CC3MeshNode*)[self getNodeNamed:@"Sphere"];
btCollisionShape *fallShape = new btSphereShape(1);
btDefaultMotionState *fallMotionState = new btDefaultMotionState(btTransform(
           btQuaternion(sphereNode.location.x,sphereNode.location.y
              ,sphereNode.location.z,1), btVector3(0,0,0)));
btScalar mass = 1.0;
btVector3 fallInertia(0,0,0);
fallShape->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass
                      ,fallMotionState,fallShape,fallInertia);
fallRigidBodyCI.m_restitution = 1.0;
fallRigidBody = new btRigidBody(fallRigidBodyCI);
fallRigidBody->setDamping(0.3,0.8);
dynamicsWorld->addRigidBody(fallRigidBody);

```

To view the physics body, I use bullet physics debug drawing method and this is how it is drawn

As far as I can tell, physics body looks fine, the hole is there alright.

## My problem

It is simple. My ball just slide over the hold instead of falling through it. I expect with a mass and negative Y gravity, the ball to fall through the hole.

Ball is falling of the edge of the plane alright. So gravity is there.

Any idea?

# Answer
Okay, I got this working. I changed the sphere adding code to this

```
CC3MeshNode *node =  (CC3MeshNode*)[self getNodeNamed:@"Sphere"];

//This was the magic step.. I don't know how
//copying helped. But it did
CC3MeshNode *sphereNode = (CC3MeshNode*)[node copyWithName:@"someOtherName"];

sphereNode.location             =   cc3v(0.0, 1.0, 10);
[self addChild:sphereNode];

//Remove the original node, since we no longer need this.
[self removeChild:node];

//Now physics body.
btCollisionShape *fallShape = new btSphereShape(0.5);

//This line also different.. Compare with the code in question
btDefaultMotionState *fallMotionState
     =  new btDefaultMotionState(btTransform(btQuaternion(
         sphereNode.location.x, sphereNode.location.y, sphereNode.location.z,1)
         ,btVector3(sphereNode.location.x,sphereNode.location.y
         ,sphereNode.location.z)));
btScalar mass  =   1.0;
btVector3 fallInertia(0,0,0);
fallShape->calculateLocalInertia(mass, fallInertia);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(
                 mass,fallMotionState,fallShape,fallInertia);
fallRigidBodyCI.m_restitution   =   1.0;
btRigidBody* fallRigidBody =   new btRigidBody(fallRigidBodyCI);
fallRigidBody->setDamping(0.3,0.8);
dynamicsWorld->addRigidBody(fallRigidBody);

```
> 1 votes

---
Tags: ios, blender, bullet-physics, cocos3d
---


# Question
Title: Create bullet physics rigid body along the vertices of a blender model
I am working on my first 3D game, for iphone, and I am using **Blender** to create models, **Cocos3D game engine and Bullet** for physics simulation. I am trying to learn the use of physics engine.

## What I have done

I have created a small model in blender which contains a **Cube** (default blender cube) at the origin and a **UVSphere** hovering exactly on top of this cube (without touching the cube)

I saved the file to get MyModel.blend. Then I used

```
File -> Export -> PVRGeoPOD (.pod/.h/.cpp)

```

in Blender to export the model to **.pod** format to use along with **Cocos3D**.

In the coding side, I added necessary bullet files to my Cocos3D template project in XCode.

I am also using a bullet objective C wrapper.

```
-(void) initializeScene {
    _physicsWorld = [[CC3PhysicsWorld alloc] init];
    [_physicsWorld setGravity:0 y:-9.8 z:0];

    /*Setup camera, lamp etc.*/
    ..........
    ...........

    /*Add models created in blender to scene*/
    [self addContentFromPODFile: @"MyModel.pod"];

    /*Create OpenGL ES buffers*/
    [self createGLBuffers];

    /*get models*/
    CC3MeshNode* cubeNode    = (CC3MeshNode*)[self getNodeNamed:@"Cube"];
    CC3MeshNode* sphereNode  = (CC3MeshNode*)[self getNodeNamed:@"Sphere"];

    /*Those boring grey colors..*/
    [cubeNode setColor:ccc3(255, 255, 0)];
    [sphereNode setColor:ccc3(255, 0, 0)];

    float *cVertexData  = (float*)((CC3VertexArrayMesh*)cubeNode.mesh).vertexLocations.vertices;
    int cVertexCount    = (CC3VertexArrayMesh*)cubeNode.mesh).vertexLocations.vertexCount;

    btTriangleMesh* cTriangleMesh  = new btTriangleMesh();

//    for (int i = 0; i < cVertexCount * 3; i+=3) {
//        printf("\n%f", cVertexData[i]);
//        printf("\n%f", cVertexData[i+1]);
//        printf("\n%f", cVertexData[i+2]);
//    }

    /*Trying to create a triangle mesh that curresponds the cube in 3D space.*/
    int offset = 0;
    for (int i = 0; i < (cVertexCount / 3); i++){
        unsigned int index1 = offset;
    unsigned int index2 = offset+6;
    unsigned int index3 = offset+12;
    cTriangleMesh->addTriangle(
           btVector3(cVertexData[index1], cVertexData[index1+1], cVertexData[index1+2] ),
           btVector3(cVertexData[index2], cVertexData[index2+1], cVertexData[index2+2] ),
           btVector3(cVertexData[index3], cVertexData[index3+1], cVertexData[index3+2]
        ));
        offset += 18;
    }

    [self releaseRedundantData];

    /*Create a collision shape from triangle mesh*/
    btBvhTriangleMeshShape* cTriMeshShape   =   new btBvhTriangleMeshShape(cTriangleMesh,true);
    btCollisionShape *sphereShape =   new btSphereShape(1);

    /*Create physics objects*/
    gTriMeshObject  = [_physicsWorld createPhysicsObjectTrimesh:cubeNode shape:cTriMeshShape mass:0 restitution:1.0 position:cubeNode.location];
    sphereObject    = [_physicsWorld createPhysicsObject:sphereNode shape:sphereShape mass:1 restitution:0.1 position:sphereNode.location];
    sphereObject.rigidBody->setDamping(0.1,0.8);
}

```

When I run the sphere and cube shows up fine. I expect the sphere object to fall directly on top of the cube, since I have given it a mass of 1 and the physics world gravity is given as -9.8 in y direction. But What is happening the spere rotates around cube three or times and then just jumps out of the scene. Then I know I have some basic misunderstanding about the whole process.

So my question is, how can I create a physics collision shape which corresponds to the shape of a particular mesh model. I may need complex shapes than cube and sphere, but before going into them I want to understand the concepts.

# Answer
> 2 votes
Well, I got this working. I had to make some changes. For starters, I did throw out the Bullet wrapper, and used my own code to create physics bodies.

These are the changes I have done.

## Changes in code

My `initializeScene` method now looks like this

```
-(void) initializeScene {
   // Create the camera, place it back a bit, and add it to the scene
   CC3Camera* cam  = [CC3Camera nodeWithName: @"Camera"];
   cam.location    =   cc3v( 0.0, 7.0, 10.0 );
   cam.rotation    =   cc3v(-20.0, 0.0, 0.0);
   [self addChild: cam];

   CC3Light* lamp  =   [CC3Light nodeWithName: @"Lamp"];
   lamp.location   =   cc3v( -2.0, 2.0, 10.0 );
   lamp.isDirectionalOnly  =   NO;
   [cam addChild: lamp];

   [self addContentFromPODFile: @"MyModel.pod"];

   [self createGLBuffers];

    //Bullet codes
    btBroadphaseInterface* broadphase = new btDbvtBroadphase();
    btDefaultCollisionConfiguration* collisionConfiguration =
                         new btDefaultCollisionConfiguration();
    btCollisionDispatcher* dispatcher
           = new btCollisionDispatcher(collisionConfiguration);
    btSequentialImpulseConstraintSolver* solver
           = new btSequentialImpulseConstraintSolver();
    dynamicsWorld
           = new btDiscreteDynamicsWorld(dispatcher
              ,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0,-10.0,0));

    /*get models*/
    CC3MeshNode* cubeNode    = (CC3MeshNode*)[self getNodeNamed:@"Cube"];
    CC3MeshNode* sphereNode  = (CC3MeshNode*)[self getNodeNamed:@"Sphere"];

    /*Those boring grey colors..*/
    [cubeNode setColor:ccc3(255, 255, 0)];
    [sphereNode setColor:ccc3(255, 0, 0)];

    [self setPhysicsBodyForCube:cubeNode];

    [self setPhysicsBodyForSphere:sphereNode];

    [self releaseRedundantData];

    [[CCScheduler sharedScheduler]
       scheduleSelector:@selector(updatePhysics:)
       forTarget:self interval:0 paused:NO];
}

```

and `setPhysicsBodyForCube` method is

```
-(void)setPhysicsBodyForCube:(CC3MeshNode*)mesh{
    float *gVertexData = (float*)((CC3VertexArrayMesh*)mesh.mesh)
                            .vertexLocations.vertices;
    GLushort* gIndices = (GLushort*)((CC3VertexArrayMesh*)mesh.mesh)
                            .vertexIndices.vertices;
    int gIndiceCount   = ((CC3VertexArrayMesh*)mesh.mesh)
                            .vertexIndices.vertexCount;
    btTriangleMesh* gTriangleMesh = new btTriangleMesh();

    float locX =   mesh.location.x;
    float locY =   mesh.location.y;
    float locZ =   mesh.location.z;

    for (int i = 0; i < gIndiceCount; i+=3){
        unsigned int index1 = gIndices[i] * VERTEX_SIZE;
        unsigned int index2 = gIndices[i+1] * VERTEX_SIZE;
        unsigned int index3 = gIndices[i+2] * VERTEX_SIZE;
        gTriangleMesh->addTriangle(
              btVector3(  gVertexData[index1] + locX
                        , gVertexData[index1+1] + locY
                        , gVertexData[index1+2] + locZ),
              btVector3(  gVertexData[index2] + locX
                        , gVertexData[index2+1] + locY
                        , gVertexData[index2+2] + locZ),
              btVector3(  gVertexData[index3] + locX
                        , gVertexData[index3+1] + locY
                        , gVertexData[index3+2] + locZ));
    }//end of for loop.

    btBvhTriangleMeshShape *gTriMeshShape
              =   new btBvhTriangleMeshShape(gTriangleMesh,true);
    btDefaultMotionState *groundMotionState
              =   new btDefaultMotionState(btTransform(
                        btQuaternion(0,0,0,1),btVector3(0,-.1,0)));
    btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(
                0,groundMotionState,gTriMeshShape,btVector3(0,0,0.0));
    groundRigidBodyCI.m_restitution = 0.3;
    btRigidBody *groundRigidBody = new btRigidBody(groundRigidBodyCI);
    dynamicsWorld->addRigidBody(groundRigidBody);
}

```

and finally my `setPhysicsBodyForSphere` method is..

```
-(void) addSphereToScene:(CC3MeshNode*)node{
   CC3MeshNode *sphereNode = (CC3MeshNode*) [node
                    copyWithName:@"SomeOtherName"];
   sphereNode.location    = cc3v(0.0, 10.0, 0.0);
   //for some reason, this copying is necessary.
   [self addChild:sphereNode];

   //remove the original node, since we have a replacement.
   [self removeChild:node];

   btCollisionShape *fallShape = new btSphereShape(0.5);
   btDefaultMotionState *fallMotionState =
        new btDefaultMotionState(btTransform(
               btQuaternion(sphereNode.location.x, sphereNode.location.y
                       , sphereNode.location.z,1),
              btVector3(sphereNode.location.x,sphereNode.location.y
                       , sphereNode.location.z)));
   btScalar mass =  1.0;
   btVector3 fallInertia(0,0,0);
   fallShape->calculateLocalInertia(mass, fallInertia);
   btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(
                  mass,fallMotionState,fallShape,fallInertia);
   fallRigidBodyCI.m_restitution   =   1.0;
   btRigidBody* fallRigidBody      =   new btRigidBody(fallRigidBodyCI);
   fallRigidBody->setDamping(0.3,0.8);
   dynamicsWorld->addRigidBody(fallRigidBody);
}

```

Now one thing, I need to explain is the constant `VERTEX_SIZE` used in `setPhysicsBodyForCube` method. When we take the vertex array in code using below line

```
float *gVertexData = (float*)((CC3VertexArrayMesh*)mesh.mesh)
                            .vertexLocations.vertices;

```

we get the vertex array, interleaved with

* normals of each vertex
* texture uv coordinates (if textures are there)

So where there is no texture in your model (cube in my case), the vertex arrays is arranged like this.

```
v1X, v1Y, v1Z, n1X, n1y, n1z, v2X, v2Y... so on..

```

The second vertex coordinate gets started at index 6 in vertex array. So in this case we need to set `VERTEX_SIZE` as 6.

```
#define VERTEX_SIZE 6

```

When there is texture in your model, the vertex array is aligned like this

```
v1X, v1Y, v1Z, n1X, n1y, n1z, uX, uY, v2X, v2Y... so on..

```

and in this case `VERTEX_SIZE` is 8

```
#define VERTEX_SIZE 8

```

I am sure there may be a way to get this offset value straight from the model. But I couldn't find one when I searched. If anyone knows this, please let us know.

## Changes in the way I exported the POD

You can see I am creating a triangle Mesh to create the physics body. You can export the triangle mesh used to create the model in the first place along with your vertices when you export. So when I exported the model using PVRGeoPOD exporter in blender, I used

```
  primitive type -> indexed triangle list
  export Materials -> checked
  Export transformation as Matrices -> checked

```

## Physics Debug

As user @Byte56 suggested in comments, you can draw debug lines to see where your physics body stand. I have already written an answer about bullet physics debugging. So I am not going to repeat. Thank you @Byte56 for the help.

---
Tags: collision-detection, blender, bullet-physics, cocos3d
---


title: Slick2D and Nifty GUI

text:
# Question
Title: Slick2D and Nifty GUI
I am currently trying to combine both slick2d and nifty to work together. I've had some amount of success - I can now actually run my test and it won't crash. As far as I can tell, it will also receive input properly.

First, I'm having doubts I'm doing it right. I extend NiftyStateBasedGame in my outer game and then I extend two NiftyOverlayGameState to create the two states. However, I am getting an error that doesn't crash my application saying:

```
WARNING: An event service by the name NiftyEventBusalready exists.  Perhaps multiple threads tried to create a service about the same time?
org.bushe.swing.event.EventServiceExistsException: An event service by the name NiftyEventBusalready exists.  Perhaps multiple threads tried to create a service about the same time?
    at org.bushe.swing.event.EventServiceLocator.setEventService(EventServiceLocator.java:123)

```

I could ignore it, since the application is running well enough (I think?) but I'm concerened that once I figure out how to actually implement some parts of the GUI they might not work.

Which leads me to my next question. I was trying to create a simple button on screen and I could not for the life of me figure out how to go about it. I have my nifty instance... But what do I do with it? Any pointers in the right direction would be greatly appriciated!

My three classes:

The outer class, TheGame (This is the StateBasedGame)

```
public class TheGame extends NiftyStateBasedGame
{

    Menu menu;
    Nifty nifty;
    GameOver go;

    public TheGame(String name)
    {
        super(name);
        menu = new Menu();
        go = new GameOver();

    }

    @Override
    public void initStatesList(GameContainer arg0) throws SlickException
    {
        this.addState(menu);
        this.addState(go);

    }

    public static void main(String[] args) throws Exception
    {
        AppGameContainer game = new AppGameContainer(new TheGame("OMG, Super test!"));

        game.setDisplayMode(800, 600, false);
        game.setAlwaysRender(true);

        game.start();

    }

```

And the two dummy classes the are the states:

```
public class Menu extends NiftyOverlayGameState
{
    @Override

    protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException
    {
        initNifty(gc, sbg);
    }

    @Override
    protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException
    {
        g.drawString("Does it work?", 100, 100);

    }

    @Override
    protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
    {
        Input input = gc.getInput();
        if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
            sbg.enterState(1);
    }

    public int getID()
    {
        return 0;
    }

public class GameOver extends NiftyOverlayGameState
{

    protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException
    {
        initNifty(gc, sbg);
    }

    @Override
    protected void renderGame(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException
    {
        g.drawString("WORKS, OOOH-YEA!", 100, 100);
    }

    @Override
    protected void updateGame(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
    {
        Input input = gc.getInput();
        if (input.isMouseButtonDown(Input.MOUSE_RIGHT_BUTTON))
            sbg.enterState(0);
    }

    public int getID()
    {
        return 1;
    }

```

Again, if compiled, this gets me the two screens I want with the warning/exception I mentioned above. What am I doing wrong? And how would I start actually adding GUI elements to this?

# Answer
> 2 votes
first off: You are doing it the right way. How ever something is wrong with your classes. There are `abstract` methods in the `NiftyOverlayGameState` you are not implementing in your samples.

I am talking about:

```
/**
 * Enter the game state. This function is called during the default {@link #enter(GameContainer, StateBasedGame)}
 * function call.
 *
 * @param container the container that displays the game
 * @param game the state based game this state is a part of
 * @throws SlickException in case entering the state fails
 */
protected abstract void enterState(GameContainer container, StateBasedGame game) throws SlickException;

/**
 * Leave the game state. This function is called during the default {@link #leave(GameContainer, StateBasedGame)}
 * function call.
 *
 * @param container the container that displays the game
 * @param game the state based game this state is a part of
 * @throws SlickException in case entering the state fails
 */
protected abstract void leaveState(GameContainer container, StateBasedGame game) throws SlickException;

/**
 * This function should be used to prepare the actual GUI and the controllers of the Nifty GUI. It is called right
 * after the Nifty GUI got initialized.
 *
 * @param nifty the Nifty GUI that got initialized
 * @param game the game this state is part of
 */
protected abstract void prepareNifty(Nifty nifty, StateBasedGame game);

```

While you might not need the `enterState` and `leaveState` functions right away, the `prepareNifty` function is very important. Inside this function you have to load the GUI itself.

Loading the GUI is done on two ways. Either using the builder classes or using the XML loader.

You find a sample on how to use the builder classes here in the Nifty-Examples. For example here: Nifty-Examples - Default Controls - Source

As for the XML loading. This is simply done using `nifty.fromXML("gui.xml", "startScreen")`. The XML Files look like this for example. You find more examples for these as well in the Nifty-GUI examples. Nifty-GUI fetches the XML files using the context classloader. So you need to apply the path to the file starting at the root resource or source path.

In addition I recommend a look at the manual of the Nifty-GUI. You find this one here.

I hope this helps you getting started with the Nifty-GUI. :)

Oh and the warning... this one usually appears if the initialization of the Nifty-GUI is called twice for any reason. In your code I fail to see any reason for that. The warning is not critical. But its a indication that the initialization process is flawed and most likely slower then it has to be.

---
Tags: gui, slick, nifty-gui
---


# Question
Title: Lightweight Simple Fast-Object Collision Detection Algorithm/Logic
I'm making a game where i need to give my objects collision, but i have many fast small objects and normal collision algorithms (Intersection of shapes and such) do not work, because the position+speed iteration advances the walls and there's never actually an Intersection.

I've reserched on those algorithms for a while but they all seem so unecessary complicated, checking all the wall's lines (being that the wall is a rectangle, 4 lines needed to check for each wall..) and maybe resource-expensive...

So i've started constructing my own (Maybe it already exists but i didnt see it anywhere) collision algorithm based on saving the last position the object was.

Please see the following image:

The idea is demonstrated in frame 1 and 2 of the image. Basicly by checking if there's a wall between the left side of the last rectangle and the right side of the new rectangle, i never skip zones while i check collision, and there's no risk of skipping a wall (so i thought).

This is the (sloppy and half-assed) code of the algorithm:

```
    private void bounce(GameElement b, Terrain t)
{
    Rectangle tR = t.getRectangle();
    int tRleft = tR.x;
    int tRright = tR.x+tR.width;
    int tRup = tR.y;
    int tRdown = tR.y+tR.height;

    Rectangle bRnow = b.getRectangle();
    int bRnowLeft = bRnow.x;
    int bRnowRight = bRnow.x+bRnow.width;
    int bRnowUp = bRnow.y;
    int bRnowDown = bRnow.y+bRnow.height;

    Rectangle bRlast = b.getRectangleLast();
    int bRlastLeft = bRlast.x;
    int bRlastRight = bRlast.x+bRlast.width;
    int bRlastUp = bRlast.y;
    int bRlastDown = bRlast.y+bRlast.height;

    boolean leftRight = false, rightLeft=false, upDown=false, downUp=false;
    boolean betweenX = false, betweenY = false;

    if(bRnow.x>bRlast.x)leftRight=true;
    if(bRnow.x<bRlast.x)rightLeft=true;
    if(bRnow.y>bRlast.y)upDown=true;
    if(bRnow.y<bRlast.y)downUp=true;

    if(bRlastRight>tRleft && bRlastLeft<tRright) betweenX = true;
    if(bRlastDown>tRup && bRlastUp<tRdown) betweenY=true;

    if(leftRight)
        if((tRleft>bRnowLeft || tRleft>bRlastLeft) && tRleft<bRnowRight && betweenY)
        {
            b.setX(tR.x-bRnow.width - 1);
        }

    if(rightLeft)
        if((tRright<bRnowRight || tRright<bRlastRight) && tRright>bRnowLeft && betweenY)
        {
            b.setX(tR.x+tR.width + 1);
        }

    if(upDown)
        if((tRup>bRnowUp || tRup>bRlastUp) && tRup<bRnowDown && betweenX)
        {
            b.setY(tR.y-bRnow.height - 1);
        }

    if(downUp)
        if((tRdown<bRnowDown || tRdown<bRlastDown) && tRdown>bRnowUp && betweenX)
        {
            b.setY(tR.y+tR.height + 1);
        }
}

```

Its called bounce because its not really organized atm, i still have to think how to structure the algorithm so it becomes more generalized and pratical (Would appreciate help on that too)

This way of doing collision has one bug at the moment which is seen in image 3 (sorry for drawing circles, they are supposed to be squares) because FAST objects still pass diagonals :/ On the other hand, direct hits on walls are pretty neat.

How could i improve, optimize and organize this algorithm? Or is there any better algorithm and im just thinking too much for nothing?

# Answer
Your objects are moving so quickly that they can pass through walls. This is called *tunneling.* There are a couple ways to deal with tunneling. One way is to simply stop using small, fast objects. If you want to keep your fast objects, you might want to *reduce the timestep* of your physics simulation.

This means that rather than running your collision detection code 60 times a second (or whatever it currently is), you would run it much more frequently. This stops objects from passing through walls, and doesn't require you to write your own collision detection code.
> 1 votes

# Answer
You could use a swept volume, which is one of the common ways of dealing with this case.

A swept volume is what you get if you take an object's previous position and "sweep" its shape like a paint brush to its current position. In the example of your circle, the swept volume will be a single capsule. For rectangles the shape is a little more complex. For arbitrary polygonal shapes it's more complex still, of course.

Using this volume you can more easily test collisions. You can also find out where along the swept volume a collision first occurs and then figure out the time `t` of the collision to properly handle it.

Swept volumes do not work exceedingly well when you have rotating objects. There are significantly more intricate methods available that handle these, which you can research in more detail by searching for continuous collision detection.

A simpler alternative for particularly small objects (bullet fire) is to just use a raycast instead of full object-object collision detection. You'll want to ensure that you can do fast ray casts (or line segment casts more accurately, in some cases) as many elements in a game's physics must (or usually are) faked with such ray casts. A player character controller is often just a capsule for rough collision handling and a crap load of ray casts to handle the finer details.
> 1 votes

# Answer
My suggestion, choose a simple algorithm, like rectangle intersection, but with the following addition: remember your previous position. If difference between previous position and current is more than your sprite width, then divide that by your sprite width, or half your sprite width, and do your rectangle intersection in a loop, advancing that chosen distance each iteration in the same frame of simulation. This way you don't miss objects that are between your previous position and your current one even even if their are not wide enough to intersect your sprite in any of both positions.

You already realized the need to save the previous position, now you only need to divide your displacement in steps equal or less than your sprite width.

For a similar question I tried to illustrate what is my solution in ASCII in this other answer (Collision detection problems using AABB's). I think my writing could be a bit more efficient but I think It is understandable. Ignore the part about AABB as you already picked rectangle intersection.

Another solution, by brute force, reduce the time step between frames by and "absurd" number. For example, fix your fps at 200 or 400, probably only possible if you have your screen refreshes separated from your simulation. I don't know if you are already doing this, if not and you want to try it, this helped me a lot: http://gafferongames.com/game-physics/fix-your-timestep/
> 0 votes

---
Tags: java, collision-detection, algorithm
---


# Question
Title: Starter love2d physics program not working
I am starting out with my first love2d (using LöVE 0.8) physics program. I am just creating some ground/floor, a car body and attaching two wheels with revolute joints and setting the motors a-go.

However, the car stands still, whereas I expect it to move. Can someone glance over the code below and see what I am doing wrong?

***UPDATE*** See below!

```
function love.load()

  -- Set up world
  love.physics.setMeter(50)
  world = love.physics.newWorld(0, 9.81*50, true)

  -- Window dimensions
  windim = {height = love.graphics.getHeight(), width = love.graphics.getWidth()}

  objects = {}

  -- Ground/Floor
  objects.ground = {}
  objects.ground.body = love.physics.newBody(world, 300, windim.height)
  objects.ground.shape = love.physics.newRectangleShape(2000,20)
  objects.ground.fixture = love.physics.newFixture(objects.ground.body, objects.ground.shape)
  objects.ground.fixture:setFriction(3)

  -- Body of the car; a rectangle
  objects.carbody = {}
  objects.carbody.body = love.physics.newBody(world, 300, 500, "dynamic")
  objects.carbody.shape = love.physics.newRectangleShape(100,40)
  objects.carbody.fixture = love.physics.newFixture(objects.carbody.body, objects.carbody.shape)
  objects.carbody.fixture:setFriction(3)
  objects.carbody.fixture:setDensity(3)
  objects.carbody.fixture:setRestitution(0)

  -- First wheel
  objects.wheel = {}
  objects.wheel.body = love.physics.newBody(world, 330, 520, "dynamic")
  objects.wheel.shape = love.physics.newCircleShape(20)
  objects.wheel.fixture = love.physics.newFixture(objects.wheel.body, objects.wheel.shape)
  objects.wheel.fixture:setFriction(3)
  objects.wheel.fixture:setDensity(3)
  objects.wheel.fixture:setRestitution(0.6)

  -- Second wheel
  objects.wheel2 = {}
  objects.wheel2.body = love.physics.newBody(world, 270, 520, "dynamic")
  objects.wheel2.shape = love.physics.newCircleShape(20)
  objects.wheel2.fixture = love.physics.newFixture(objects.wheel2.body, objects.wheel2.shape)
  objects.wheel2.fixture:setFriction(3)
  objects.wheel2.fixture:setDensity(3)
  objects.wheel2.fixture:setRestitution(0.6)

  -- Create joint between car body and first wheel
  objects.carbody.wheeljoint1 = love.physics.newRevoluteJoint(objects.carbody.body, objects.wheel.body, 330, 520)
  objects.carbody.wheeljoint1:enableMotor()
  objects.carbody.wheeljoint1:setMaxMotorTorque(10000) -- Following example from http://www.emanueleferonato.com/2011/08/22/step-by-step-creation-of-a-box2d-cartruck-with-motors-and-shocks/

  -- Create joint between car body and second wheel
  objects.carbody.wheeljoint2 = love.physics.newRevoluteJoint(objects.carbody.body, objects.wheel2.body, 270, 520)
  objects.carbody.wheeljoint2:enableMotor()
  objects.carbody.wheeljoint2:setMaxMotorTorque(10000)

end

function love.update(dt)
  -- Set contstant speed for the wheels
  objects.carbody.wheeljoint1:setMotorSpeed(20)
  objects.carbody.wheeljoint2:setMotorSpeed(20)

  world:update(dt)

end

function love.draw()
  love.graphics.print(objects.carbody.wheeljoint1:getMotorSpeed(), 10, 10)

  -- Render ground
  love.graphics.setColor(72, 160, 14)
  love.graphics.polygon("fill", objects.ground.body:getWorldPoints(objects.ground.shape:getPoints()))

  -- Render car body
  love.graphics.setColor(72, 160, 200)
  love.graphics.polygon("fill", objects.carbody.body:getWorldPoints(objects.carbody.shape:getPoints()))

  -- Render wheels
  love.graphics.setColor(193, 47, 14)
  love.graphics.circle("line", objects.wheel.body:getX(), objects.wheel.body:getY(), objects.wheel.shape:getRadius())
  love.graphics.circle("line", objects.wheel2.body:getX(), objects.wheel2.body:getY(), objects.wheel2.shape:getRadius())
end

```

***UPDATE*** I added a line to print the angle of one of the wheels (see below). When this line is present, suddenly the car flips over from the wheels spinning when it hits the ground. This leads me to believe that something did not get initialized properly first time around.

This is the line added:

```
function love.draw()
  love.graphics.print(objects.wheel.body:getAngle(), 10, 10) -- Line added

```

# Answer
After playing around with this for a while, I finally discovered that my calls to `enableMotor` were wrong.

I was just saying

```
enableMotor()

```

when what it actually needed is

```
enableMotor(true)

```
> 2 votes

---
Tags: box2d, lua, love2d
---


# Question
Title: make turret move following the tank position
i'm starting my game assignment in XNA c#. I am making a 2d tank shooting game.

Now i trying to make my turret move together with my tank. My tank class "Has A" turret entity, and i'm drawing my turret in my tank class. Now i wanted to make my turret move with my tank. I'm passing in my tank position to my turret class (tank and turret is in different class), and update in my turret class, but my turret did not shows up when i build and run the game.

I attach my code below for anyone help that is kind to lend me a hand and point out where i got wrong.

My game code structure: sprite.cs - the main class player.cs and turret.cs - child class of sprite.cs game1.cs - the game class

Turret.cs

```
class Turret:Sprite
{
    //public Vector2 turretPosition, origin;
    //public Texture2D texture;
    //string textureName;
    Player player;

    public Turret()
    {}

    public Turret(Vector2 pos):
        base(pos)
    {
        //turretPosition = pos;
        this.textureName = "Turret";
    }

    public void updatePosition(Vector2 pos)
    {
        this.position.X += pos.X;
        this.position.Y += pos.Y;

    }

    public void init()
    {
        player = new Player(position);
    }

    public override void Update()
    {
        init();
        this.position.X += player.getPosition().X;
        this.position.Y += player.getPosition().Y;

        base.Update();
    }

}

```

}

player.cs(this is the tank class)

Player:Sprite {

```
    KeyboardState keyboard , prevKeyboard;
    float friction = 0.1f;
    public Turret turret;
    public Player(Vector2 pos)
        : base(pos)
    {
        position = pos;
        speed = 5;
        textureName = "Tank11";

        turret = new Turret(this.position);

    }

    public Vector2 getPosition()
    {
        return this.position;
    }

    public override void Update()
    {

        //REMEMBER TO CALL your turret.Update() here if u implemented override update function in turrent class.
        //update turret position;
       // turret.Update();

        keyboard = Keyboard.GetState();
        //origin = new Vector2(texture.Width / 2, texture.Height / 2);

        if(keyboard.IsKeyDown(Keys.A))
            rotation -= 0.1f ;
        if(keyboard.IsKeyDown(Keys.D))
            rotation += 0.1f ;
        if (keyboard.IsKeyDown(Keys.W))
        {
            velocity.X = (float)Math.Sin(rotation) * speed;
            velocity.Y = -(float)Math.Cos(rotation) * speed;
        }
        if (keyboard.IsKeyDown(Keys.S))
        {
            velocity.X = -(float)Math.Sin(rotation) * speed;
            velocity.Y = (float)Math.Cos(rotation) * speed;
        }
        else if (velocity != Vector2.Zero)
        {
            float i = velocity.X;
            float j = velocity.Y;

            velocity.X = i -= friction * i;
            velocity.Y = j -= friction * j;
        }

        position += velocity;

        prevKeyboard = keyboard;
        base.Update();
    }

    public override void LoadContent(ContentManager content)
    {
         turret.LoadContent(content);
         base.LoadContent(content);
    }

    public override void Draw(SpriteBatch spriteBatch)
    {

        var turretOffSet = new Vector2(0, 0);

        base.Draw(spriteBatch);
        turret.Draw(spriteBatch);
    }

}

```

Sprite.cs (the main class)

```
 Sprite
{
    protected Vector2 position, origin, velocity;
    protected Texture2D texture;
    protected float speed = 0.0f;
    protected float rotation = 0.0f;
    protected float scale = 1.0f;
    protected string textureName;

    public Sprite()
    { }

    public Sprite(Vector2 pos)
    {
        position = pos;
        speed = 0.0f;
        rotation = 0.0f;
    }

    public virtual void LoadContent(ContentManager content)
    {
        //textureName = name;
        texture = content.Load<Texture2D>("Image\\" + this.textureName);
    }

    public virtual void Draw(SpriteBatch spriteBatch)
    {
        Rectangle size;
        origin = new Vector2(texture.Width / 2, texture.Height / 2);

        spriteBatch.Draw(texture, position, null, Color.White, rotation, origin, scale, SpriteEffects.None, 0);
    }

    public virtual void Update()
    {

    }

    public void pushTo(float spd, float dir)
    {
        // XNA Client Space is in the opposite quadrant of the positive rotation quadrant
        float newX = -(float)Math.Cos(dir);
        float newY = -(float)Math.Sin(dir);

        position.X += spd * (float)newX;
        position.Y += spd * (float)newY;
    }
}

```

hope tat someone here who read it can point out where did i done wrong....

# Answer
> 1 votes
You seem to be calling init in your turret's Update method, which sets the player property to a new instance. I don't see how your turret instance knows about its tank instance in order to read the current position value.

```
public class Turret
{
    private Player player;

    public Turret(Player parent)
    {
        // Store a reference to the parent player instance
        this.player = parent;
    }

    public override void Update()
    {
        // Read current parent player position
        var p = player.Position;

        ...
    }

    ...
}

public class Player
{
    private Turret turret;

    // Allow turret to access the position of the player
    public Vector2 Position { get { return position; } }

    public Player()
    {
        // Pass reference to this parent instance into the new turret
        turret = new Turret(this);
    }
}

```

---
Tags: xna
---


title: Linking classes together

text:
# Question
Title: Linking classes together
My game is now getting to the point where I have alot of classes. Currently, I'm linking all those together through my MainGame Gamestate class. So in my MainGame class I have a Camera instance, a World instance, a Player instance etcetera. Now I know this is bad practise, as this is gonna get real dirty real quick.

What is the correct way of 'linking' loads and loads of classes and systems together?

For example:

In my MainGame class I have a GUI (own GUI library) defined called DebugMenu. Now in this menu I have an input field to change my FOV. When I click the button to update the FOV, the ClickButton event i called in the DebugMenu class which is inherited from the GUI class. To change the FOV I have to call camera.setFOV(40). This camera is an instance, so I need to find the instance that the system is using! That instance is declared in the MainGame class.

I'm using Java.

# Answer
There's nothing wrong with declaring instances of top-level components (like the `World` or `Player`) in your `Game` class. After all, they have to live somewhere.

To get those instance references to other interfaces, *pass them* as parameters to the other interfaces. For example, since it sounds like your GUI renderer needs to have a reference to the camera object so it can call `setFOV`, the GUI renderer should have a constructor:

```
GuiRenderer (Camera camera) {
    m_camera = camera;
}

```

This constructor takes a camera reference and stores it for later use.

In this fashion you make the dependencies of all your other components or subsystems very explicit, which improves readability and maintainability of those systems.
> 4 votes

---
Tags: java
---


# Question
Title: Graphics.drawImage will only fill a small portion of my control
I'm trying to create a map class for a simple 2D game. The map has an `array(100,100,5)` of `string`, returning the kind of tiles to draw ( with 5 possible layers from 0 to 4) players will move on the 2nd layer, the background of the game is on layer 0)

I'm want a `drawMap` sub that I would be able to call as needed. ( not the `onPaint` method, because I'm loading the game data map from a binary file, and this game contains the needed coordinates, number of tiles, etc and the array of tiles, so I need to load the map info 1st, then use the draw sub)

I'm struggling right now because only the Tiles(0 to 3, 0 to 1,0) are showing ... while my array is full of tiles !

Heres the code :

```
Public class Map
   inherits Panel

'... properties and stuff ....'

 Public Sub New(Optional ByVal mapName As String = "")

    G = Me.CreateGraphics()

    Me.BorderStyle = Windows.Forms.BorderStyle.Fixed3D
    Me.Location = New Point(250, 50)

    Load(mapName)

    Me.Width = mapSizeX * tileSize
    Me.Height = mapSizeY * tileSize

End Sub

Public Sub DrawGraphics(ByVal layer As Integer, ByVal g As System.Drawing.Graphics)
    For y As Integer = 0 To Map.mapSizeY - 1
        For x As Integer = 0 To Map.mapSizeX - 1
            If Not Map.Tile(x, y, layer) = "" Then
                GetSourceRect( x, y, layer, Map) 'return rectangle from my spritesheet '
                dRect = New Rectangle((x * tileSize), (y * Map.tileSize), tileSize, tileSize)
                g.DrawImage(SpriteSheet, dRect, sRect, GraphicsUnit.Pixel)
            End If

        Next
    Next
End Sub
end class

```

`Load(mapname)` deserializes a binary file containing the value for `mapSizeX` and `mapSizeY`, as well as `tileSize` and the `Tiles(100,100,5)` array all filled up.

What am I doing wrong at this point ?

# Answer
The answer was pretty simple, but took me a whole 2 days of reading forums ... the Paint event overrides the drawn image, cancelling/stopping it.
> 0 votes

---
Tags: 2d
---


# Question
Title: Good resources for learning modern OpenGL (3.0 or later)?
I stumble upon the search of a good resource to start with OpenGL (3.0 or later) . Well, I found a lot of books but none of them can be considered a good resource!

Here two examples:

**OpenGL Programming Guide (7th edition)** http://www.amazon.com/exec/obidos/ASIN/0321552628/khongrou-20 This is FULL of deprecated material! Almost every chapters begin with a note about that.

**OpenGL Superbible (5th Edition)** http://www.amazon.com/exec/obidos/ASIN/0321712617/khongrou-20 This book uses a library created by the author to explain the main arguments, hiding what you want to learn! I don't want to learn how to use your library! I want to learn OpenGL!

I hope that you understand this is not the same question like "hey I'm not able to use Google... tell me how to learn OpenGL". I've just finished a full and deep search but I can't find a good and complete resource to learn the "new" OpenGL avoiding deprecated topics.

Can someone heading me in the right direction? I know C++ and I have 10 years of experience in development... where I can find a good resource?! I want to spend time on it and I want to learn deeply.

# Answer
> 70 votes
I agree about the above books with a few notes:

* The OpenGL programming 8th guide is now out and has be redone for modern OpenGL 4.3.
* The SuperBible 5th ed, does provide you will a crutch library to start off but as you go through the book you reimplement the functionality of that library so by the end of it you should be fully versed. I also highly recommend wrapping OpenGL stuff in something if your using a object orientated language. I'm working on my own library for fun which seems to be the way to go, implementing it myself I understand all the ins and outs and I only need to put in the bits I actually use. Also you can abstract away some things like sending data to shaders (isn't shinyMaterial.setColor(Red) much nicer), this can also let you backport some stuff by providing legacy alternatives. There is also oglplus.

The main problem with learning modern 'core' OpenGL is that to get a basic pipeline up and running even if it's just to draw a cube you need to understand the following:

* Matrix operations (use GLM if you on C++, you will also need a MatrixStack OpenGL Unofficial SDK's version here, or my simple one here.)
* GLSL shader programming.
* binding data to shaders and Vertex Buffer Objects. If you wanted to learn just real pure core profile they would all need to be implemented simultaneously and if anything is broken you just wont see anything and have almost no clue where it went wrong. That also doesn't cover things like basic lighting (where you need to learn the shading algorithms in addition to the programming language).

But you don't need to start in the deepend with the core profile. Use *some* of the deprecated functionality at the beginning, just about everything will still support it, then modernize it.

Another issue is that 'modern' OpenGL can really refer to 3 things:

* The first one is the programmable shader pipline as opposed to the fixed function pipeline. The core 'modern' techniques have been possible since OpenGL 2.0 was released in 2004 when shaders where introduced (the tutorials just didn't get updated) also 1.5 had Vertex Buffer Objects's which are another cornerstone of modern OpenGL. A problem is that even today OpenGL developers might not even be able to take advantage of all that stuff, there are plenty of crappy netbooks out there with those Intel chipsets that only support OpenGL 1.5 and phones such as older iPhones/Android ones that only support OpenGL ES 1.1. The only real difference between this stuff in OpenGL 2.0 and OpenGL 3.x/4.x is it's now mandatory for the core profile.
* Modern OpenGL could also refer to the new stuff that's in 3.x, 4.x. Things like Vertex Array Objects, Framebuffer Objects, Uniform Buffer Objects/std140, layout qualifiers, GLSL subroutines and so on. Many of those I have found can make things much much nicer to program with. They can also subtly change your overall engine pipelines. They are also things that with a little effort you can backport by making helper functions and so on (For example write a generic shader manager object that you can use to set uniforms, if UBOs are supported use that otherwise manage uploading the values to shaders manually, maybe put a little shader rewriting stuff in there to automate it). This stuff only runs on new video cards, you wont see any netbooks supporting it or any current generation video game consoles (they use their own subset of OpenGL similar to OpenGL ES). The latest OSX only have 3.2 support and I understand that they will be fixed at this version forever since Apple write their graphics drivers and specify OpenGL versions based on the OS version not the GFX drivers/video card capabilities the only way for a user to get a new OpenGL on a current generation Mac would be to pay for an upgrade to a new version of OSX.
* The Ultra Modern nextgen OpenGL. OpenGL 4.3 was just released. It comes with compute shaders, glMultiDrawElementsIndirect and shader storage buffers. This allows for a fundamentally different pipeline where you upload all the vertex data to the GPU and then use compute shaders to calculate what should be drawn rather than doing it in your program. Unfortunately this is very new so I don't know of any decent tutorials on it. Take a look at the OpenGL 4.3 review which gives an outline of how this works (also the author says there is a GPU Pro article to be released explaining it). Being brand new it's not going to be supported anywhere at this stage (unless you're on a newer nvidia card with beta drivers). Although you might be able to use OpenCL/CUDA to implement some of it.

I would skip glBegin, glEnd, glVertex\*, glNormal\*, glTextCoord\*, glTranslate\*, glRotate\*, glLoadIdenity, glModelViewMatrix and so on. Instead start with learning Vertex Buffer Objects without shaders, don't try 3D at this point just a flat white triangle so you don't have to work with 3d operations using matrices (as you will need to learn to bind them to shaders soon so no sense in learning to old way). Next add in in the shaders, you will need to change how your vertex buffer objects are bound since you will now want to use vertex attributes. Learn how to communicate properties to them via uniforms. Then learn matrix operations with GLM, bind the matrices to the shaders and get 3D going. Once you have that done then it's basically just learning more advanced things like texturing, lighting and some special features like framebuffer objects, vertex array objects, uniform buffer objects, GLSL routines and so on (those are all things I recommend you have a look at. Most of it is fairly new except for texturing and lighting but if you learn them as shader concepts rather than as OpenGL ones, you should get the modern approach).

Some general online modern OpenGL tutorials, covering the shader programming pipeline that most of which works with OpenGL 2.0+:

For other general learning resources. OpenGL ES might be a good starting point. OpenGL ES has stripped out all the deprecated stuff. OpenGL 4.1 has full compatibility with OpenGL ES so it should be possible to take an OpenGL ES program and run it in OpenGL 4.1. And the basic principles are the same for both.

Some things to note is that OpenGL ES 3.0 has just been released but as it's new, it won't have any tutorials or hardware support yet. It doesn't seem to have any major fundamental changes (like the difference between fixed pipeline and shader model that we saw with OpenGL ES 1.0-\>2.0). So you probably won't be learning any out of date stuff.

Also, OpenGL ES will often be using EGL so you will need to learn another way to open a Window but that shouldn't be too hard. Otherwise there are a few OpenGL ES wrappers/emulators around or you can learn on Android/iPhone if you have one (or look at using their emulators).

There is the Addison Wesley OpenGL ES 2.0 Programming Guide which is the equivalent of the red book.

You can also look at GLSL shader focused stuff since that's where most of modern OpenGL lives. You just need to ensure what you learn covers the OpenGL binding 'glue' side of things.

Check out the OpenGL Shading Language 2nd edition (Orange Book).

The OpenGL 4.0 Shading Language Cookbook covers some more bleeding edge OpenGL stuff but isn't itself a comprehensive tutorial. Its definitely worth a look to get some understanding in the latest real world OpenGL practices such as uniform buffer objects and GLSL subroutines.

Finally you could have a look at WebGL, although being in JavaScript that is going to be somewhat different and much harder to debug.

# Answer
> 15 votes
Forget about books at least until the 8th edition of the programming guide comes out.

Besides the mentioned tutorial, I found this site to be helpful, since it goes past the basics fairly quickly. They're both a great introduction to modern OpenGL. Once you get past that, you'll only need the documentation, OpenGL is easy to use once you get used to it. The rest is computer graphics theory and mathematics.

# Answer
> 11 votes
I have been in the exact same situation as you and have finally found what I needed to get going.

First off head here: http://www.arcsynthesis.org/gltut/. This site is fantastic, good working examples and deep explanation of what is going on. Even though the code is written in C++ I'm using this to teach me writing OpenGL demos in Lisp. It also is totally free of the old way of doing things so you don't have to worry about picking up bad habits.

I would stress that even though its 'just another website' I haven't found any books which give as clean and concise an explanation of the basics as this does.

Once you have got through the site above you will already have a basic grasp of shaders and a lot of what you need to know can now be googled (have a good look at the opengl es or webgl resources as they removed all the deprecated stuff) or found in the opengl wiki site. The later is horrendously cryptic if you don't have the fundamentals from the arcsynthesis site under your belt but quite helpful when you know roughly what you are looking for.

Also for a really deep look at GLSL then have a gander at: OpenGL Shader Language (The Orange Book) I'm working through this very slowly but will give you the understanding of writing shaders to allow you to take this pursuit on further. I'll warn you that this book does have, in the words of a reviewer, "200 pages of top quality content packed into a 600 page book" but the extra history and info can provide the context you need to understand the routes that OpenGL as a standard has gone down (well it's helping me anyway!)

I hope this helps and best of luck, I look forward to seeing/playing your work in the future!

# UPDATE

It seems arcsynthesis is sadly offline, however the site has been converted to pdf here and the code has been mirrored over here.

Also in the few years since my original answer learnopengl.com/ has become absolutely brilliant. Whilst I still recommend arcsynthesis for the raw excellence of its introduction to modern opengl, the learnopengl site covers far more that arcsysthesis did, and manages it with approachable language, we crafted examples and open source code. Basically, it's damn good, go check it out!

With regard to books I didnt get too far with the orange book but can recommend the third edition of 'Real-Time Rendering'. Once you are ready for the technical stuff, this book is a goldmine.

# Answer
> 8 votes
Also check out Open.gl. It has tutorials using modern Open GL

# Answer
> 5 votes
Two sites that have been very helpful for me are: http://www.arcsynthesis.org/gltut/ and http://ogldev.atspace.co.uk/

Also, the OpenGL wiki is an extremely good and up-to-date resource.

Once you get through these, I highly recommend biting the bullet and reading the OpenGL specification. Then you'll be a pro.

# Answer
> 4 votes
The best book I've come across that covers "modern" OpenGL is http://www.packtpub.com/opengl-4-0-shading-language-cookbook/book

Even though it's a "cookbook", it does walk you through necessary steps to set up rendering and what kinds of companion libraries you'll need (image lib, vector math lib).

In addition to that it goes through all sorts of common things you might want to use OpenGL for, without digging too deeply into anything (like for shadows, it covers shadow mapping and filtering shadow maps, but doesn't go into any of the more complex shadow mapping methods).

I also recommend getting the orange book.

# Answer
> 4 votes
Some more Tutorials and stuff which wasn't mentioned but helpful

---
Tags: opengl, assets
---


title: Automated texture mapping

text:
# Question
Title: Automated texture mapping
I have a set of seamless tiling textures. I want to be able to take an arbitrary model and create a UV map with these properties:

* No stretching (all textures tile appropriately so there is no stretching and sheering of the texture)
* The textures display on the correct axis relative to the model it's mapping to (if you look at the example, you can see some of the letters on the front are tilted, the y axis of the texture should be matching up with the y axis of the object. Some other faces have upside down letters too)
* the texture is as continuous as possible on the surface of the model (if two faces are adjacent, the texture continues on the adjacent face where it left off)
* the model is closed (all faces are completely enclosed by other faces)

A few notes. This mapping will occur before triangulation. I realize there are ways to do this by hand and it's probably a hard problem to automatically map textures in general, but since these textures are seamless and I just need uniform coverage it seems like an easier problem. I'm looking for an algorithmic approach to this that I can apply in general, not a tool that does it.

What approach would work for this, is there an existing one? (I assume so)

# Answer
> 8 votes
Texture mapping is a hard problem. For some primitives there is a mathematically sound way of finding the UV coordinates. This is only possible if we can think of a function `F(u,v)->(x,y,z)`. An example of a figure where this is possible is the a cube. Here we can easily cut out a square for each of the surfaces.

For a sphere this is also possible, here we can use the UV coordinates as latitude and longitude.

The function for the cube is perfectly linear, however the sphere is already more of a problem and for even more complex models there doesn't exist such an easy function.

Luckily in texture mapping we can use an easy primitive, like the cube or sphere. To map their easy function onto the harder to describe surface of the model:

Of course this will not give a perfect effect:

There are multiple techniques for mapping the simple texture coordinates onto a harder model:

* You can use the normal of the complex model to map to the texture coordinate on the primitive. But this can lead to radical behavior for complex models.

* You can spread out from the center to the primitive, this gives a more linear distribution of texture coordinates.

* Or you can cast rays spread out from the viewport/camera to the model and try to map the texture from the intersection point on the primitive to the intersection point of the complex model.

I can't think of one perfect way to do what you want, simply because there is no way to come up with a function that describes every surface perfectly. The best bet for you is to find a primitive that matches your complex model as close as possible or to create a complex model yourself, do manual UV mapping and then use that with the techniques described above as a primitive source for texture coordinates that you can map on other complex models.

# Answer
> 0 votes
This doesn't answer the question but why do you use texture mapping and not Procedural materials?

Procedural materials do have these advantages

* the object looks as if it were carved out of real material (stone, wood, ...)
* details can be calculated without the need for more memory
* no UV map calculation necesary

---
Tags: textures, uv-mapping
---


title: Smoothing the scrolling path in 2D

text:
# Question
Title: Smoothing the scrolling path in 2D
I have the following problem:

In a 2D game the screen can scroll in any of the 4 directions. Basically, the center of the screen during scrolling moves from (x1,y1) to (x2, y2) whereby (x1,y1) is the current focus and (x2, y2) is the desired focus. The latter changes frequently depending on what happens in the game.

At the moment, I only scroll if the distance d between (x1,y1) and (x2, y2) is above a certain threshold and also I am scrolling the faster the larger d is.

This already results in a quite smooth movement of the screen but I am still not completely happy with it. I was wondering if there are any standard or best-practice approaches to the problem of smoothing the path of the screen? I can imagine something with b-splines but I have no concrete idea of how to approach this.

# Answer
While this question is a little abstract, I can share a few tips/realizations I've had over the years.

First, 'smooth' normally means 'more continuous derivatives.' If you are moving at speed X, you are all good. your position is v\*t (continuous), the derivative of that is v (continuous), and all derivatives of that are 0 (continuous). However, if you suddenly stop at time T, your position is v\*t -\> v\*T (continuous), but your speed is X -\> 0 (discontinuous at T). So maybe to solve this you 'slow down' when close to T rather than coming to an immediate stop.

Some other side notes - the 'farther away' the motion is from the player, the more tolerant they'll be of these discontinuities. Closest: camera, next: avatar, farther: enemies/ais. A super rough guideline - the camera likes to have inf continuous derivatives, the avatar can survive w/ continuous movement and velocity (but then have instant acceleration, but continuous acceleration is better - that's why analog controller input 'feels' better than digital or keypresses), enemies can be a lot crazier.

Ok, now let's analyze your situation.

```
pos = if (d > D) pos
      else (pos + f(d));

```

So, let's analyze where the discontinuities could be.

The first obvious point is d = D, where we switch from moving to not moving. What cases would this be continuous and what cases would this be discontinuous? So on one side pos is constant and the velocity == 0, so on the otherside we need our velocity to approach 0 as d -\> D. Ok, what's the simplest function that does that? What about f(d) = 0, hah! Of course this works, but that just means the camera never moves! Ok, next simplest function f(d) = k. Now we get there, but definately have a discontinuity at D == d. Ok, next simplest: f(d) = k * d. That has some nice features that we'll get to in a sec but immediately we notice that k\*d is non-zero for any D != 0. But we can fix that by subtracting out a D: f(d) = k * (d - D). Now f(d) = 0 when d == D.

Awesome, now we are continuous across d, what about when d \> D? Then we are strictly in the case

```
x = x + k(D-d)

```

where x is the camera position. Taking the derivative (using the notation x' := the derivative of x)

```
x' = k(D-d)

```

cool, and noting that d is a function of x (the camera position) and P the focus position

```
x' = k(D - (x - P))

```

interesting, we have a first order differential equation, which i'll skip the hairy details but that means the solution is in the form

```
f(x) = A * exp(B(x - C))

```

which is pretty neat because exp(...) has infinite continuous derivatives - exactly what we are looking for (and probably why you settled on that scheme in the first place!)

So that's pretty awesome! But you can go deeper and deeper. Note that this is the case for the focus position P being constant - what happens when the focus changes/is moving? Is that a function of analog stick position? A binary function of a key being pressed? A cut in a cutscene? And so on. By unrolling the complexity of what's driving your motion and understanding what is actually causing what to happen, you can add and adjust constants and factors and functions, normally in the service of 'smoothness' (but sometimes for other reasons like 'keep the player on screen' or 'avoid ringing' or 'avoid framerate dependance') to achieve enjoyable results.
> 1 votes

---
Tags: xna, 2d, xna-4.0, side-scroller
---


# Question
Title: Mobu: Motion Files Naming Scheme for Unity
When exporting takes as several fbx files in Motionbuilder 2014 with **File \> Motion File Export...**, the files are named like so:

> file\_Take1.fbx
>
> file\_Take2.fbx
>
> file\_Take3.fbx

In order for the motion files to be loaded into Unity correctly, I have to rename them to:

> file@Take1.fbx
>
> file@Take2.fbx
>
> file@Take3.fbx

Having to replace underscores with '@' is fine for small projects but can become time consuming when working with many takes in large projects.

Is there a way to change the default naming scheme in Motionbuilder, through preferences or python scripting, so that the default underscore is replaced with an '@'?

# Answer
I managed to write a solution after some python experimentation. To get this to work, save the code into a python file (.py), drop the file into Motionbuilder, and click execute.

Here's the code if you're interested:

```
from pyfbsdk import *
import os

#save default name here for quick execution
dName = "Untitled.fbx"

lSystem = FBSystem()
lApplication = FBApplication()

lFileName = lApplication.FBXFileName

FileDlg = FBFilePopup()
FileDlg.Style = FBFilePopupStyle.kFBFilePopupSave
FileDlg.Caption = "Saving Motion Files"
FileDlg.FileName = dName
FileDlg.Filter = "*.fbx"

if FileDlg.Execute():
    mSuccess = True
    lOptions = FBFbxOptions(False)
    lOriginalTake = lSystem.CurrentTake

    lFileNameText = os.path.splitext(FileDlg.FileName)[0];
    lFileNameExt = os.path.splitext(FileDlg.FileName)[1]

    for lTake in lSystem.Scene.Takes:
        lSystem.CurrentTake = lTake
        lFullFileName = FileDlg.Path + '\\' +  lFileNameText + '@' + lTake.Name + lFileNameExt;

        if lApplication.FileExport(lFullFileName) == False:
            mSuccess = False
            print lFullFileName + " Failed...";
        else:
            print lFullFileName + " OK!";

    lSystem.CurrentTake = lOriginalTake

    if mSuccess:
        print "Export successful!"
    else:
        print "Export failed."
else:
    print "Export canceled."

```
> 1 votes

---
Tags: unity, python
---