Showing posts with label Box2D. Show all posts
Showing posts with label Box2D. Show all posts

Thursday, July 12, 2012

Citrus Engine on Nape and physics performance improvement

Hi folks! Since my studies are over and my new portfolio online, I have time to focus on personal projects. Yep, it was time to contribute again to the Citrus Engine. I’ve worked 3 days at full time focusing on its big issue : mobile performances. I’m glad to say that now they are just an old memories!
6 months ago, I’ve made the CE compatible with Stage3D thanks to Starling and added some cool stuff. CitrusEngineV3 BETA 1 has been downloaded 3047 in 6 months, that’s not bad! However it didn’t see lots of Stage3D game, because it was missing the point : people wants to make mobile games.
You will find all the sources at the end.
Nape
Nape is Luca Deltodesco‘s open-source physics engine written in haXe with the help of his preprocessor caXe. It is written with AVM2 in mind for performance, and utilising another part of his build chain provides a seamless API between AS3 and haXe though it does compile with hxcpp with other targets unknown. The idea behind Nape is to provide a high-performance, powerful and moreover friendly and safe physics engine.
Nape is faster than Box2D, and easier to handle. Adding it in the CE wasn’t hard, and we use it the same way than Box2D. Using Box2D (Alchemy version) & Stage3D with Starling in the CE you must take a look on Adobe Flash Player Premium announcement if you are targetting Browser games. With Nape, you are no more related to the “premium features license” from Adobe.
Nape is ready to be use (no bug spotted!), however since I’m really new to Nape, there are some strange behavior whith NapePhysicsObject in the CE (you can see it in this demo). It’s not a problem for a performance test.
A NapeStarlingGameState Class exemple :
[...] Read more: Citrus Engine on Nape and physics performance improvement

Wednesday, March 28, 2012

Simulate radial gravity (also known as “planet gravity”) with Box2D as seen on Angry Birds Space

With the launch of Angry Birds Space I am sure you are wondering how to simulate planet gravity with Box2D.

And guess what… the basics are very easy.
First, in space there’s no gravity, so you will create a b2World world without gravity this way: [...]
Read more: Simulate radial gravity (also known as “planet gravity”) with Box2D as seen on Angry Birds Space

Friday, March 23, 2012

Creation of a rotating room with Flash and Box2D

I was thinking about a game concept which features physics and a rotating room, so I asked to myself how to make a rotating room with Box2D, and what is the best way to do it. These are the three ways I tried. 1 – “Manually” rotating a static room In my first attempt I built a static room with a compound object (see the theory of compound objects in this post), then I rotated the object at every frame. This is the source code: [...]
Read more: Creation of a rotating room with Flash and Box2D

Thursday, February 23, 2012

Building An Elevator in Box2D

Introduction

It took me 4 days to build an Elevator via Box2D in Corona SDK. I wrote the actual code and API for it in about 30 minutes. Getting the physics to work proved way more challenging than I anticipated. I’m still learning the ins and outs of Box2D as it relates to game development, so wanted to report on how I went about it and what I learned.

The following article talks about how I’m using Box2D in my game, the 4 approaches I took to building an elevator, and what I eventually decided upon.

Please keep in mind some of the things below are related to Corona SDK’s implementation of Box2D. Thus, some of the issues and compensation measures I took may not need to be done, nor happen, in other implementations and platforms.

Why An Elevator?

Elevators provide an interesting transition in both games and movies. They also provide easier ways for game developers to unload and load a level, provide a rest for the player, and/or make it easy to provide cut scene dialogue to prepare for the player for an upcoming part. In a lot of horror movies, they actually are the focal point of a lot of scary scenes such as Resident Evil, and also provide a perfect setting for comedic relief such as such as Spiderman 2 and Deep Rising (good ole Ipanema).

One of my favorite easter eggs was from Max Payne was in an elevator. You walk into a shoddy NYC apartment building elevator alone, with the notorious off-kilter 3rd person camera. Combined with the absurd brightness in the elevator’s interior amongst a very noir game, the tell tale “elevator muzak” is playing. If you shoot the overhead speaker, Max utters a smirk filled, 2nd word annunciated “Thank you!“.

Romance, fear, death. In such a confined space clearly only meant for short periods of stay, elevators can force us to view the human condition ever more clearly. Many writers play up the claustrophobia aspect, the lack of control as a metaphor for life taking us where it wills to, or preying on our fear of the unknown when you hear bad things just outside the lift walls.

It also helps players in games get from one floor to another in a controlled manner. Kind of like they do in the real world.

How Does Mine Need to Work?

