In this part of the “GSwF” series, we’re going to show you how to use Fireworks to setup some basic buttons with their own unique mouse-sensitive states and behaviors. This will add another level of interactivity to your designs, so if you’re starting out with Fireworks, you won’t want to miss this one!
In the last “Getting Started with Fireworks” post, we looked at how to create Hot Spots, or interactive layers that you can use to link things like text or buttons up with other pages in your documents. Today, we’re going to expand on that by showing you how to create multiple “behaviors”, also known as states within your document.
Connor is going to walk us through how to create a simple button with two different states (one for the normal state, one for the mouse-hover state). Then he’ll expand on this by putting the knowledge to use in the practice project we’ve been using for the series. I’ll let Mr. Turnbull take it from here:
Topic: Getting Started with FireworksTime Required: 30 MinutesSoftware: FireworksVersion: CS5
Today we’re going to dive into the world of Fireworks by examining some of the basic features that make it different from Photoshop. Specifically, we’re going to be using a very basic design to show how Master Pages, Sub-Pages, and Web Layers work to create a complete web design in Fireworks that uses internal file linking. This is a great place to start if you haven’t really used Fireworks much before, so let’s dig in!
This is the first in our series of Getting Start with Fireworks posts where we’re be examining the program and what it has to offer to web designers. In future tutorials we’ll be walking through how to properly slice and export optimized web files, how to use Fireworks for rapid prototyping, and how to use many of the other features that are specific to FW.
We’ll be examining the Fireworks feature called “Pages” in the video, but let me provide just a bit of background. These features simulate different pages within a webpage; Fireworks has the unique ability to allow users to define some “universal” or “master” elements for the entire site (like navigation and branding) in addition to variable content, like text, images, etc. In the video, we’ll be examining how these features relate to each other using a very simple design. By the end of the video, you should have a pretty good understanding of how you can use these features in your own web design.
Feel free to download the source files and follow along, or use your own design to create the same effect.
Connor Turnbull is a web designer based in the UK with a special interest in attempting to create websites around a specific need. He has a special interest in designing usable websites that user can really interact with. And, he’s also part of a new, three-person collaboration on the Envato Marketplaces.
Connor will be walking us through more of these Fireworks videos in the future, so if you have any other specific requests, questions, or ideas, post them down below!
Program: Adobe FireworksVersion: CS5+Estimated Time: 30 mins
In this tutorial, our Fireworks expert Tom Green is going to show us a wide variety of tricks and techniques for working with graphics in Adobe Fireworks. Our ultimate goal will be to create a video player interface, but the lessons are all in watching Tom work with the program.
We’ve been getting a lot of requests for “technique” tutorials in Fireworks that show how to use the program for basic graphical tasks. So, the video tutorial today is as much about the techniques that we’re going to use as the final product. We’ve broken this tutorial down into three videos to make it a bit easier to pick where you want to jump in. The entire video should take about 25 minutes to watch, so kick back and get ready to watch Tom in action!
Part 2: Building the Interface
The great thing about working in Fireworks is that once a design is built, you can export it to pretty much any program in the Adobe Suite. This means that you can take this same design to use in a Photoshop mockup or even directly into Flash to use as a working video player.
Tom Green is a professor of Interactive Multimedia through the Humber Institute of Technology and Advanced Learning’s School of Media Studies. Like all faculty in the program, Tom believes his students deserve to be taught by instructors who are regarded as experts in their field and whose knowledge of their subject is current with industry best practice. He is an Adobe Community Expert, Adobe Education Leader (Post Secondary), Community MX partner and was listed in Adobe’s Top Ten Most Influential Flash Designers.
Tom has written several books (9 in all!) and extended tutorials on the topic of Fireworks and web design over the last 7 years, so he’s a natural fit to guide us through this incredible program. After this introduction, Tom will be guiding us through the wonderful world of Fireworks with several video tutorials. Alright, now that you know a bit about Tom, let’s dig in!
If you’ve been wondering about what makes Fireworks tick for a while, this “Session” is being recorded for you!
We’re amassing quite a few tutorials for everyone from the beginner to the expert, so be sure to check out our entire library of Fireworks tutorials.
If you have a particular request or question about using Fireworks for web or app design, post it in the comments section along with any of your other thoughts!
Program: Adobe FireworksDifficulty: Easy PeezyEstimated Time: 4 mins
Ever needed to batch process an entire folder of files for the web? We’ll walk you through how to do it in this screencast… and there’s a special surprise at the end (hint, you’ll wonder why you haven’t been doing this all along!).
We’ve been releasing a wave of Fireworks tutorials lately… but we haven’t hit the single most important tool that (I believe) Fireworks has to offer web designers. What is it you ask? Batch Processing!
In mere seconds, Fireworks can offer you some enormous file-size reduction over the “Save for Web” process in Photoshop… but what’s better is that it’s 100% automated. This means you can easily save out all of your normal files in Photoshop, and run a simple batch process over the entire folder and get some massive file compression without losing any noticeable quality loss!
I was going to make some crass reference to overweight web graphics and the serious need for a treadmill… but this is a professional blog, so I won’t.
Just do this test for me (you can thank me later):
Find an existing folder of web-images that you’re using right now for a site. (preferably all .JPGs for simplicity, but any files will do).Run a Batch Process over the entire folder…Use JPG > 85% for your .JPGS – play around with optimal settings for the other file types.Record the orginal file sizes and the new file sizes.Post Your Results in the Comments Section below.
I’ve done this little text about 30 times over the last 2 weeks and each and every time I save about 40% – 60% of the file size…
I’m about to release a new product over at ThemeForest.net, so I figured that I would run some basic tests over some of the background images. The problem was, a lot of the files were PNG-24 files with transparency and I didn’t think Fireworks would offer any better compression. I was oh-so-wrong! I was able to save out the PNG-24s as PNG-8's in most cases with no lost quality and came out with 50% file size savings.
Alright – I’ll stop gushing about how much I love the Batch Processing tool (because I kinda feel like one of those infomercial goons on late night TV right now). Even if our Fireworks Pro Video series doesn’t convince you to stop using Photoshop as your pimary tool (I’m still a die-hard PS user myself), take a moment to consider what Batch Processing in Fireworks has to offer.
Today, in this Adobe Fireworks tutorial we will practice how to create a letterpress effect. This is very detailed tutorial, so if you have a beginning level knowledge in Adobe Fireworks you can follow the simple techniques used in this tutorial you will have no problem creating a beautiful and professional effect in the future.
Here’s a preview image of what we’ll be creating together.
Create new document 500pixels x 3500pixels 72dpi Canvas color White
Select Rectangle tool (Fireworks Shortcut Key U) to draw a rectangle vector for Background with Color #BBBBBB
Draw a rectangle with the Rectangle tool (U) size to 500px x 350px create a Texture of your choosing. I create (Wood) texture with Amount of Texture (16%). Rather than using a shade of the background color with Gradient fill.
And fill it with a color #BBBBBB (Grey).
You should have something like this:
Type out some text with the Text tool (T) and chose a font. I am using the awesome ChunkFive font.
And fill it with a color #939393 (Dark Grey). take off any stroke.
Select a text and go in the Properties panel Filler box, next go Shadow and Glow > Inner Shadow.
In the Inner Shadow dialog, change the properties as appear in the example picture below. I am use Distance 1, Opacity 90%, Softness 1, and Angle 270.
Then change the Inner Shadow color to #555555
After Inner Shadow Effect use the same process for drop shadow, in the Properties panel Filler box, select the Shadow and Glow > Drop Shadow.
In the Drop Shadow dialog, change the properties as appear in the example picture below. I am use Distance 1, Opacity 90%, Softness 1, and Angle 270.
In this tutorial you are going to learn how to draw a sunflower using star auto shapes properties in Fireworks. Star draws object that appear as stars with any number of points from 3 to 25. Using control points, you can add or remove points, and you can adjust the inner and outer angles of the points. The image below shows how we have created sunflower bokay.
This tutorial teaches you how to create a sunflower art using Fireworks and thus assumes you are familiar with some design software, even if you are new to Fireworks. However be assured that our detailed instructions can be followed by even a total novice.
You Are Here ::: Home >> Free Tutorials >> Fireworks Tutorials >> Sunflower Art
Follow the steps given below:
#FFFF00#FF9900#D35A23#944D00#D88000
Using this sunflower we have created a beautiful bokay by adjusting the radial effect. See the below image that will how we have arranged the sunflower to form a bokay:
Adobe Fireworks (Macromedia Fireworks prior to version 8). Please check out the compatible versions listed in the box below. Since this tutorial covers an inbuilt core function of fireworks to create sunflower art, using mostly any version of these software should be fine. If you are using the CS4 version of these software please read Sunflower Art with Adobe Fireworks CS5.
In this tutorial you are going to learn how to draw a snail using spiral effect in Fireworks. Spiral draws object groups that appear as open spirals. Using control points, you can edit the number of spiral rotations, and you can determine whether the spiral is open or closed. The image below shows how we have created snail.
This tutorial teaches you how to create a snail using Fireworks and thus assumes you are familiar with some design software, even if you are new to Adobe Fireworks. However be assured that our detailed instructions can be followed by even a total novice to graphic design.
You Are Here ::: Home >> Free Tutorials >> Fireworks Tutorials >> Spiral Effect Snail Graphic
Follow the steps given below:
#C99F2F#BE8D00#957528#3E3015#99CC00#336600#000000#333333Step 1: Open Fireworks and create a new document of size 350x250 pixels. Go to Window >> Auto shape Properties. Insert a Spiral Shape, tick on Close Spiral and untick on Clockwise. Then, go to Modify >> Transform >> Flip Horizontal and rotate the spiral using Scale Tool .Step 2: Now you are going apply gradient effect to the shell. Select the Spiral set Fill Color as #C99F2F and Stroke Color as #3E3015. To apply gradient effect select the spiral and choose the following options:Select the Fill color go to Fill category >> select Gradient >> Choose Contour optionNow click the Fill color, and then click on the small color rectangle that is on the left side and set its color to #C99F2F and set the Opacity as 36.After that, click on the small color rectangle that is on the right side and set its color to #957528.Now add another rectangle by clicking the ‘+’ symbol in between the two small color rectangle and make the colors as #BE8D00. See the illustration below that will show how to set the colors:
Step 3: Using Pen Tool draw a shape as shown below and apply linear effect. See the illustration below that shows how to draw a snail.
Step 4: Again using Pen Tool, draw head part of snail and apply radial effect as shown below.
Step 5: More over you have completed the snail, now we need to apply shadow effect. To apply shadow effect, draw an ellipse using Ellipse tool with the dimensions of Width: 75 pixels and Height: 28 pixels set the Fill color as #333333 and Stroke color as none. Step 6: Select the ellipse to apply Feather effect. Then, click on Edge from Properties panel, choose Feather and set the feather value to 11. Now reduce the Opacity to 25. Since the shadow should appear behind the snail, go to Modify >> Arrange >> Send to Back (Ctrl+Shift+Down arrow). See the illustration below that will show how the ellipse is placed:
The final snail will look as below:
Adobe Fireworks (Macromedia Fireworks prior to version 8). Please check out the compatible versions listed in the box below. Since this tutorial covers the core function of Fireworks to draw a snail, using mostly any version of these software should be fine. If you are using the CS4 version of these software please read Spiral Effect Snail Graphic with Adobe Fireworks CS5.
Programs: Fireworks and Flash CatalystVersion: CS5+Time: 15 minutesThis entry is part 5 of 7 in the Fireworks Pro Series Session « PreviousNext »
In this part of the Fireworks Pro Series, we’re going to continue looking at how Fireworks works with other programs in the Adobe Creative Suite. Specifically, we’ll be creating a website design and then convert it to an interactive, animated website in Flash Catalyst… all in under half an hour!
If you’ve never worked with Flash Catalyst before… this is actually a pretty great starting point. Tom is going to walk through the creation of a simple, straight forward website in Fireworks… but that’s where things really get interesting. Once the site design is complete, we’ll walk through how to convert the entire design into a working, fully interactive (and animated!) site in Flash Catalyst that you can deploy just about anywhere on the web!
This is a great jumping off point for anyone who is new to Flash, Fireworks, or Catalyst – But it’s also useful for just about anyone who hasn’t really used the entire Creative Suite to take a site from design to implementation. In under 30 minutes we’ll be creating a working website… not bad for the same amount of time that it takes to grab lunch.
The key topics that we’ll be covering:
How to build a complete site design in Fireworks (with multiple pages)How to Export the design for Flash CatalystHow to convert the flat design into an interactive website, complete with video, scrollable content, and more. Part 1 of 2 of the Fireworks > Catalyst Video : Exporting into Catalyst Part 2 of 2 of the Fireworks > Catalyst Video : Creating the File in Fireworks
Tom Green is a professor of Interactive Multimedia through the Humber Institute of Technology and Advanced Learning’s School of Media Studies. Like all faculty in the program, Tom believes his students deserve to be taught by instructors who are regarded as experts in their field and whose knowledge of their subject is current with industry best practice. He is an Adobe Community Expert, Adobe Education Leader (Post Secondary), Community MX partner and was listed in Adobe’s Top Ten Most Influential Flash Designers.
Tom has written several books (9 in all!) and extended tutorials on the topic of Fireworks and web design over the last 7 years, so he’s a natural fit to guide us through this incredible program. After this introduction, Tom will be guiding us through the wonderful world of Fireworks with several video tutorials. Alright, now that you know a bit about Tom, let’s dig in!
If you’ve been wondering about what makes Fireworks tick for a while, this series is being recorded for you!
We’re amassing quite a few tutorials for everyone from the beginner to the expert, so be sure to check out our entire library of Fireworks tutorials.
If you have a particular request or question about using Fireworks for web or app design, post it in the comments section along with any of your other thoughts!
Typography is one of the most important skills that a designer can have… industry veterans spend years honing their technique and you could easily spend years at a university studying the topic; But where is the best place to really start out? Today, in the latest addition to our Basix series, we’re introducing typography for beginners by explaining one simple thing: why typography matters so much in web design.
Typography is an ancient discipline that can be most simply explained as the art of arranging and designing the written word. The earliest examples of typography go back as far as 1800 B.C. with the ancient Greeks, but the modern era of typography is tied to the mid 15th century when the printing press was invented.
I’ll keep the history lesson short here: typography is important for one reason: because it is the primary way that designers can communicate with readers… whether the medium be a book, a print advertisement, billboard, or a television show, typography is important because it the embodiment of the visual language.
96% of the Internet is comprised of written information or text. This text is distributed into big and small chunks of information that is spread over different pages with different formats.
The formatting of all this written information in a website’s design is what we call “Web Typography”.
Typography is the most important part of a web design because it influences the way that a website communicates with readers. From larger headlines and bold blocks to small body, the various uses of text on the web are the core communication method… so it’s natural that how a web designer decides to arrange type on a web-page is crucial to the effectiveness of that site.
We see its usage everywhere as all websites rely on typography to convey their message to the readers. However, there are some web designers who tend to over-look the inevitable importance of typography and focus only on the visual or graphical part of the web design.
Using typography for print medium like brochures, fliers, magazines, books or outdoor mediums like pole signs and billboards is different than using it for the computer screen. In terms of typography, the screen is a completely different medium… and as with any type of design, you truly need to consider the medium that people will be viewing your design through. Consider the following two images:
The top image is a poster for the band, The Black Keys. The bottom image is their website. Same band, different approach to typography. Why? Because the medium (and therefore the message and intent) for each design is different. One is to promote a concert, the other is a portal to all sorts of information about the band.
When you are using typography in a print design for something like a book, the fact that it will be viewed from a relatively close proximity gives you the ability to play with the fonts quite a bit because it won’t hurt the readability much. If you are using typography for outdoor communication mediums like a billboard or poster, you know that the reader has only a fraction of time to view the board and consume what is being communicated and so you don’t mess with the fine tuning of the typography much – instead you might focus on the initial impression an readability of the type.
However, with a website there are totally different objectives in mind. Designing typography for computers and the web requires the designer to divide lots of information into different segments and sub-segments (Micro and Macro-typography). Also, a web page is not constant as it has to appear on different browsers, different Internet access devices and with different screen resolutions. So the web typography has to deal with a good number of issues as compared to other mediums. So, while choosing typography for their website, a designer must consider the cross-platform compatibility and readability. These are just a few of the concerns that a web designer has to keep in mind when approaching a website.
When it comes to web design, typography is not limited to choosing a font and laying it out; It is the art of dividing up bundles of information in such a way that the reader will have a good chance of finding what is of interest to him… this is where typography on the web becomes more like information design.
Typography on the web is as much about organizing type into effective, meaningful layouts as it is about using a great typeface.
Drawing attention to a certain block of text, helping users find the content they are searching for, or fitting a wide variety of content onto a single page is all done through typographic skills.
The idea of designing type to be more than just legible, but to also be meaningful is part of what confuses a lot of people about web typography. Anyone can type out a paragraph of text; fewer people can use things like letter-spacing, line-height, and font-size to give it a sense of character;… but the best web designers can organize type across an entire layout in a way that imparts meaning to readers and helps guide them across an entire website.
This is what we mean by typography being information design.
It’s often helpful to begin the typographic system for a design by breaking it up into two different segments:
Macro-typography, which comprises of overall text structure of the documentMicro-typography, which covers the smaller and much detailed aspects like the font type, line-height and spacing etc.
By approaching the Macro-typography first, it can be easy to sketch out the “bigger picture” elements of the type system in a design. Where will the navigation be? How will type on the site be laid out? One column? Two? More? All of the overarching structural rules should be defined first. At this point you can use just about any typeface that you want… but you can begin getting a feel for the size and scale of a design.
Once you have the “big picture” outlined, it’s time to approach Micro-typography. This is where you’ll begin to really refine your type system by defining the stylistic elements such as your primary (and possibly secondary) font-face, how large big headlines will be, the default size of things like sidebar titles, paragraph text, link color, etc.
If you’re just starting out as a web designer, looking around at all of the wild and crazy things happening with web typography can be daunting. You might have a number of questions, like: Where to start? What’s right and wrong? Are there rules that I have to follow? The good news is that at it’s core, web typography does indeed have a few consistent rules that you should be aware of. What follows are are some useful tips I have collected for creating effective type systems for the web:
The hierarchy of typography is very important in a web design. Think of all of the different places that you use text on a website: the navigation, headlines, paragraphs, image captions, sidebars, etc… Chances are good that there’s a lot of text! How are you going to turn all of this into a logical type system? By developing a type hierarchy.
A well-developed hierarchy enables you to know where to start reading, how to proceed reading further, and the difference between most important and less important information on a page. With an effective type hierarchy, you don’t need to rely in text placement anymore to highlight what you want your readers to go through first.
Read more about Understanding Hierarchy
Lack of consistency in typography is one of the most common and most repeated mistakes which web designers commit these days. A print designer often will meticulously design each and every letter on a page… but that’s not necessary with web design.
Instead of trying to manually design each and every piece of type on a site, design with the idea of Cascading Style Sheets (CSS) in mind. Make use of the blessing of CSS and set the font, size, color, line spacing, height and other features of your typography throughout the entire website.
I have mentioned this earlier, but let me emphasize the point: Great web designers do more than just place images and paste text into a web layout. It takes good professional habits to make a winning website design; One of the best professional habits a web designer should have is to read the text before placing it in the web layout. If you have access to the text-content that you’ll be using, avoid just pasting it all in blindly. By going through and reading the actual text, you’ll be able to make a better connection between the content and the design.
Also, when you are done placing the text and other elements in the design, make it a point to go through it again as a proofreading practice to avoid any mistakes or things left out. It’s amazing how often designers forget to style simple things like bullet lists because they rushed through the design phase.
For a successful web design, a web designer should pay attention to both macro and micro typography. Even the best layouts can fall apart if things are missing on the “micro” side of things… and even the best micro-typography won’t be useful to readers if it’s not laid out using proper macro-typography principles. Both are important!
Lots of designers are especially good on one or the other… so take some time to consider what your strongest suit is: macro or micro? Then do your best to strengthen your abilities (through practice and attention to detail!) in your weaker skillset.
This goes without saying for lots of designers, but the color of text is another important thing to consider. There are hundreds of websites which take this point for granted and use font colors that either:
Make typography immensely difficult to be reador… are boring! (and boring colors are wasted colors)
You don’t need to go and splash the entire rainbow across the page, and you don’t need to use something awful like red text on a green background… just use simple, sensible color theory to pick colors for your fonts that are readable and interesting. Remember, links should be colored in most cases… it tells people they can click them!
Read more about Web Design Color Theory.
Stop using Lorem Ipsum! There is no substitute for the actual text while designing a website. While you can use dummy text to get an idea of how things will look like in the layout, as soon as your web design is coming to a completion, try to use the actual text that you or your client plan to use in the live website. Only then will you be able to synchronize the design with the text and determine the impact of how the overall website will look like… even small oversights in this process can lead to weak points in a design, so take the time to use live text before calling a project ‘complete’!
The wonderful thing about web typography is that there are a wide variety of ways to approach it – every designer will have his or her own style for doing things, and there really isn’t a single “right” way of layout out type on the web. Type has personality, just like you or the client you’re working for, so don’t be afraid to play around with your own creative variations once you nail the basix of a site design.
Read more about Choosing the Right Font
Web design requires you to master a number of things in order to make a really great layout, and typography is definitely one of these things. A web designer who truly understands the importance of typography will be able to hit the success factor more often than not… and all it really takes is practice to train your mind to see the best possible way to lay out any given piece of type! Typography is not rocket science, but it does take a lot of work to discover the best way of doing things for any given project.
Take some time every day to practice – try taking an article that you really like and re-design it; Design your own resume, portfolio, whatever you can find… just use whatever ideas that you can to practice and you’ll find yourself getting better in no time! Trust me, as soon as you understand the basics, it’ll become a piece of cake!
This article was co-written by Arfa Mizra and Brandon Jones. Thanks for reading!
Program: Adobe FireworksVersion: CS5+Time: 18 MinutesThis entry is part 6 of 7 in the Fireworks Pro Series Session « PreviousNext »
If you’ve ever wondered about the best possible way to save images for the web, this is going to interest you! In today’s addition to the Fireworks Pro Series, we’re going to look at image optimization in Adobe Fireworks.
One of the best features in Fireworks is the comprehensive “Save for Web” feature that has been layered throughout the entire interface of the program. Unlike Photoshop, where saving images for the web is somewhat limited, Fireworks gives you a vast set of tools to refine your web images. Better yet, because Fireworks has been created for web designers specifically, you’ll notice a smoother workflow when it comes time to chop or slice your design into code-ready images!
Even if you’ve used Photoshop for a site design, using Fireworks for your web-image creation will allow you to:
Reduce the filesize on web images (up to 40% over Photoshop)Access comprehensive tools for tweaking the image settingsCreate independent, transparent .PNG slicesCreate PNG8's with full transparencyUse the powerful 4-Up view for saving images
Here’s the video – I’ll let Tom take it from here:
Tom Green is a professor of Interactive Multimedia through the Humber Institute of Technology and Advanced Learning’s School of Media Studies. Like all faculty in the program, Tom believes his students deserve to be taught by instructors who are regarded as experts in their field and whose knowledge of their subject is current with industry best practice. He is an Adobe Community Expert, Adobe Education Leader (Post Secondary), Community MX partner and was listed in Adobe’s Top Ten Most Influential Flash Designers.
Tom has written several books (9 in all!) and extended tutorials on the topic of Fireworks and web design over the last 7 years, so he’s a natural fit to guide us through this incredible program. After this introduction, Tom will be guiding us through the wonderful world of Fireworks with several video tutorials. Alright, now that you know a bit about Tom, let’s dig in!
If you’ve been wondering about what makes Fireworks tick for a while, this “Session” is being recorded for you!
We’re amassing quite a few tutorials for everyone from the beginner to the expert, so be sure to check out our entire library of Fireworks tutorials.
If you have a particular request or question about using Fireworks for web or app design, post it in the comments section along with any of your other thoughts!
Introduction to Box2D for Flash and AS3 | Activetuts+ var NREUMQ=[];NREUMQ.push(["mark","firstbyte",new Date().getTime()]);(function(){var d=document;var e=d.createElement("script");e.type="text/javascript";e.async=true;e.src="https://d1ros97qkrwjf5.cloudfront.net/14/eum/rum.js";var s=d.getElementsByTagName("script")[0];s.parentNode.insertBefore(e,s);})(); body {background-position: 0 81px;}#bundle_wrap { background: #f0ead7 url(http://active.tutsplus.com/wp-content/themes/tuts/images/global/bundle-bg.jpg) no-repeat center 0; border-bottom: 1px solid #fff; height: 80px; position: relative; z-index: 200; min-width: 980px; padding: 0 10px;} #bundle { height: 80px; /* width: 980px; */ width: 1190px; margin: 0 auto; position: relative; z-index: 200; } #bundle a.bundle-link { display: block; height: 80px; text-indent: -9999px; width: 100%; z-index: 210; } Freelance Mac App Bundle Activetuts+ Advertise Write for Us About Usage Home Tutorials3DActionScriptAIRAnimationDesignEffectsFlexGamesLecturesMediaMobileS.E.O.SilverlightToolsUnityWeb DesignWorkflowXML ArticlesAsk the EditorsCompetitions and GiveawaysGeneralInterviewsNewsOpen MikeQuizzesReviewsRoundups TipsMediaActionScriptWeb DesignGamesAnimationWorkflow Sessions BasixToolsActionScriptGamesWorkflowAnimationUnityTutorialsEffects VideosLectures3DGamesDesignWorkflowSilverlight Premium Plus Premium Tuts+ NetworkEnvatoActiveDenAudioJungleThemeForestVideoHiveGraphicRiver3DOceanCodeCanyonTuts+ MarketplaceCreatticaAppStormMac.AppstormWeb.AppstormiPhone.AppstormPlusPsdtuts+Nettuts+Vectortuts+Audiotuts+Aetuts+Activetuts+Cgtuts+Phototuts+Mobiletuts+Webdesigntuts+Rockable PressFreelanceSwitchCreative Sessions Subscribe Full Post RSS Summary RSS Subscribe via Email Twitter Updates Activetuts+ Plus Network Advertise Here Tutorials\Games Introduction to Box2D for Flash and AS3 Michael James Williams on Jun 2nd 2011 with 22 comments Tutorial Details Difficulty: IntermediatePlatform: Flash (Flash Player 9)Language: AS3Software used: Flash Pro CS3 and FlashDevelop, but you can use any AS3 compiler and editor Tweet Download Source Files
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.
I’d love to say that doing this is as simple as:
var wheel:b2CircularObject = new b2CircularObject();
…but that would be a big fat lie. The thing about Box2D is, apparently simple things can require quite a bit of code to get sorted. This extra complexity is very useful for doing advanced work, but it kinda gets in our way for simple things like what we’re trying to do at the moment. I’m going to quickly go over what we need to do to make this wheel; we can examine it in more detail in later tutorials.
To create a single “physics object” — that is, an object with a shape and a mass that Box2D can simulate within a world — we must construct it using five different classes:
A body definition, which is like a template for creating…A body, which has a mass and a position, but doesn’t have…A shape, which could be as simple as a circle, that must be connected to a body using…A fixture, which is created using…A fixture definition which is another template, like the body definition.
Phew. Here’s what that all looks like in code:
import Box2D.Dynamics.b2BodyDef;import Box2D.Dynamics.b2Body;import Box2D.Collision.Shapes.b2CircleShape;import Box2D.Dynamics.b2Fixture;import Box2D.Dynamics.b2FixtureDef;//...private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);}
The argument that we pass to b2CircleShape() specifies the radius of the circle. Everything else should make sense based on the list above, even if the reasoning behind this structure makes no sense.
Note that we never write new b2Body() or new b2Fixture(); the world is used to create the body from the body definition, and the body is used to create the fixture from the fixture definition. This means that the world knows about all the bodies that are created within it, and the body knows about all the fixtures that are created that connect shapes to it.
The actual physics object that we’ve created is the wheelBody; everything else is just part of a recipe to form that one object. So, to check that we’ve been successful, let’s see whether the wheelBody exists:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);trace(wheelBody);}
Result:
[object b2Body]
Good.
Step 4: Move Your Body
Do you know what I mean when I talk about the “game loop” and a “tick”? If not, go read my short article, Understanding the Game Loop, right now, because it’s really important for what we’re doing.
The Box2D world object has a method, Step(), which drives the simulation. You specify a tiny period of time (a fraction of a second), and Step() simulates the movement and collisions of every object in the world; once the function has run, all the body objects will have been updated with their new positions.
Let’s see this in action. Instead of tracing wheelBody itself, we’ll trace its position. Then, we’ll run b2World.Step(), and trace the wheel’s position again:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);world.Step(0.025, 10, 10);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);}
(The GetPosition() method of a body returns a b2Vec2, so we need to trace the individual x and y properties rather than just calling trace(wheelBody.GetPosition().)
The first parameter we pass to Step() is the number of seconds to simulate passing in the Box2D world. The other two parameters specify how much accuracy Box2D should use in all the mathematical calculations it uses to simulate the passing of time. Don’t worry about these right now; just know that bigger numbers could make Box2D take more time to simulate the world — if you set these too high, it might even take longer than 0.025 seconds to run Step(), so we’d be getting out of sync with the real world!
Test the SWF, and look at your output window:
0 00 0
That’s a little depressing. The wheel hasn’t moved at all — and yet, the world has gravity, so you’d think it would have fallen a little bit. What’s going on?
Step 5: Being Dynamic
By default, all Box2D bodies are static, meaning that they don’t move. Think of the actual platforms in a platform game; they’re solid objects, but aren’t affected by gravity and can’t be pushed around.
We need our wheel to be dynamic, so that it can move. Guess how we define this property of the body? Using the body definition, of course!
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);world.Step(0.025, 10, 10);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);}
Try the SWF now, and see what you get:
0 00 0.00625
It’s moved! How exciting!
Step 6: Keep on Moving
We can’t call this a game loop yet, though, because it’s only running once; we need it to run over and over and over again. We can make this happen using a Timer and an event listener:
import flash.utils.Timer;import flash.events.TimerEvent;//...private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var stepTimer:Timer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);stepTimer.start();}private function onTick(a_event:TimerEvent):void{world.Step(0.025, 10, 10);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);}
(Note that I’ve given the timer a period of 0.025 seconds as well, so that it stays in sync with the world’s steps. You don’t have to do this — in fact, if you make the two periods different, you can get some really cool time-related effects, like slow-motion.)
But, oops, that code won’t work; we need wheelBody to be accessible in the onTick() function. While we’re at it, we might as well make the timer accessible everywhere, too:
public var world:b2World;public var wheelBody:b2Body;public var stepTimer:Timer;//...private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBody = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);stepTimer.start();}
Note that lines 14 and 20, above, have changed, now that the wheel body and timer are defined elsewhere.
Hooray, it’s falling forever! Okay, that’s enough analysing the numbers; let’s make something visual.
Step 7: Draw!
We’ve got all these coordinates, so why not join the dots?
Replace the traces with the code to draw a line from the wheel’s old position to its new one:
private function onTick(a_event:TimerEvent):void{graphics.moveTo(wheelBody.GetPosition().x, wheelBody.GetPosition().y);world.Step(0.025, 10, 10);graphics.lineTo(wheelBody.GetPosition().x, wheelBody.GetPosition().y);}
In order to see the line, we’ll need to set its lineStyle:
private function getStarted():void{//...stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
Now run the SWF. You’ll see a red line accelerating down the left edge. I’ve added some trickery to my SWF that means it won’t do anything until you click it, so you can check it out below:
Great! So, the wheel is free-falling, and getting faster due to gravity, as it should be. We should leave its vertical speed alone so that gravity can do its work, but we can manually alter its initial horizontal speed to make the line’s shape a little more interesting:
private function getStarted():void{//...var startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
Remember that a b2Vec2 looks like an arrow, so, in this case, the starting velocity is going to look like an arrow pointing directly to the right, as if we had just shot it out of a cannon from the top of a cliff. Our world has no air resistance (because there’s no air!) so there’s absolutely nothing to slow it down — though, thanks to gravity, it is speeding up vertically.
Sounds confusing, but it should be clear once you run the SWF:
We’ve just inadvertently drawn a parabola. So… that’s neat, I guess?
Step 9: The Illusion of Movement
Okay, okay, maybe you’re not as thrilled to see a curved red line as I am. If we’re going to simulate a world, we should make the objects look like, well, objects, right? So instead of seeing a line that traces the wheel’s position through space, we should make it look as if the wheel is actually moving through space.
We can do this by repeatedly drawing and erasing a circle, centered on the wheel’s location:
private function onTick(a_event:TimerEvent):void{graphics.clear();graphics.lineStyle(3, 0xff0000);world.Step(0.025, 10, 10);graphics.drawCircle(wheelBody.GetPosition().x, wheelBody.GetPosition().y, 5);}
We have to specify the line style in onTick() now, because graphics.clear() resets it, as well as erasing all the graphics from the screen. Note that I’ve set the radius of the circle to 5, which is the same as the radius of the circleShape we created earlier.
Try this SWF:
I think it’s pretty obvious what the next step should be…
Step 10: Grounded
This infinite world of nothingness doesn’t lend itself to many exciting situations. Sure, we could add new wheels, but without any ground or walls, they’d never do anything interesting.
We’ll create some solid objects that the wheel can collide with, starting with a big flat piece of ground. For this, we’ll use a rectangle.
Remember the objects we need to create a body?
A body definition, which is like a template for creating…A body, which has a mass and a position, but doesn’t have…A shape, which could be as simple as a circle, that must be connected to a body using…A fixture, which is created using…A fixture definition which is another template, like the body definition.
You know how to do this for a circular body; now we need to make a rectangular one:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBody = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var groundBodyDef:b2BodyDef = new b2BodyDef();var groundBody:b2Body = world.CreateBody(groundBodyDef);var groundShape:b2PolygonShape = new b2PolygonShape();groundShape.SetAsBox(stage.stageWidth, 1);var groundFixtureDef:b2FixtureDef = new b2FixtureDef();groundFixtureDef.shape = groundShape;var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
It’s mostly the same, except that, where in creating a circular body we passed the desired radius to the b2CircleShape() constructor, here we must pass the desired width and height of the rectangle to the b2PolygonShape.SetAsBox() function. (Actually, we pass the desired half-width and half-height, so the box will be twice as wide as the stage and two pixels tall, but that’s fine.) Remember that all bodies are static by default, so we don’t have to worry about the ground falling away.
By default, any new shape will be created at (0, 0), so we need to specify that the ground should be created at the bottom of the stage. We could manually alter the position of the ground body once it’s been created, just as we manually altered the velocity of the wheel body, but it’s neater if we set the position as part of the ground’s body definition:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBody = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var groundBodyDef:b2BodyDef = new b2BodyDef();groundBodyDef.position.Set(0, stage.stageHeight);var groundBody:b2Body = world.CreateBody(groundBodyDef);var groundShape:b2PolygonShape = new b2PolygonShape();groundShape.SetAsBox(stage.stageWidth, 1);var groundFixtureDef:b2FixtureDef = new b2FixtureDef();groundFixtureDef.shape = groundShape;var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
Make sure you set this before passing the body definition to world.CreateBody(), or the changes will be ignored.
Now test the SWF:
We can’t see the ground because we haven’t drawn it, but Box2D still simulates it, so we see its effect: the wheel collides with it and rolls to the side.
Step 11: Set Some Boundaries
We’re going to add more wheels in the next step, but first, let’s make this a completely enclosed space, with a ground, a ceiling, and two walls.
I’d like you to have a go at this yourself; create three more rectangular bodies of the right sizes and in the right positions. It’ll be easiest to start with the one on the right, since the wheel is going to collide with it. To test the others, fiddle about with the initial velocity.
You’ll need to change the wheel’s initial position, or it’ll overlap the left wall and the ceiling when they’re created. You can do this in the same way that you set the position of the rectangular objects, through the position.Set() method of the body definition.
Good luck! If you get stuck, check out my code below:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(10, 10);wheelBody = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var groundBodyDef:b2BodyDef = new b2BodyDef();groundBodyDef.position.Set(0, stage.stageHeight);var groundBody:b2Body = world.CreateBody(groundBodyDef);var groundShape:b2PolygonShape = new b2PolygonShape();groundShape.SetAsBox(stage.stageWidth, 1);var groundFixtureDef:b2FixtureDef = new b2FixtureDef();groundFixtureDef.shape = groundShape;var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);var rightWallBodyDef:b2BodyDef = new b2BodyDef();rightWallBodyDef.position.Set(stage.stageWidth, 0);var rightWallBody:b2Body = world.CreateBody(rightWallBodyDef);var rightWallShape:b2PolygonShape = new b2PolygonShape();rightWallShape.SetAsBox(1, stage.stageHeight);var rightWallFixtureDef:b2FixtureDef = new b2FixtureDef();rightWallFixtureDef.shape = rightWallShape;var rightWallFixture:b2Fixture = rightWallBody.CreateFixture(rightWallFixtureDef);var leftWallBodyDef:b2BodyDef = new b2BodyDef();leftWallBodyDef.position.Set(0, 0);var leftWallBody:b2Body = world.CreateBody(leftWallBodyDef);var leftWallShape:b2PolygonShape = new b2PolygonShape();leftWallShape.SetAsBox(1, stage.stageHeight);var leftWallFixtureDef:b2FixtureDef = new b2FixtureDef();leftWallFixtureDef.shape = leftWallShape;var leftWallFixture:b2Fixture = leftWallBody.CreateFixture(leftWallFixtureDef);var ceilingBodyDef:b2BodyDef = new b2BodyDef();ceilingBodyDef.position.Set(0, 0);var ceilingBody:b2Body = world.CreateBody(ceilingBodyDef);var ceilingShape:b2PolygonShape = new b2PolygonShape();ceilingShape.SetAsBox(stage.stageWidth, 1);var ceilingFixtureDef:b2FixtureDef = new b2FixtureDef();ceilingFixtureDef.shape = ceilingShape;var ceilingFixture:b2Fixture = ceilingBody.CreateFixture(ceilingFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
And the result:
Nice work.
Step 12: Create an Array
Now we’re ready to add more bodies, slam them together, and see what happens.
We could create them all invididually, like I did with the rectangles, but it’d be neater to use an array to hold them all, and a single function to create them.
So, first, let’s create that array, with a single element: the existing wheel.
public var world:b2World;//public var wheelBody:b2Body; <-- delete this linepublic var wheelArray:Array;public var stepTimer:Timer;//...private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);wheelArray = new Array();var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(10, 10);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);wheelArray.push(wheelBody);//...var startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}private function onTick(a_event:TimerEvent):void{graphics.clear();graphics.lineStyle(3, 0xff0000);world.Step(0.025, 10, 10);for each (var wheelBody:b2Body in wheelArray){graphics.drawCircle(wheelBody.GetPosition().x, wheelBody.GetPosition().y, 5);}}
If this works, your SWF will act exactly the same as it did before.
Step 13: Add One More Wheel
To test this out properly, we can add an extra wheel — just one for now! Copy and paste the code for creating the wheel and change parts of it so the wheels aren’t exactly the same:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);wheelArray = new Array();var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(10, 10);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);wheelArray.push(wheelBody);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(100, 200);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);wheelArray.push(wheelBody);//... create boundaries herevar startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
You’ll get a bunch of warnings about duplicate variable definitions, but it should still compile, depending on your settings:
The first wheel drops straight down, without an initial sideways velocity. This makes perfect sense when you look at the code; we’re calling wheelBody.SetLinearVelocity() in the wrong place. Move it up:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);wheelArray = new Array();var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(10, 10);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(50, 0);wheelBody.SetLinearVelocity(startingVelocity);wheelArray.push(wheelBody);var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(100, 200);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(5);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(-100, 0);wheelBody.SetLinearVelocity(startingVelocity);wheelArray.push(wheelBody);//... create boundaries herestepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
Okay! That’s working well. We can wrap all that wheel creation code up in a function, now.
Step 14: Wheel Generator
To create this wheel generation function, you can basically copy and paste all the code we’ve been using. Here’s mine:
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void{var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(startX, startY);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(radius);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);wheelBody.SetLinearVelocity(startingVelocity);wheelArray.push(wheelBody);}
I’ve added some parameters so that we can specify the customisable properties of the wheels. While we’re at it, I suggest we move all of the boundary creation code to a separate function, just to keep things tidy:
private function createBoundaries():void{//insert your boundary code here}
Now we can rewrite the entire getStarted() function like so:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);wheelArray = new Array();createWheel(5, 10, 10, 50, 0);createWheel(5, 100, 200, -25, 0);createBoundaries();stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
Try it out! Again, the SWF should act the same as it did before.
Step 15: Automatic Wheels
Now that we’ve simplified the wheel generation, we can make lots of them without much difficulty or mess:
private function getStarted():void{var gravity:b2Vec2 = new b2Vec2(0, 10);world = new b2World(gravity, true);wheelArray = new Array();for (var i:int = 0; i < 20; i++){createWheel(Math.random() * 10,Math.random() * (stage.stageWidth - 20) + 10,Math.random() * (stage.stageHeight - 20) + 10,(Math.random() * 100) - 50,0);}createBoundaries();stepTimer = new Timer(0.025 * 1000);stepTimer.addEventListener(TimerEvent.TIMER, onTick);graphics.lineStyle(3, 0xff0000);stepTimer.start();}
This will create twenty wheels, each with a radius of between 0 and 10, a position of anywhere between (10, 10) and (stageWidth-10, stageHeight-10), and a horizontal speed of anywhere between -50 and +50. Try it out!
It almost works, but something’s wrong. Let’s figure out what’s going on.
Step 16: Spoiler — It’s the Radius
Check out this image from when I ran the SWF:
Some of the wheels are sunk into the ground or wall, and some are overlapping each other. It’s really weird. And on a related note, didn’t we set the radii of the wheels to be anywhere between 0 and 10? Why are they all the same?
As you’ve probably figured out, they’re the same because we hard coded the radius of the circle to draw in the onTick() event handler function. Oops.
Unfortunately we can’t just use wheelBody.radius to find the radius of the wheel; remember that the body doesn’t have a shape, but rather is connected to a shape through a fixture. To find the radius, then, we have to do something like this:
var wheelFixture:b2Fixture = wheelBody.GetFixtureList();var wheelShape:b2CircleShape = wheelFixture.GetShape() as b2CircleShape;var radius:Number = wheelShape.GetRadius();
Fortunately we can simplify this to (wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius(); let’s use this in onTick():
private function onTick(a_event:TimerEvent):void{graphics.clear();graphics.lineStyle(3, 0xff0000);world.Step(0.025, 10, 10);for each (var wheelBody:b2Body in wheelArray){graphics.drawCircle(wheelBody.GetPosition().x,wheelBody.GetPosition().y,(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius());}}
How’s that?
Ah, much better!
Step 17: Have a Little Fun
The simulation is a little dull at the moment; the wheels just roll a little bit and then stop. Boring. Let’s liven things up a bit by changing them from metal wheels to air-filled rubber tyres.
To do this, we can use a property called the coefficient of restitution. This is physics-talk for “bounciness”; the coefficient of restitution of an object shows how much it will bounce back after colliding with another object. Typically, this takes a value between 0 and 1, where 0 means it stops dead as soon as it touches another object, and 1 means it bounces back without losing any energy.
By default, all Box2D bodies have a coefficient of restitution of 0; let’s liven things up by setting it a bit higher:
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void{var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(startX, startY);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(radius);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);wheelBody.SetLinearVelocity(startingVelocity);wheelArray.push(wheelBody);}
This will set the coefficient of restitution of each wheel to a random value between 0.5 and 1. Note that this is a property of the fixture definition, rather than the shape or the body definition.
Let’s see what happens:
That’s more like it! What else can we set?
Step 18: Other Properties
We can also set the friction (how rough or smooth the outer surface is; a polished steel wheel will have less friction than a rough stone one) and the density (how heavy the body would be compared to another of the same size and shape; stone is denser than wood).
The friction coefficient should be between 0 and 1, where 0 means extremely smooth and 1 means extremely rough, and is 0.2 by default. The density can be any value you like, and is 1 by default. (Well, for static bodies, it’s 0, but it doesn’t really matter to them as they don’t move anyway.)
Let’s mess around with these values and see what happens:
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void{var wheelBodyDef:b2BodyDef = new b2BodyDef();wheelBodyDef.type = b2Body.b2_dynamicBody;wheelBodyDef.position.Set(startX, startY);var wheelBody:b2Body = world.CreateBody(wheelBodyDef);var circleShape:b2CircleShape = new b2CircleShape(radius);var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();wheelFixtureDef.shape = circleShape;wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5;wheelFixtureDef.friction = (Math.random() * 1.0);wheelFixtureDef.density = Math.random() * 20;var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);wheelBody.SetLinearVelocity(startingVelocity);wheelArray.push(wheelBody);}
The result:
All good. Feel free to add parameters for restitution, friction, and density to the createWheel() function if you want a bit more control.
There’s something that’s bugging me, though…
Step 19: Heavy, Man
…Why does everything feel so floaty?
Seriously, it’s like the whole world is moving through treacle. But there’s no air resistance, let alone molasses resistance; gravity is at a sensible level; and the time step is matched to the timer’s tick duration — what’s the issue?
If you’re a scientist, you’ve probably noticed that I haven’t mentioned any units in the whole tutorial. The first wheel’s radius was just “5? — not “5 inches” or whatever. We’ve just been working in pixels. But Box2D is a physics engine, and so it uses actual physical units. That wheel had a radius of five meters, not five pixels; that’s roughly sixteen feet, not far off the height of an average house. Most wheels aren’t that height, although there are exceptions, as this Flickr photo from Monochrome shows:
Even then, the tires in that photo have a radius of about 2.5 meters; we’d normally expect a wheel’s radius to be somewhere between a few centimetres and half a meter. This means that every Box2D object we’ve created is much bigger than it appears on the screen, and — as anyone who’s watched Honey I Shrunk The Kids knows — bigger objects move in slow motion.
So, we can get a much less floaty simulation by changing the radius of the wheels that we create:
The resulting SWF feels a lot more realistic, but at the same time, the wheels are all drawn so tiny that it feels like we’re watching from half a mile away:
There’s a common trick that Box2D developers use here…
Step 20: Set the Scale Factor
To recap: Box2D uses meters, but Flash uses pixels. Therefore, a wheel of 0.5 meters in radius is drawn as a tiny circle, just over a pixel wide.
When you read it like that, perhaps the solution seems obvious: we need to scale up the conversion between meters and pixels, so that one meter is drawn as, let’s say, 20 pixels.
Modify the graphics.drawCircle() call in onTick() to reflect this new scale factor:
private function onTick(a_event:TimerEvent):void{graphics.clear();graphics.lineStyle(3, 0xff0000);world.Step(0.025, 10, 10);for each (var wheelBody:b2Body in wheelArray){graphics.drawCircle(wheelBody.GetPosition().x,wheelBody.GetPosition().y,(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * 20);}}
Does that work?
Um, no. We’re back to floatiness, plus the wheels aren’t colliding with each other any more.
Ah, but, this is misleading. The graphical representations of the wheels appear to be overlapping, but actually, they’re not. See, we can’t just use this scale factor for the radii of the wheels and leave it at that; we have to use it for all lengths and distances — and that includes the x- and y-positions of the wheels. So, try this:
private function onTick(a_event:TimerEvent):void{graphics.clear();graphics.lineStyle(3, 0xff0000);world.Step(0.025, 10, 10);for each (var wheelBody:b2Body in wheelArray){graphics.drawCircle(wheelBody.GetPosition().x * 20,wheelBody.GetPosition().y * 20,(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * 20);}}
Actually, hold on — let’s use a public variable instead of hard coding the number 20:
public var scaleFactor:Number = 20;//pixels per meter//...private function onTick(a_event:TimerEvent):void{graphics.clear();graphics.lineStyle(3, 0xff0000);world.Step(0.025, 10, 10);for each (var wheelBody:b2Body in wheelArray){graphics.drawCircle(wheelBody.GetPosition().x * scaleFactor,wheelBody.GetPosition().y * scaleFactor,(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * scaleFactor);}}
Try the SWF now, and… hmm. Just a blank white canvas. Let’s see what’s going on under the hood:
for each (var wheelBody:b2Body in wheelArray){trace(wheelBody.GetPosition().x * 20, wheelBody.GetPosition().y * 20);graphics.drawCircle(wheelBody.GetPosition().x * scaleFactor,wheelBody.GetPosition().y * scaleFactor,(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * scaleFactor);}
My stage is 500x400px. When I wasn’t using a scale factor, a new wheel’s x-position could be anywhere from 10px to 490px from the left of the stage. This was the same as being anywhere from 10 meters to 490 meters from the left of the stage, because each meter was represented as a single pixel long. But now, each meter is represented by twenty pixels — so a new wheel’s x-position could be anywhere from 200px to 9800px from the left of the stage! No wonder we’re not seeing any of them.
To fix this, we’ll use the scale factor in the code that creates a new wheel:
Does it make sense to you that we’re dividing it, rather than multiplying it? Remember, Box2D uses meters, Flash uses pixels, and our scale factor is in pixels/meter.
Try the SWF now:
Much better — but the right wall and ground appear to have disappeared.
…Have you already guessed what’s happening?
It’s because, again, the distances are specified in meters, and we haven’t applied the scale factor. So rather than the right wall being 500px from the left edge, it’s 500 meters, or 10,000px. Again, we need to divide our distances by the scale factor to take this into account.
If you wrote this code yourself, I’m sure you can figure out how to alter it yourself :) Otherwise, here’s mine:
private function createBoundaries():void{var groundBodyDef:b2BodyDef = new b2BodyDef();groundBodyDef.position.Set(0, stage.stageHeight / scaleFactor);var groundBody:b2Body = world.CreateBody(groundBodyDef);var groundShape:b2PolygonShape = new b2PolygonShape();groundShape.SetAsBox(stage.stageWidth / scaleFactor, 1 / scaleFactor);var groundFixtureDef:b2FixtureDef = new b2FixtureDef();groundFixtureDef.shape = groundShape;var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);var rightWallBodyDef:b2BodyDef = new b2BodyDef();rightWallBodyDef.position.Set(stage.stageWidth / scaleFactor, 0);var rightWallBody:b2Body = world.CreateBody(rightWallBodyDef);var rightWallShape:b2PolygonShape = new b2PolygonShape();rightWallShape.SetAsBox(1 / scaleFactor, stage.stageHeight / scaleFactor);var rightWallFixtureDef:b2FixtureDef = new b2FixtureDef();rightWallFixtureDef.shape = rightWallShape;var rightWallFixture:b2Fixture = rightWallBody.CreateFixture(rightWallFixtureDef);var leftWallBodyDef:b2BodyDef = new b2BodyDef();leftWallBodyDef.position.Set(0, 0);var leftWallBody:b2Body = world.CreateBody(leftWallBodyDef);var leftWallShape:b2PolygonShape = new b2PolygonShape();leftWallShape.SetAsBox(1 / scaleFactor, stage.stageHeight / scaleFactor);var leftWallFixtureDef:b2FixtureDef = new b2FixtureDef();leftWallFixtureDef.shape = leftWallShape;var leftWallFixture:b2Fixture = leftWallBody.CreateFixture(leftWallFixtureDef);var ceilingBodyDef:b2BodyDef = new b2BodyDef();ceilingBodyDef.position.Set(0, 0);var ceilingBody:b2Body = world.CreateBody(ceilingBodyDef);var ceilingShape:b2PolygonShape = new b2PolygonShape();ceilingShape.SetAsBox(stage.stageWidth / scaleFactor, 1 / scaleFactor);var ceilingFixtureDef:b2FixtureDef = new b2FixtureDef();ceilingFixtureDef.shape = ceilingShape;var ceilingFixture:b2Fixture = ceilingBody.CreateFixture(ceilingFixtureDef);}
Try it now:
Excellent! And since the scale factor is soft-coded, you could try increasing it:
Conclusion
Congratulations! If you’ve followed this far, then you understand the very important basic concepts of Box2D. (If you didn’t follow this far, then post a comment explaining where you got stuck, and I’ll help you out.) Okay, the final SWF might not look like much, but don’t be fooled; you’ve given yourself an excellent framework for what you’ll learn next.
Speaking of what’s next… what do you want to learn? I’ve got plenty of ideas, and I’m happy to continue this series in whatever direction I’d like to explore, but it’d be cool to know what you think. Do you want to make a physics puzzler? A platformer? A side-scrolling racing game? Are there any core concepts you’d like to focus on, like creating joints?
The next tutorial in this series will most likely be about rendering objects using other methods than the built-in drawing methods — in particular we’ll look at using DisplayObjects, either drawn through Flash or imported as Bitmaps. We’ll also create some actual boxes, because it’s pretty weird to have done an entire Box2D tutorial without any.
You can vote on tutorial ideas through our Google Moderator page at http://bit.ly/Box2DFlashTutorialIdeas, or submit a brand new one, if nobody’s thought of it yet. Looking forward to seeing what you suggest!
Michael James Williams is MichaelJW on Tutsmarketplace Tags: Box2DBox2DFlashAS3physics Enjoyed this Post?
Subscribe to our RSS Feed, Follow us on Twitter or simply recommend us to friends and colleagues!
Tweet By Michael James Williams Rollover to read this author's bio or click through to see a full list of posts by this author. Michael is a freelance Flash developer and technical writer. He is technical editor for Activetuts+, and writes AS3 game development tutorials on his blog. You can find him on Twitter, too: @MichaelJW. Plus Premium Hello!
You can grab source files and bonus tutorials from the members area.
Premium Members
Source Files, Bonus Tutorials & More for all relevant Tuts+ sites in one subscription. Join Now
Related Posts Add Depth to Your Game with Parallax Scrolling 66 Comments Create an Epic War Game in Flash: Part 2 – Active Premium 12 Comments Create a Customizable Flash Quiz Application - Active Premium 4 Comments Create a Basic Drawing Application in Flash 104 Comments Conquer the Universe With ActionScript 3.0 and the Flixel Game Engine: Part 1 38 Comments Advanced Character Customization for Flash Games 16 Comments Add CommentDiscussion 22 Comments tibbi says:June 2, 2011 at 7:00 am
Hello, at the 6th step, the trace in onTick gives error in flashdevelop:
[Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference.
Replytibbi says:June 2, 2011 at 7:13 am
actually getting that error at the 7th step too, at adding graphics.moveTo.. I hate that error :/
ReplyMichael James Williams says:June 2, 2011 at 7:46 amAuthor
Hmm… did you make your wheelBody a public variable? And, if so, did you change the line in getStarted() from var wheelBody:b2Body = (...) to wheelBody = (...)?
Replytibbi says:June 2, 2011 at 9:05 am
oh i see, Ive had a “var wheelBody:b2Body = world.CreateBody(wheelBodyDef);” at getstarted, right under wheelBody = world.CreateBody(wheelBodyDef); Havent seen in the 6th step that you deleted it :) my bad, thanks
Michael James Williams says:June 2, 2011 at 9:42 amAuthor
Goodgood :) I’ll make it clearer in the tutorial that that’s what you’re supposed to do.
tibbi says:June 2, 2011 at 10:30 am
I wish syntax highlighter worked like github, so you could show deleting lines too, not just adding :p
tibbi says:June 2, 2011 at 11:33 am
and since Im in a spammy mood now… you have a bug at rightWallShape.SetAsBox(1, stage.stageWidth);
it works well for you as your width > height, but it didnt work for me :p should be rightWallShape.SetAsBox(1, stage.stageHeight);
left side is ok
Michael James Williams says:June 2, 2011 at 1:37 pmAuthor
Oh wow, nicely spotted! Thanks, I’ve fixed that now :)
James says:June 3, 2011 at 1:39 pm
Been looking forward to this series. I would love to see a Platformer developed using the Box 2d.
Thanks
ReplyMichael James Williams says:June 3, 2011 at 11:08 pmAuthor
At the moment, platformer is the most popular choice of game on the Google Moderator page :)
Replymehmet says:June 3, 2011 at 6:14 pm
Great tutorial on box2d Michael. Keep delivering more box2d tutorials. Box2d is meant for the game development but would love to see how this can be used on a regular site to get more interest.
ReplyMichael James Williams says:June 3, 2011 at 11:09 pmAuthor
Thanks! I think this is a great example of Box2D being used on a regular site like you said: http://www.youtube.com/wariolandshakeit2008. (Click and drag things once the video finishes.)
Replymehmet says:June 4, 2011 at 12:21 pm
Sick find Michael.
Ian Yates says:June 4, 2011 at 11:17 pmStaff
Genius!
Michael James Williams says:June 5, 2011 at 1:55 amAuthor
It was even more impressive when it first came out, because that’s exactly what YouTube looked like!
Zync says:June 4, 2011 at 8:11 am
Great tutorial. Highlighted a lot of good info that the docs don’t explain that well. What do you think about QuickB2? (http://code.google.com/p/quickb2/) as a quickbox wrapper. Seems to cut down on a lot of the mundane setup work.
ReplyMichael James Williams says:June 4, 2011 at 9:13 amAuthor
Cheers :)
Is QuickB2 the same as QuickBox2D? We published a couple of tutorials about that last year; I really like the idea, though at the same time I get a perverse enjoyment out of doing the setup myself.
The QuickB2 demos are very impressive; I particularly like the soft-bodies. We’ll have to commission a tutorial on that in the future!
ReplyZync says:June 4, 2011 at 9:40 am
QuickB2 is similar to QuickBox2D but different coder, slightly better abstraction with a lot more features like soft bodies. You can access the low level Box2D setup work with QuickB2 as well (something you couldn’t really do easily in QuickBox2D) so it can do the best of both worlds. :)
Michael James Williams says:June 4, 2011 at 10:41 amAuthor
Oh, that sounds great! Is it possible to migrate an existing Box2D project over to QuickB2?
Zync says:June 4, 2011 at 8:42 pm
I haven’t used Box2D natively as much mostly cos the setup work for just creating a simple object always did my head in :P But don’t see why not. Where you make a wheel with:
var wheelBodyDef:b2BodyDef = new b2BodyDef(); var wheelBody:b2Body = world.CreateBody(wheelBodyDef); var circleShape:b2CircleShape = new b2CircleShape(5); var wheelFixtureDef:b2FixtureDef = new b2FixtureDef(); wheelFixtureDef.shape = circleShape; var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
You can boil that down to (roughly):
//newCircleShape(center:amPoint2d, radius:Number, mass:Number = 0):qb2CircleShape var wheelBody:qb2CircleShape=qb2Stock.newCircleShape(new amPoint2d(10,10), 20,1); world.addObject(wheelBody);
ReplyMichael James Williams says:June 5, 2011 at 1:54 amAuthor
Nice. Thanks :) In that case, once I’ve got a few parts of this series done, I’ll probably go back and redo some of them using QuickB2.
Replytal says:June 13, 2011 at 4:07 pm
We would love to see next things like how body changes its startingVelocity by using drag and drop of a body
how do drag and drop a body how do you attach to its body other bodies
thats really great!!!
Reply Add a Comment Name Email Address URL Your Comments To add a code snippet to your comment, please wrap your code like so:
YOUR CODE
. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: < and > respectively. Click here to cancel reply. RSS Updates Email Updates Twitter Facebook RSS Subscribers 8,450 Twitter Followers 8,300 Facebook Fans 4,139 Advertise Here Learn More...
Already a member? Sign In
Plus Icon Hello!
Source Files, Bonus Tutorials & More for all relevant Tuts+ sites in one subscription
Members Area Logout Facebook Graph API Development with Flash
Follow Activetuts+ tech editor Michael James Williams as he walks you through integrating Flash with Facebook! Learn to develop apps for the Facebook website and harness the Graph API in your external projects.
Find Out More FacebookTwitter Follow Activetuts+ and Tuts+ on Twitter ? Create an Apple Inspired Flash Preloader http://enva.to/iYkBJSCheck out the great series of podcasts by @riaradio (now nerd radio) they did live at flash and the city http://ht.ly/5oR6DOur latest Fan Bonus tutorial is up on Facebook: http://j.mp/l6aBWP This one's about math tricks! ^MJW? Create a Complete Typing Game in Flash with AS3 http://enva.to/mGahuR Join our newsletter!
Get weekly updates and an exclusive un-released tutorial when you sign up to our free newsletter.
Name Email Top Selling on ActivedenNightstar Premium Facebook F ... only $20.00 by damojo3d Moving Clouds Animation only $3.00 by barisintepeNew Tutorials on Tuts+ MarketplaceCreate a "Rapid Roll" Game i ... only $1.00 by ActivePremiumCreate a Customizable Flash ... only $1.00 by ActivePremium
Sagres Preta Chocolate - More
Freelance Jobs More Freelance Jobs... Basix Active Basix
Just getting started? Start with our basix tutorials on the fundamentals. View All Basix Tutorials
Create a Tutorial, Get Paid!
Have something to teach the world? Want to earn money doing it? Tutorials, screencasts, and articles published here on Activetuts+ are largely contributed by readers just like you! We'll pay you great money for good content. Find Out More