Escolar Documentos
Profissional Documentos
Cultura Documentos
29
30
Adobe has done a great job of making the new mobile APIs in Flash agnostic to any particular platform. For the most part, youll develop your games exactly the same way (with some extra considerations well examine later). However, it is the compilation and deployment steps that are radically different between iOS and Android. This is because iOS is, for better or worse, a very closed system. One of the clear rules and regulations Apple has put in place is that no virtual machines (like Flash) are allowed to run on their devices. Only machine code precompiled for the platform is permitted. Well look at this in depth in a moment, along with its ramifications, but suffice it to say that Adobe had to dramatically change things under the hood in Flash to make our content play on an iOS device. At the other end of the spectrum, Google has made the Android about as open as iOS is closed. It is incredibly easy to deploy software to Android devices (making piracy rampant), just about any manufacturer can make an Android phone or tablet (leading to feature fragmentation across the platform), and all of the operating system is open source. There are no rules about virtual machine code on Android, so Adobe was able to take their popular Adobe Integrated Runtime (AIR) software for developing Flash desktop applications and port it to this mobile OS. Plainly titled AIR for Android, this piece of software must first be installed on any phone that wants to run your games. Luckily for us developers, many phones are looking to ship with it, and it is a free download from Googles Android marketplace. Once a user has it, short of upgrades, they dont have to download it from scratch again. The other main distinction between Flash running on these two platforms is performance. Because of the different compilation techniques and the way the software runs and consumes memory, Flash on the Android is quite noticeably faster than Flash on the iPhone. Ever increasingly fast devices (and work on Adobes part) will eventually mitigate these differences, but as of this writing, it is night and day. As such, if you want to target both iOS and Android with your game, your best bet is to develop with iOS in mind as the lowest common denominator of performance. Once you have your game tightly optimized enough to run acceptably on an iPhone, you can know that on Android it will absolutely sing! During the beta period of the Flash to iPhone packaging software, I created a simple card game for my company, Blockdot, and we released it to the App Store. At the time it was much less stable and feature complete than its 1.0 release a few months later. I spent a number of hours trying to squeeze an extra few frames per second out of some of the animations to keep the game smooth. Fast-forward a few months to when AIR for Android entered beta: I took the same codebase and made some art changes to accommodate for the resolution
31
differences of the two platforms. Within a day or so, I had a working copy of the same game on Android that ran like lightning. In the next two sections, Ill cover getting started with each platform using this same technique of starting with iOS and porting to Android.
32
Compilation
While Adobe masks the creation of Flashs various forms of output under a uniform progress bar, the process happening under the hood is vastly different between a traditional SWF and an iOS application. One of the first assumptions that is often made about Adobes new workflow is that they have simply bundled an iOScompatible version of the Flash Player along with the SWF, not unlike many desktop SWF-to-EXE applications do. It is far more complicated than that. When Flash outputs a traditional SWF, it is creating bytecode that will be either compiled or interpreted at runtime by the Flash Player (see the left-hand side of Fig. BC3.1. In the world of desktop computing, this strikes a good balance between a lightweight file format and a certain amount of user-end computing power required to run Flash content (and minimal time needed to compile it). This form of real-time compilation is known as JIT (or JustIn-Time). For performance reasons (supposedly), Apple does not allow for JIT-driven virtual machines to run on its devices (per the developers agreement). When creating iPhone applications, Flash CS5/5.5 uses a totally different open-source compiler framework known as LLVM (Low-Level Virtual Machine) to compile any AS3 code directly down to ARM machine code, much the same way XCode or any other native language compiler would. Compared to JIT, this is known as AOT (Ahead-Of-Time) compilation. You can see a comparison of the compilation process for both types of files in Fig. BC3.1. If all of these acronyms are making your head spin, fear not! Were almost done. Obviously, the biggest gain this new compilation process makes for Flash applications on iOS is speed. Because it is already a native ARM code, it will run as fast as possible with no conversion or preprocessing required. However, for the boost in speed, there is some loss in functionality and code design considerations, which must be taken into account in order to achieve the best performance. It also means that compiling an iPhone application is not the mere seconds it usually takes to output a SWF, but rather anywhere from one to several minutes depending on the complexity of your application and your computer. This can have a huge impact on workflow since many Flash developers are used to clicking Test Movie with great frequency while coding.
33
Figure BC3.1 The compilation flow of an iOS application from Flash compared with a traditional SWF.
offers these properties as form fields in the new Publish Settings dialog for iOS applications. Well cover each of these properties in depth shortly when we create an extremely simple iPhone application and deploy it to a device. In addition to these settings, iOS applications need a set of icons created for use on the device, and a start-up screen to display while they load. The pixel dimensions for the iPhone icons are
34
29 29, 57 57, 114 114, and 512 512, with the iPad needing specific sizes of 48 48 and 72 72. The start-up screen dimensions (and overall resolution) of the iPhone (pre iPhone 4) is 320 480, a portrait (vertical) orientation. Even if your game is meant to run in landscape (horizontal) mode, this screen image must be vertically oriented when bundled with the application.
35
36
First, click the link in the gray box to download the WWDR intermediate certificateyoull only need this one time per machine to get your system to recognize Apple as a Certificate Authority. Once it has downloaded, click the Request Certificate button. This will take you to a page where you can upload a certificate request file. The process for generating this request is different on Windows and Mac machines. Since it is more illustrative and doesnt require downloading any additional components (and since, as of this writing, the only way to upload your games to the App Store is with a Mac-only utility), well cover the Mac process in this text. Ill post links for the Windows certificate process on this books Web site. In your Applications/Utilities folder on your system, you will find an application called Keychain Access; launch this program. When it is open, select the main application drop-down menu and choose Certificate Assistant Request a Certificate, as in Fig. BC3.5. A new panel should pop open for the Certificate Assistant. Input your e-mail address associated with your iOS developer account, as well as your name in the same format you typed it on the site. Select the option to save the certificate to disk and click Continue.
Figure BC3.4 The Developer Certificates section of the program portal; here you can create a new certificate for building applications.
37
The Assistant will create a file on your Desktop (by default) called CertificateSigningRequest.certSigningRequest. Switch back to your Web browser and upload this file via the certificate request page. The page should refresh and look very similar to Figure BC3.7. In most cases, you will be the only person on your account, but if you have a team of developers under one main log-in, the person with administrative privileges will have to approve the certificate.
Figure BC3.6 The Certificate Assistant panel will help you create a certificate request usable by Apple.
38
Well assume for the moment that you are said administrator and can click the Approve button yourself. Once youve approved the request, the page should refresh momentarily and look as that in Fig. BC3.8. Click the download button and a small file called something like developer_identity.cer will be created. Open the folder containing both files youve just downloaded (your certificate and the WWDR file). Double-click the WWDR fileit should automatically be associated with Keychain Access and install itself. Next double-click your certificate file. It should be added to your Certificates list in Keychain Access, as shown in Fig. BC3.9. As you can see, the certificate has an expiration date of one year; at that time, youll have to repeat this step, assuming youve renewed your Developer Program membership. The final step to generate the file in a format that Flash CS5 can read is to select the certificate in Keychain Access and click File Export Items. It will automatically select the correct format (a p12 file, or Personal Information Exchange). Save the resulting file in a location that is easily accessible. You will reference this certificate whenever you want to generate an iOS application from Flash.
Figure BC3.8 An official certificate has been created and can be downloaded at any time.
Figure BC3.9 Once youve installed the developer certificate, it will show up in Keychain Access for future reference.
39
Keychain Access will prompt you for a password; select something you will remember easily as youll also have to type in this password each time Flash uses this certificate. You are done with this first and most complicated stepcongratulations!
The UDID
Every iOS has a unique device identifier. Plug your device into your computer and launch iTunes. Select the device in the left-hand menu, and the Summary tab for the device should be displayed in the main window, as in Fig. BC3.10. By default, the last of the four pieces of information about the device will show the serial number. Click on this serial number and iTunes will switch to display the UDID. Then immediately press Control/Command + C on the keyboard to copy this value to your clipboard. You will need it momentarily. Return to the Developer Program portal page and select Devices from the left-hand menu. Choose Add Devices. You will be presented with the page shown in Fig. BC3.11. You can enter a name that will help you identify the device later (since you might be testing on multiple devices at some point) and paste in the UDID from
Figure BC3.11 The page for adding an iOS device to your list of available development devices.
40
the clipboard. Click Submit and your device will be added to the portal. This will be necessary for the next steps.
The AppID
Each unique application created for the iPhone should have a corresponding Application ID (or AppID). Select App IDs from the portal menu and choose to create a new App ID by clicking New App ID; this will present you with the page shown in Fig. BC3.12. Enter a description and a Bundle Identifier; it is a good idea to follow the recommended practice and choose an identifier in the same reverse-domain name style as Flash stores class packages. This will help ensure no namespace collisions with other applications. For the Bundle Seed ID, most of the time you will select Generate New. However, as noted on the Create App ID page, if you were creating a suite of related applications (not as common with games) that needed to access the same information, you would give them the same Bundle Seed. Once youve submitted the App ID, you should see it listed in the format as shown in Fig. BC3.13.
Figure BC3.12 The page for creating App IDs on the developer portal.
Figure BC3.13 Once an App ID is created, you can configure its properties and see its entire unique identifier and description.
41
42
Even then, you often will only need to do some of them. Now lets open Flash CS5.5 and get started building our first application.
The DemoApp
Ive never liked Hello World applications. I can appreciate having an extremely simple application that does basically nothing and serves as a starting point for a new language. However, if youre at all familiar with Flash (which I would assume since you picked up this book), then making your first iPhone application really isnt learning a new language, but rather a new process. On top of that, since the process is a little bit of a pain, we should create something slightly more gratifying than two words on a background color. As such, our first application will touch on all three of the major new APIs available for the iPhone on a very superficial level. If you havent already, I would suggest taking a moment to go to www.flashgamebook.com and download the examples file, so you can follow along. All of the files are in one package, so youll be set for the rest of the chapters in this book.
43
As the information laid out here suggests, well be capturing the x, y, and z values from the Accelerometer, the longitude and latitude from the Geolocator, and some touch events from the MultiTouch class. This will make our first program on the iPhone in Flash basically interactive. Hello World, indeed.
Figure BC3.16 The first application well build for the iPhone.
The two new sensor devices in the iPhone are the Accelerometer and the Geolocator, both of which are in the new flash .sensors package, and they each have corresponding events for the data they capture. The new classes for handling multitouch input are logically found in the UI package alongside the keyboard and mouse.
public class APIDemo extends Sprite{ private var _accelerometer:Accelerometer; private var _geolocation:Geolocation; public var accelX:TextField, accelY:TextField, accelZ: TextField; public var latitude:TextField, longitude:TextField; public var touchText:TextField; public var touchSensor:Sprite;
44
This application has very few variables declared. Well store instances of Accelerometer and Geolocation objects, and then there are references to all of the TextField instances and the touch sensor Sprite in the visual layout. Now were ready to dig into the functionality.
public function APIDemo() { addEventListener(Event.ADDED_TO_STAGE, addedToStage, false, 0, true); } private function addedToStage(e:Event):void { if (Accelerometer.isSupported) { _accelerometer = new Accelerometer(); _accelerometer.addEventListener(AccelerometerEvent .UPDATE, accelerometerUpdate, false, 0, true); } else { accelX.text = accelY.text = accelZ.text = "N/A"; } if (Geolocation.isSupported) { _geolocation = new Geolocation(); _geolocation.addEventListener(GeolocationEvent .UPDATE, geolocationUpdate, false, 0, true); } else { latitude.text = longitude.text = "N/A"; } Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; touchSensor.addEventListener(TouchEvent.TOUCH_TAP, touchListener, false, 0, true); touchSensor.addEventListener(TouchEvent.TOUCH_BEGIN, touchListener, false, 0, true); touchSensor.addEventListener(TouchEvent.TOUCH_END, touchListener, false, 0, true); touchSensor.addEventListener(TouchEvent.TOUCH_ROLL_OVER, touchListener, false, 0, true); touchSensor.addEventListener(TouchEvent.TOUCH_ROLL_OUT, touchListener, false, 0, true); touchSensor.addEventListener(TouchEvent.TOUCH_MOVE, touchListener, false, 0, true);
45
Most of what happens in this application is in its initialization, which happens when the application is finally on the Stage and loaded. For both the Accelerometer and Geolocation classes, we check their static properties of isSupported (which will be false in environments where those devices do not exist) and then attach listeners to their update events. If they are not supported, well simply output N/A in the corresponding TextFields of the application. Note that you have to create an instance of the Accelerometer and Geolocation classestheir core functionality is not static. As any reader familiar with my last book will remember, when adding our event listeners we pass the fifth parameter of false to weakly reference the listener. This aids greatly in garbage collection, which is essential to smoothly running applications on the iPhone. After setting up the sensors, we create listeners for all of the various touch events that Flash is capable of reading. These events are the most akin to traditional MouseEvents in the desktop environment. Also, since you have to choose at any given moment whether your application is in Touch or Gesture mode (hence the static Multitouch.inputMode property), well keep it simple and only listen for Touch events. Now lets look at the three methods referenced by our event listeners.
private function accelerometerUpdate(e:AccelerometerEvent):void { accelX.text = e.accelerationX.toFixed(2); accelY.text = e.accelerationY.toFixed(2); accelZ.text = e.accelerationZ.toFixed(2); } private function geolocationUpdate(e:GeolocationEvent):void { longitude.text = e.longitude.toFixed(2); latitude.text = e.latitude.toFixed(2); } private function touchListener(e:TouchEvent):void { touchText.text = e.type; }
Every time the Accelerometer registers an update, the three text fields associated with it will be updated with the corresponding x,
46
y, and z values. The same is true of the Geolocation class though unless you move around a whole lot youre probably not going to notice different values from the initial start-up ones. All of these values are floating point numbers that can get very large, so when assigning them to the text fields, were truncating them to two decimal places using the toFixed method. When performing calculations with them, its best to leave them in their original form unless you have a reason to round. Finally, the event handler for TouchEvents simply updates that text field with the most recent event type. Well see the practical result of this shortly. In the mean time, switch back to the XFL file and hit Control/Command + Enter to perform a Test Movie. A SWF will be compiled and launched in the Adobe AIR Debugger. This will prove useful for doing quick testing of certain application elements later on when you dont want to take the time to do a full iPhone export. Note that all of the sensor text fields show up as N/A because they do not exist on your computer. The moment of truth has now comelets put this application on an iPhone and see what happens. Inside of Flash CS5.5, select File iPhone Settings. You will be presented with a three-tabbed panel. In the General tab, as shown in Fig. BC3.18, you can select the basic aspects of your application, such as the file name, the version number, and the aspect ratio. If you had extra resources to bundle with the application, you would include these here as well. If youre using the example file I have provided, all of these fields should be correctly filled. Click the Deployment tab. From this screen, we will select the developer certificate (p12 file) we created several steps back. Use the file browser to select this certificate and enter the same password you chose for it earlier. For convenience, select the Remember password for this session option as well. This will keep you from retyping it until you restart Flash. Next, locate the provisioning file we also saved earlier and imported into iTunes. The last piece of information needed is the App ID we created earlier. Figure BC3.19 shows how this screen should be basically configured. Finally, click on the Icons tab. If it is not already set correctly, select the appropriately sized icon PNG files from the Icons folder bundled with this example. While they are nothing glamorous, they work better than having a plain white square as an icon for your first program. To complete the process, click OK and save your file (so, you dont lose your settings in case Flash crashes or locks up). Then, re-open the iOS Settings panel and click Publish. You will be presented with a progress bar and some exterFigure BC3.17 Our DemoApp running nal applications may launch and close as it goes about geninside the AIR Debuggernotice that no sensors were detected. erating your IPA file. Even with this very simple application,
47
Figure BC3.19 The Deployment tab of the AIR for iOS Settings panel.
48
it will likely take up to a minute or two to compile the final file. When it is complete, you will see a new file (likely titled DemoApp .ipa) alongside your SWF file. If youve gotten this far without repeating any steps or correct mistakes, great job! If not, dont be discouragedit took me several hours to get it right the first time. That said, I did not have an outstanding text such as this one to guide me. Double-click the IPA file and it will be added automatically to your Applications menu inside of iTunes. You should see the appropriate icon displayed. Select your device and go to the Applications tab, as shown in Fig. BC3.20. If it is not already selected, check the box beside DemoApp so that it will be synced to your device. Then click Sync. Assuming there are no problems with the file or certificates, the sync process will complete and you will see the DemoApp icon on your iPhone or iPod Touch screen. Tap it to launch it and see your handiwork! Once open, you will likely be prompted to let the DemoApp have access to your location for the Geolocation class; grant it to see your latitude and longitude. You should also see the Accelerometer values changing every second or so as you move and tilt the device. Finally, if you interact with the touch sensor square, you will see the resultant event. Tap on the screen and it should return a touchTap. Press your finger and begin to drag and you should see a touchBegin followed by touchMove. Pretty nifty, eh?
Figure BC3.20 The device Applications tab inside of iTunes, showing our new DemoApp.
49
Document Resolution
One of the biggest challenges from a developer standpoint in working with the Android devices is the fact that there is no enforced, fixed resolution or even aspect ratio across the many different pieces of hardware out there. The OS supports screens as small as 240 400 and as large as 480 1024. There are techniques you can apply to make sure your content scales or adjusts properly to the screen size of a particular device. Ill explore a few of these options in Chapter 16 to make sure the elements of your game can adjust to these different sizes. In the mean time, well go with a nice, high-density standard that Adobe and Google seem to have unofficially settled on of 480 800. This is the resolution of both of Googles official phones (the Nexus One and Nexus S) and goes by the name of WVGA (wide VGA). Change the document size to this new resolution. Youll see that you suddenly have a lot of empty space to the right and bottom of the applications interface. In a real application with raster artwork, youd probably have different assets for an Android build of the game, so youd likely spend some time at this point swapping all of those pieces. However, since this application is nothing but text fields and lines, we can go the lazy route. With the Stage in focus, click and drag a bounding box around all of the elements on the Stage to select everything at once. Hit the Q key to go into Free Transform mode, then hold down the Shift key and click and drag the lower left handle to stretch the elements to fill the screen, as shown in Fig. BC3.21.
50
Publish Settings
Next, open the Publish Settings dialog from the File menu. iPhone OS should be the selected Player type. Change this to AIR Android, then click the Settings button next to the dropdown to open the AIR for Android configuration menu, shown in Fig. BC3.23. For the purposes of this application, well just leave all of the default options checked on the General tab. Select the Deployment tab. Like when developing iOS applications, youll need a certificate, but luckily you can create one here within Flash for development purposes. Just click Create and enter some values for the
Figure BC3.22 The new option for scaling content when the Stage is resized.
51
Figure BC3.23 The application settings menu for AIR for Android applications.
settings, including a password you can remember. This will serve as your default AIR for Android dev certificate from this point forward. Enter the password in the field below the cert selector and choose the options shown in Fig. BC3.24: Device release, and both check boxes for installing and launching the application.
Deploy!
Now comes the moment of truth. If you have an Android device connected, click Publish and about 1520 seconds later the DemoApp should launch on it. Its really that simple. If you dont have a device, things get a little trickier. Youll need to get the Android SDK from developer.android.com and set up an emulator. I wont go through all of those steps here, as an emulator unfortunately wont work for any of the APIs in this demo application. In general, nothing beats testing on a device, so picking up a new or used phone for development is always the best idea.
52
Figure BC3.24 The deployment settings for our AIR Android application.