A game I’m building requires that a character inside a building go up a floor in the building he is in. It’s based on a Brooklyn apartment building that has 13 floors with 12 ft ceilings. The character is on the 12th floor and needs to use the standard elevator. It has a call switch on the outside. You press a button and the elevator will arrive at the floor the button was pressed. You can optionally walk into the elevator and press the up or down buttons for the same effect. The elevator does not move on it’s own, only when a button is pressed. It currently only operates on 2 floors.

Simple, right? Code wise, it was. Here’s the Lua class on Github. The only thing to really note is the goUp, goDown, and tick functions. The goUp and goDown simply set flags so the elevator knows where to go. The tick function handles the actual movement via the game loop. Distance joints, which I’ll cover in a minute, are not powered by motors, so I just increment or decrement the length to move it up or down.

Brief On Box2D

Read more: Building An Elevator in Box2D

Friday, December 9, 2011

Create REAL explosions with Box2D

Look at the title… Create REAL explosions with Box2D… keyword: REAL.

This means we will make a Box2D explode into pieces using the basics of Slicing, splitting and cutting objects with Box2D. At the moment it’s just a prototype but it does not need that much optimization.

That’s what we’ll get:

Click the mouse to make the box explode.

Too fast? Get this slow motion example:

As you can see, this is a real explosion.

This is the source code, can you discover how was it possible?

Read more: Create REAL explosions with Box2D

Friday, October 21, 2011

Develop a Flash game like Angry Birds using Box2D – Killing the pigs

Do you know why Angry Birds had such as a worldwide success? Because people love to kill pigs in videogames.

I got sick when I saw Babe movie and I want to kill pigs since then.

Today, you will learn how to do it thanks to the second part of the Angry Birds tutorial.

Before we start, let me explain how we are going to kill them. A pig dies when something, including the bird, the objects in the game, and even the ground, hits it too hard.

Various objects in the game also break when they hit something too hard.

You are already able to see when two objects collide thanks to tutorials like Create a Flash prototype of The Moops – Combos of Joy, but we’ve never seen how to determine the force of the collision.

You still have to create a custom contact listener class, but rather than using BeginContact function which just has an argument we can use to determine which objects collided, we will use PostSolve, which has another argument, a b2ContactImpulse variable.

With b2ContactImpulse we can know the amount of impulse Box2D has to give to bodies to avoid them from penetrating each other due to the collision. In other words, the collision force.

Once we know the strength of the collision, we can compare it with the maximum strength allowed before an object breaks (which can also be different according to the material, such as glass, wood, stone) and if the collision will break the object, we simply remove it from the Box2D world, and then we’ll show a cute animation.

This is what I made with this concept:

Throw the pigeon to the castle on the right to see how all blocks (and the pig) which are hit hard get destroyed.

In this prototype, world boundaries and the bird itself can’t be destroyed.

This is the Main class [...]

Read more: Develop a Flash game like Angry Birds using Box2D – Killing the pigs

Sunday, September 11, 2011

quickb2 – Box2D for Flash games

quickb2 – Box2D for Flash games

QuickB2 is a complete abstraction of Box2D, providing grouped hierarchies, extensible classes, and event-driven callbacks. The high-level interface enables developers to create physics simulations that are impractical to write using Box2D’s API alone. It takes care of things that you don’t want to, so that you can concentrate on your game.

Here are some examples of what it can do: http://quickb2.dougkoellmer.com/bin/qb2DemoReel.swf

Here is a place where you can ask questions: http://quickb2.dougkoellmer.com/forum

I’ve just gone and looked through the demo reel, and I have to say this is quite impressive. Obviously having a nicer to use, ActionScript 3 style syntax rather than the C++ syntax is a bonus, but what really makes this cool is the features that this library has, over and above the basics of Box2D.  Things like shape cutting, soft bodies; breakable joints etcetera.

You can find out more information, and download the source code from Google Code, at: http://code.google.com/p/quickb2/

quickb2 – Box2D for Flash games.

Saturday, August 27, 2011

Create a terrain like the one in Tiny Wings with Flash and Box2D – adding textures

If you are following the series about the creation of a Tiny Wings-like terrain, you should know one of the most popular requests once I placed a car running on the hills was how to get rid of the debug draw graphics and use your own textures.

First, you need a seamless texture, or a texture without seam at least horizontally. I suggest you to pick a texture of the same length of the hills (640 pixels in this case) or a texture which width divides the lenght of the hills.

I used a rock texture taken from 40 watt.

Then, as soon as you place the polygons representing the hill slices, you also have to draw on a sprite the same shape you are giving your hill.

This will act as a mask for your seamless texture. And obviously remember to remove both the mask and the texture when they leave the screen to the left side.

This is what you will get:

Use UP and DOWN arrow keys to control the cart, and LEFT/RIGHT to balance it while in the air.

This is the fully commented source code: [...]

Read more: Create a terrain like the one in Tiny Wings with Flash and Box2D – adding textures

Monday, July 4, 2011

Slicing, splitting and cutting objects with Box2D – part 3: cutting your own Sprites

In the second part of this series I showed you how to cut Box2D objects.

Unfortunately I was working in the debug draw environment, so the whole process can’t be applied in a real-world example, unless you want to publish a game with the debug draw graphics.

So it’s time to see how to cut your own sprites. This is what you’ll get at the end of this step:

Cut the debug draw polygons to see randomly colored debris fall down. These debris are Sprites generated in real time.

So let’s take a look at the source code, and see what changed since the previous step[...]

Slicing, splitting and cutting objects with Box2D – part 3: cutting your own Sprites

Thursday, June 16, 2011

How to create a Flash platformer using Citrus Engine

More than a year ago I shows you how to create a little game prototype using Citrus Engine.

A year has passed, and now Citrus Engine is back with version 2.0 which promises to let us create complex games in a quick.

For all you specs maniacs, here it is a brief list of features:

* Blazing 50 FPS in the browser on current machines, and 250+ FPS on the desktop (or Adobe AIR).
* Integrated with Box2D physics, which allows for tumbling crates, pulleys, vehicles, and just about anything else you can imagine, without the limitations of a grid.
* Supports multiple rendering methods with very little code. Like blitting and sprite sheets? Citrus Engine’s got it. Prefer animating using the timeline? No problem.
* Hijack the Flash IDE and use it as a level editor, for easily laying out and iterating on level designs.
* Robust documentation includes and ASDoc API, tutorial videos, and a forum.
* Standards-based code API means developers and designers spend more time tweaking the fun stuff, and less time debugging.
* Level-based progressive downloading allows gamers to start playing the game quicker by only downloading what the next level needs.
* Pre-made commonly used objects, like a hero, coins, enemy, platforms, clouds, and more!
* Easily use embedded or dynamic graphics.
* Decoupled architecture allows for custom rendering methods, like blitting or 3D.
* Sound management
* Keyboard and input management
* Built-in particle system
* Intuitive Signals event framework

Ok, the boring part is over. Now take this little prototype I made in 20 minutes (yes, 20 minutes):

Look at what we have:

* The hero (on the bottom right)
* A pushable crate (on the bottom left)
* Some platforms around the stage
* A moving platform
* An enemy (on the upper right corner)
* A coin (on the upper right corner)

Move the hero with LEFT and RIGHT and jump with SPACE. Try to grab the coin. See what happens if you touch the enemy. The game mechanics are complex enough to represent a level of a good platformer. But it took me only a few lines to do it.

This is the main class [...]

Read more: How to create a Flash platformer using Citrus Engine

Thursday, June 2, 2011

Introduction to Box2D for Flash and AS3

Box2D is a popular physics engine with a solid Flash port, which was used to create the excellent game Fantastic Contraption. In this tutorial, the first of a series, you’ll get to grips with the basics of Box2D 2.1a for Flash and AS3.


Step 1: The Boring Setup

I’m going to assume you already know how to set up a basic Flash project using your editor and workflow of choice, whether that means creating a FLA with a document class, a pure AS3 project in a different editor, or whatever. I’m using FlashDevelop, but you should use whatever you feel comfortable with.

Create your project, and name the main class Main.as. Give it some boilerplate code; mine looks like this:

package
{
 import flash.display.Sprite;
 import flash.events.Event;

 [Frame(factoryClass="Preloader")]
 public class Main extends Sprite
 {

  public function Main():void
  {
   if (stage) init();
   else addEventListener(Event.ADDED_TO_STAGE, init);
  }

  private function init(e:Event = null):void
  {
   removeEventListener(Event.ADDED_TO_STAGE, init);
   getStarted();
  }

  private function getStarted():void
  {

  }

 }

}

Don’t worry about the [Frame] metatag — that’s just how FlashDevelop creates a preloader. All you need to know is that getStarted() is run when the SWF has fully loaded. Create a function of the same name that runs when your Main class has loaded.

I’m also going to assume you’re comfortable with using a separate library or API in your project. Download Box2DFlash 2.1a from this page (I’m using the Flash 9 version), and extract the zip to wherever you normally put your APIs. Next, add a classpath to point to the \Source\ folder from the zip. Alternatively, you could just extract the contents of the \Source\ folder to the same directory as your Main class.

Great! That was easy. Let’s start using Box2D.


Step 2: A Whole New b2World

“If you want to make an apple pie from scratch, you must first create the universe,” wrote Carl Sagan; if we want to make a few physics objects, we only need to create a world.

In Box2D, a world is not a planet or an ecosystem; it’s just the name given for the object that manages the overall physics simulation. It also sets the strength of gravity — not just how quickly objects accelerate but also in which direction they fall.

We’ll create a vector to set the gravity before creating the world itself:

import Box2D.Common.Math.b2Vec2;

//...

private function getStarted():void
{
 var gravity:b2Vec2 = new b2Vec2(0, 10);
}

A b2Vec2 is a Box2D Euclidean vector (the second 2 stands for 2D again, because it’s possible to have a 3D Euclidean vector). Daniel Sidhion wrote an excellent tutorial explaining what Euclidean vectors are (they are nothing to do with the Vector class in AS3), so check that out if you’re not sure. But briefly, think of a Euclidean vector as an arrow:

This arrow shows b2Vec2(4, 9); it points down and to the right. Our gravity vector, then, will point straight down. The longer the arrow, the stronger the gravity, so later on in the tutorial you could try changing the gravity vector to b2Vec(0, 2) to simulate a much weaker gravity, much like that on the Moon.

Now we’ll create the world itself:

import Box2D.Dynamics.b2World;

//...

public var world:b2World;

//...

private function getStarted():void
{
 var gravity:b2Vec2 = new b2Vec2(0, 10);
 world = new b2World(gravity, true);
}

The second parameter we pass to b2World() tells it that it can stop simulating objects that it doesn’t need to simulate any more, which helps speed up the simulation but is completely irrelevant to us at the moment.

Run the SWF to check there are no errors. You won’t be able to see anything yet, though. The world is currently completely empty!


Step 3: Reinvent the Wheel

Let’s create a simple circular object; this could represent a rock, a basketball, or a potato, but I’m going to see it as a wheel [...]

Read more: Introduction to Box2D for Flash and AS3

Monday, May 30, 2011

QuickB2

QuickB2 is a complete abstraction of Box2D, providing grouped hierarchies, extensible classes, and event-driven callbacks. The high-level interface enables developers to create physics simulations that are impractical to write using Box2D’s API alone.

Some features:

  • Soft-bodies.
  • Top-down car physics.
  • Friction in z-direction (top-down friction).
  • Event-driven through revent.
  • Retain mode that doesn’t require destroying/remaking objects.
  • Extensible architecture.
  • Nested hierarchy system similar to Flash’s display hierarchies.
  • Cloneable objects.
  • Highly customizable immediate-mode rendering for both debug and production purposes.
  • Hooks for integration with any typical retain-mode-type rendering engine (e.g. the Flash display list).
  • Various debugging tools including visualizations, mouse dragging, warnings, notifications, asserts, exceptions, and runtime GUIs.
  • Pixel-based units.
  • AABB and circular bounding representations.
  • Easy low-level access to Box2D API in case of emergency.
  • Large suite of “stock” functions and classes to address common needs.
  • Individual polygons may be concave and have any number of vertices.
  • All kinds of joints, including built-in spring joints.
  • Physics world is completely changeable within contact callbacks.
  • WYSIWYG editing environment for Flash CS5.
  • Built-in system for handling your game loop and time steps.
  • Easy API for beginners – lower-level optimizations and tricks available for advanced users.
Read more: QuickB2

Thursday, May 5, 2011

Flash physics draw game with a car using QuickB2

QuickB2 is a complete abstraction of Box2D, providing grouped hierarchies, extensible classes, and event-driven callbacks.

The high-level interface enables developers to create physics simulations that are impractical to write using Box2D’s API alone.

It takes care of things that you don’t want to, so that you can concentrate on your game.

Among its top features we can find:

* Soft-bodies.
* Top-down car physics.
* Friction in z-direction (top-down friction).
* Pixel-based units.
* Individual polygons may be concave and have any number of vertices.
* All kinds of joints, including built-in spring joints.
* WYSIWYG editing environment for Flash CS5.

Combining one of the official examples with the drawing concept introduced during the creation of Way of an Idea Box2D prototype I ended up with this script [...]

Read more: Flash physics draw game with a car using QuickB2

Friday, March 18, 2011

Create a Flash prototype of The Moops – Combos of Joy

Create a Flash prototype of The Moops – Combos of Joy:

Did you play The Moops – Combos of Joy?

It’s a cute physics game we can build a prototype in a few minutes (don’t worry, Plants Vs Zombies fans, as next step is about to come).

Moops – Combos of Joy screenshot

Let’s see game’s features:

* It’s a physics game so we are using Box2D to create it.

* The player fires a ball with the mouse. The direction can be decided according to mouse position, but power can’t. Player fires balls with the same, predefined speed.

* A series of shapes “fall” down from the top of the stage. Actually they don’t fall because there is no gravity in the game. Let’s say they move from top to bottom at a constant speed.

* When the ball hits a square, the square reacts according to physics, changing its direction and speed, but the ball does not exactly follow physics rules as its speed never changes.

Obviously there are more features in the original game but at the moment we’ll see these ones. Since it’s a long time we don’t deal with Box2D, I am using a line by line approach to explain the code.

This is the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package {
 import flash.display.Sprite;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import flash.utils.Timer;
 import flash.events.TimerEvent;
 import Box2D.Dynamics.*;
 import Box2D.Collision.Shapes.*;
 import Box2D.Common.Math.*;
 public class moops extends Sprite {
  private var world:b2World=new b2World(new b2Vec2(0,0),true);
  private var worldScale:int=30;
  private var timeCount:Timer=new Timer(500);
  public function moops():void {
   timeCount.start();
   debugDraw();
   addEventListener(Event.ENTER_FRAME, update);
   stage.addEventListener(MouseEvent.CLICK,onClick);
   timeCount.addEventListener(TimerEvent.TIMER, onTime);
  }
  private function onClick(e:MouseEvent):void {
   var angle:Number=Math.atan2(mouseX,mouseY-480)-Math.PI/2;
   addball(20*Math.cos(angle),-20*Math.sin(angle));
  }
  private function onTime(event:TimerEvent):void {
   addBox(300+Math.random()*200,-100,40);
  }
  private function addball(xVel:Number,yVel:Number):void {
   var ball:b2BodyDef= new b2BodyDef();
   ball.userData="ball";
   ball.type=b2Body.b2_dynamicBody;
   ball.position.Set(20/worldScale, 460/worldScale);
   var circle:b2CircleShape=new b2CircleShape(15/worldScale);
   var ballFixture:b2FixtureDef = new b2FixtureDef();
   ballFixture.shape=circle;
   ballFixture.friction=0;
   ballFixture.density=1;
   ballFixture.restitution=1;
   var ballBody:b2Body=world.CreateBody(ball);
   ballBody.CreateFixture(ballFixture);
   ballBody.SetLinearVelocity(new b2Vec2(xVel,yVel));
  }
  private function debugDraw():void {
   var debugDraw:b2DebugDraw = new b2DebugDraw();
   var debugSprite:Sprite = new Sprite();
   addChild(debugSprite);
   debugDraw.SetSprite(debugSprite);
   debugDraw.SetDrawScale(worldScale);
   debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
   debugDraw.SetFillAlpha(0.5);
   world.SetDebugDraw(debugDraw);
  }
  private function addBox(xOrigin:Number,yOrigin:Number,size:Number):void {
   var box:b2BodyDef= new b2BodyDef();
   box.position.Set(xOrigin/worldScale,yOrigin/worldScale);
   box.type=b2Body.b2_dynamicBody;
   var square:b2PolygonShape = new b2PolygonShape();
   square.SetAsBox(size/2/worldScale, size/2/worldScale);
   var boxFixture:b2FixtureDef = new b2FixtureDef();
   boxFixture.shape=square;
   boxFixture.friction=0;
   boxFixture.density=4;
   boxFixture.restitution=1;
   var boxBody:b2Body=world.CreateBody(box);
   boxBody.CreateFixture(boxFixture);
   boxBody.SetLinearVelocity(new b2Vec2(0,5));
  }
  private function update(e:Event):void {
   world.Step(1/30,10,10);
   world.ClearForces();
   world.DrawDebugData();
   for (var currentBody:b2Body = world.GetBodyList(); currentBody; currentBody=currentBody.GetNext()) {
    if (currentBody.GetPosition().y*worldScale>600 || currentBody.GetPosition().y*worldScale<(100*-1)) {
     world.DestroyBody(currentBody);
    }
    if (currentBody.GetUserData()=="ball") {
     var velocity:b2Vec2=currentBody.GetLinearVelocity();
     if (velocity.Length()!=20) {
      var speedOffset:Number=20/velocity.Length();
      currentBody.SetLinearVelocity(new b2Vec2(velocity.x*speedOffset,velocity.y*speedOffset));
     }
    }
   }
  }
 }
}

Let’s see how does it work [...]