archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • An Introduction to iOS 8 Sprite Kit Game Programming - Techotopia
    is required The physics body also allows forces to be applied to nodes such as propelling a node in a particular direction across a scene using either a constant or one time impulse force Physical bodies can also be joined together using a variety of different join types such as sliding fixed hinged and spring based attachments The properties of a physics body and therefore the associated node may also be changed Mass density velocity and friction are just a few of the properties of a physics body available for modification by the game developer eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Physics World Each scene in a game has its own physics world object in the form of an instance of the SKPhysicsWorld class A reference to this object which is created automatically when the scene is initialized may be obtained by accessing the physicsWorld property of the scene The physics world object is responsible for managing and imposing the rules of physics on any nodes in the scene with which a physics body has been associated Properties are available on the physics world instance to change the default gravity settings for the scene and also to change the speed at which the physics simulation runs Actions An action is an activity that is performed by a node in a scene Actions are the responsibility of SKAction class instances which are created and configured with the action to be performed That action is then run on one or more nodes An action might for example be configured to perform a rotation of 90 degrees That action would then be run on a node to make it rotate within the scene The SKAction class includes a wide range of action types including fade in fade out rotation movement and scaling Perhaps the most interesting action involves animating a sprite node through a series of texture frames Actions can be categorized as sequence group or repeating actions An action sequence specifies a series of actions that are to be performed consecutively whilst group actions specify a set of actions to be performed in parallel Repeating actions are configured to restart after completion An action may be configured either to repeat a set number of times or to repeat indefinitely Transitions Transitions occur when a game changes from one scene to another Whilst it is possible to immediately switch from one scene to another a more visually pleasing result might be achieved by animating the transition in some way This can be implemented using the SKTransition class which provides a number of different pre defined transition animations such as sliding the new scene down over the top of the old scene or presenting the effect of doors opening to reveal the new scene Texture Atlas A large part of

    Original URL path: http://www.techotopia.com/index.php/An_Introduction_to_iOS_8_Sprite_Kit_Game_Programming (2016-02-13)
    Open archived version from archive


  • An iOS 8 Swift Sprite Kit Level Editor Game Tutorial - Techotopia
    an SKTransition instance will be used to animate the transition from the current scene to the archery scene using a doorway style of animation Implement these requirements by adding the following code to the touchesBegan method in the GameScene swift file override func touchesBegan touches Set NSObject withEvent event UIEvent Called when a touch begins let welcomeNode childNodeWithName welcomeNode if welcomeNode nil let fadeAway SKAction fadeOutWithDuration 1 0 welcomeNode runAction fadeAway completion let doors SKTransition doorwayWithDuration 1 0 let archeryScene ArcheryScene fileNamed ArcheryScene self view presentScene archeryScene transition doors Before moving on to the next steps we will take some time to provide more detail on the above code From within the context of the touchesBegan method we have no direct reference to the welcomeNode instance We do know however that when it was added to the scene in the SpriteKit Level Editor that it was assigned the name welcomeNode Using the childNodeWithName method of the scene instance therefore a reference to the node is being obtained within the touchesBegan method as follows let welcomeNode childNodeWithName welcomeNode The code then checks that the node was found before creating a new SKAction instance configured to cause the node to fade from view over a one second duration let fadeAway SKAction fadeOutWithDuration 1 0 The action is then executed on the welcomeNode A completion block is also specified to be executed when the action completes This block creates an instance of the ArcheryScene class preloaded with the scene contained within the ArcheryScene sks file and an appropriately configured SKTransition object The transition to the new scene is then initiated let fadeAway SKAction fadeOutWithDuration 1 0 welcomeNode runAction fadeAway completion let doors SKTransition doorwayWithDuration 1 0 let archeryScene ArcheryScene fileNamed ArcheryScene self view presentScene archeryScene transition doors Compile and run the application Once running touch the screen and note that the label node fades away and that after the transition to the ArcheryScene takes effect we are presented with a grey scene that now needs to be implemented Adding the Texture Atlas Before textures can be used on a sprite node the texture images first need to be added to the project Textures take the form of image files and may be added individually to the Supporting Files folder of the project For larger numbers of texture files it is more efficient both for the developer and the application to create a texture atlas In the case of the archer sprite this will require twelve image files to animate the loading and subsequent shooting of an arrow As such a texture atlas will be used to store these animation frame images The images for this project can be found in the sample code download which can be obtained from the following web page http www ebookfrenzy com web ios8 Within the code sample archive locate the folder named SpriteImages Located within this folder is the archer atlas sub folder which contains the animation images for the archer sprite node To add the atlas to the project drag and drop the archer atlas folder into the Supporting Files folder in the Xcode project navigator panel so that it appears as shown in the following figure Figure 64 6 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Designing the Archery Scene The layout for the archery scene is contained within the ArcheryScene sks file Select this file so that it loads into the Level Editor environment With the scene selected in the canvas use the SKNode Inspector panel to change the color property to white From within the SpriteKit Level Editor the next task is to add to the scene the sprite node representing the archer Referring to the Object Library panel click on the Media Library toolbar option and locate the archer001 png texture image file as outlined in Figure 64 7 Figure 64 7 Once located drag and drop the texture onto the canvas and position it so that it is located in the vertical center of the scene at the left hand edge as shown in the following figure Figure 64 8 With the archer node selected use the SKNode Inspector panel to assign the name archerNode to the sprite The next task is to define the outline of the physical outline of the archer sprite This will be used by the SpriteKit system when deciding whether the sprite has been involved in a collision with another node within the scene By default the physical shape is assumed to be a rectangle surrounding the sprite texture represented by the blue boundary around the node in the scene editor Another option is to define a circle around the sprite to represent the physical shape A much more accurate approach and one that has been introduced in iOS 8 is to have SpriteKit base the physical shape of the node based on the outline of the sprite texture image With the archer node selected in the scene scroll down within the SKNode inspector panel until the Physics Definition section comes into view Using the Body Type menu change the setting from Bounding rectangle to Alpha mask Figure 64 9 Once the change has been made note that the sprite node is now outlined by a physical body shape matching the texture image Figure 64 10 Before proceeding with the next phase of the development process test that the scene behaves as required by clicking on the Simulate button located along the bottom edge of the editor panel Note that the archer slides down and disappears off the bottom edge of the scene This is because the sprite is configured to be affected by gravity For the purposes of the game the archer is required to be pinned to the same location and not subject to the laws of gravity Click on the

    Original URL path: http://www.techotopia.com/index.php/An_iOS_8_Swift_Sprite_Kit_Level_Editor_Game_Tutorial (2016-02-13)
    Open archived version from archive

  • A Swift iOS 8 Sprite Kit Collision Handling Tutorial - Techotopia
    as the contact delegate for the physics world object associated with the scene in which the contact took place In actual fact the system is able to notify the delegate at both the beginning and end of the contact if both the didBeginContact and didEndContact methods are implemented Passed as an argument to these methods is an SKPhysicsContact object containing information about the location of the contact and references to the physical bodies of the two nodes involved in the contact For the purposes of this tutorial we will use the ArcheryScene instance as the contact delegate and implement only the didBeginContact method Begin therefore by modifying the didMoveToView method in the ArcheryScene swift file to declare the class as the contact delegate override func didMoveToView view SKView self physicsWorld gravity CGVectorMake 0 1 0 self physicsWorld contactDelegate self self initArcheryScene eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Having made the ArcheryScene class the contact delegate the ArcheryScene swift file needs to be modified to indicate that the class now implements the SKPhysicsContactDelegate protocol import UIKit import SpriteKit class ArcheryScene SKScene SKPhysicsContactDelegate Remaining within the ArcheryScene swift file implement the didBeginContact method as follows func didBeginContact contact SKPhysicsContact let firstNode contact bodyA node as SKSpriteNode let secondNode contact bodyB node as SKSpriteNode if contact bodyA categoryBitMask arrowCategory contact bodyB categoryBitMask ballCategory let contactPoint contact contactPoint let contact y contactPoint y let target y secondNode position y let margin secondNode frame size height 2 25 if contact y target y margin contact y target y margin println Hit score The code starts by extracting references to the two nodes that have collided It then checks that the first node was an arrow and the second a ball no points are scored if a ball falls onto an arrow Next the point of contact is identified and some rudimentary mathematics used to check that the arrow struck the side of the ball for a game of app store quality more rigorous checking might be required to catch all cases Assuming that the hit was within the defined parameters a message is output to the console and the game score variable is incremented Run the game and test the collision handling by making sure that the Hit message appears in the Xcode console when an arrow hits the side of a ball Implementing a Physics Joint Between Nodes When a valid hit is detected the arrow needs to appear to embed partway into the ball and stick there as the ball continues its descent In order to achieve this a new texture will be applied to the arrow sprite node that makes the arrow appear without a tip and slightly shorter The joining of the arrow node and ball will be achieved by implementing a physics joint at the point

    Original URL path: http://www.techotopia.com/index.php/A_Swift_iOS_8_Sprite_Kit_Collision_Handling_Tutorial (2016-02-13)
    Open archived version from archive

  • An iOS 8 Sprite Kit Particle Emitter Tutorial - Techotopia
    that value is reached Particle Life Cycle The lifetime property controls the length of time in seconds that a particle lives and is therefore visible before disappearing from view The range property may be used to introduce variance in the lifetime from one particle to the next based on a random time value between 0 and the specified range value Particle Position Range The position properties define the location from which particles are created The X and Y values can be used to declare an area around the center of the node location from which particles will be created randomly Angle The angle at which a newly emitted particle will travel away from the creation point in counterclockwise degrees where a value of 0 degrees equates to rightward movement Random variance in direction can be introduced via the range property Particle Speed The speed property specifies the initial speed of the particles at time of creation The speed can be randomized by specifying a range value Particle Acceleration The acceleration properties control the degree to which a particle accelerates or decelerates after emission in terms of both X and Y directions Particle Scale The size of the particles can be configured to change using the scale properties These settings cause the particles to grow or shrink over the course of their lifetimes Random resizing behavior can be implemented by specifying a range value The speed setting controls the speed with which the size changes take place Particle Rotation The rotation properties control the speed and amount of rotation applied to the particles after creation Values are specified in degrees with positive and negative values correlating to clockwise and counter clockwise rotation respectively The speed of rotation may be specified in degrees per second eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Particle Color The particles created by an emitter can be configured to transition through a range of colors during a lifetime To add a new color in the lifecycle timeline click on the color ramp at the location where the color is to change and select a new color Change an existing color by double clicking on the marker to display the color selection dialog Figure 66 3 for example shows a color ramp with three color transitions specified Figure 66 3 To remove a color from the color ramp click and drag it downward out of the editor panel The color blend settings control the amount by which the colors in the particle s texture blend with the prevailing color in the color ramp at any given time during the life of the particle The greater the Factor property the greater the colors blend with 0 indicating no blending The blending factor can be randomized by specifying a range and the speed at which the blend

    Original URL path: http://www.techotopia.com/index.php/An_iOS_8_Sprite_Kit_Particle_Emitter_Tutorial (2016-02-13)
    Open archived version from archive

  • Integrating iAds into an iOS 8 App using Swift - Techotopia
    the banner will cycle through different ads The following code for example creates a medium rectangle ad instance and assigns the current class as the delegate let rectangleAdView ADBannerView adType ADAdType MediumRectangle rectangleAdView delegate self When an ad is ready to be displayed the bannerViewDidLoadAd method of the delegate will be called the responsibility of which is to display the ad within the current view For example func bannerViewDidLoadAd banner ADBannerView self view addSubview banner self view layoutIfNeeded Note that the above code does not attempt to position the ad rectangle In a real world application code will need to be added so that the ad appears in the appropriate location on the view The rectangle ad will rotate through different ads as long as inventory is available In the event that an ad is not available or the device loses connectivity the didFailToReceiveAdWithError delegate method will be called so that the advert can be removed from the view until another ad is available to be displayed func bannerView banner ADBannerView didFailToReceiveAdWithError error NSError banner removeFromSuperview self view layoutIfNeeded As with the banner ad format a full screen advertisement will be displayed in the event that the user taps on the rectangle ad Once again the viewWillDisappear and viewWillAppear delegate methods may be used to pause and resume the application if appropriate eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Pre Roll Video Ads For applications that make use of the iOS MediaPlayer Framework to play videos this feature allows advertisement videos to be played before the actual video is played to the user This simply involves calling the playPrerollAdWithCompletionHandler method of the media player instance A completion handler is then called so that the playback of the actual video can be initiated when the ad has finished running For example let url NSURL string http www ebookfrenzy com ios book movie movie mov let player AVPlayer URL url let playerController AVPlayerViewController playerController player player self presentViewController playerController animated true completion nil playerController playPrerollAdWithCompletionHandler error in player play As with the interstitial ad format Apple recommends preparing the application for pre roll video ads at application launch time import AVKit func application application UIApplication didFinishLaunchingWithOptions launchOptions NSObject AnyObject Bool AVPlayerViewController preparePrerollAds return true Creating an Example iAds Application In the remainder of this chapter we will work step by step through the creation of a simple iOS 8 application that includes banner interstitial and rectangle based iAd advertisements Begin this tutorial by launching Xcode and creating a new iOS application project named iAdDemo using the Single View Application template using the Swift language and with the Devices menu set to Universal Adding the iAds Framework to the Xcode Project Once the new project has been created the first step is to make sure the iAds Framework is included

    Original URL path: http://www.techotopia.com/index.php/Integrating_iAds_into_an_iOS_8_App_using_Swift (2016-02-13)
    Open archived version from archive

  • Integrating Maps into iOS 8 Applications using MKMapItem and Swift - Techotopia
    and the coordinates displayed on the console The above code is an example of forward geocoding in that coordinates are calculated based on a text address description Reverse geocoding as the name suggests involves the translation of geographical coordinates into a human readable address string Consider for example the following code let geoCoder CLGeocoder let newLocation CLLocation latitude 40 74835 longitude 73 984911 geoCoder reverseGeocodeLocation newLocation completionHandler placemarks AnyObject error NSError in if error nil println Geocode failed with error error localizedDescription if placemarks count 0 let placemark placemarks 0 as CLPlacemark let addressDictionary placemark addressDictionary let address addressDictionary kABPersonAddressStreetKey as NSString let city addressDictionary kABPersonAddressCityKey as NSString let state addressDictionary kABPersonAddressStateKey as NSString let zip addressDictionary kABPersonAddressZIPKey as NSString println address city state zip eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters In this case a CLLocation object is initialized with longitude and latitude coordinates and then passed through to the reverseGeocodeLocation method of a CLGeocoder object The method passes through to the completion handler an array of matching addresses in the form of CLPlacemark objects Each object contains an NSDictionary object which in turn contains the address information for the matching location Once again the code assumes a single match is contained in the array and uses the dictionary keys to access and display the address city state zip and country values The address dictionary keys follow the standard defined in the Address Property section of the iOS SDK Address Book Person reference When executed the above code results in output which reads 338 5th Ave New York New York 10001 United States It should be noted that the geocoding is not actually performed on the iOS device but rather on a server to which the device connects when a translation is required and the results subsequently returned when the translation is complete As such geocoding can only take place when the device has an active internet connection Creating MKPlacemark Instances Each location that is to be represented when a map is displayed using the MKMapItem class must be represented by an MKPlacemark object When MKPlacemark objects are created they must be initialized with the geographical coordinates of the location together with an NSDictionary object containing the address property information Continuing the example for the Empire State Building in New York an MKPlacemark object would be created as follows let coords CLLocationCoordinate2DMake 40 7483 73 984911 let address kABPersonAddressStreetKey 350 5th Avenue kABPersonAddressCityKey New York kABPersonAddressStateKey NY kABPersonAddressZIPKey 10118 kABPersonAddressCountryCodeKey US let place MKPlacemark coordinate coords addressDictionary address Whilst it is possible to initialize an MKPlacemark object passing through a nil value for the address dictionary this will result in the map appearing albeit with the correct location marked but it will be tagged as Unknown instead of listing the address The coordinates are however mandatory

    Original URL path: http://www.techotopia.com/index.php/Integrating_Maps_into_iOS_8_Applications_using_MKMapItem_and_Swift (2016-02-13)
    Open archived version from archive

  • An Example Swift iOS 8 MKMapItem Application - Techotopia
    address Text Field object and drag the resulting line to the area immediately beneath the class declaration directive in the Assistant Editor panel Upon releasing the line the configuration panel will appear Configure the connection as an Outlet named address and click on the Connect button Repeat these steps for the City State and Zip text fields connecting them to outlets named city state and zip respectively Ctrl click on the Get Directions button and drag the resulting line to a position beneath the new outlets declared in the Assistant Editor In the resulting configuration panel change the Connection type to Action and name the method getDirections On completion the beginning of the ViewController swift file should read as follows import UIKit class ViewController UIViewController IBOutlet weak var address UITextField IBOutlet weak var city UITextField IBOutlet weak var state UITextField IBOutlet weak var zip UITextField IBAction func getDirections sender AnyObject eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Converting the Destination using Forward Geocoding When the user touches the button in the user interface the getDirections method will be able to extract the address information from the text fields The objective will be to create an MKPlacemark object to contain this location As outlined in Integrating Maps into iOS 8 Applications using MKMapItem an MKPlacemark instance requires the longitude and latitude of an address before it can be instantiated The first step in the getDirections method is to perform a forward geocode translation of the address Before doing so however it is necessary to declare a property in the ViewController swift file in which to store these coordinates once they have been calculated This will in turn require that the CoreLocation framework be imported Now is also an opportune time to import the MapKit and AddressBook frameworks both of which will be required later in the chapter import UIKit import CoreLocation import AddressBook import MapKit class ViewController UIViewController IBOutlet weak var address UITextField IBOutlet weak var city UITextField IBOutlet weak var state UITextField IBOutlet weak var zip UITextField var coords CLLocationCoordinate2D Next select the ViewController swift file locate the getDirections method stub and modify it to convert the address string to geographical coordinates IBAction func getDirections sender AnyObject let geoCoder CLGeocoder let addressString address text city text state text zip text geoCoder geocodeAddressString addressString completionHandler placemarks AnyObject error NSError in if error nil println Geocode failed with error error localizedDescription else if placemarks count 0 let placemark placemarks 0 as CLPlacemark let location placemark location self coords location coordinate self showMap The steps used to perform the geocoding translation mirror those outlined in Integrating Maps into iOS 8 Applications using MKMapItem and Swift with one difference in that a method named showMap is called in the event that a successful translation took place All that remains therefore is

    Original URL path: http://www.techotopia.com/index.php/An_Example_Swift_iOS_8_MKMapItem_Application (2016-02-13)
    Open archived version from archive

  • Getting Location Information using the iOS 8 Core Location Framework in Swift - Techotopia
    to the current location data all the time that the application is running including when it is in the background Configuring the Desired Location Accuracy The level of accuracy to which location information is to be tracked is specified via the desiredAccuracy property of the CLLocationManager object It is important to keep in mind when configuring this property that the greater the level of accuracy selected the greater the drain on the device battery An application should therefore never request a greater level of accuracy than is actually needed A number of predefined constant values are available for use when configuring this property kCLLocationAccuracyBestForNavigation Uses the highest possible level of accuracy augmented by additional sensor data This accuracy level is intended solely for use when the device is connected to an external power supply kCLLocationAccuracyBest The highest recommended level of accuracy for devices running on battery power kCLLocationAccuracyNearestTenMeters Accurate to within 10 meters kCLLocationAccuracyHundredMeters Accurate to within 100 meters kCLLocationAccuracyKilometer Accurate to within one kilometer kCLLocationAccuracyThreeKilometers Accurate to within three kilometers The following code for example sets the level of accuracy for a location manager instance to best accuracy locationManager desiredAccuracy kCLLocationAccuracyBest Configuring the Distance Filter The default configuration for the location manager is to report updates whenever any changes are detected in the location of the device The distanceFilter property of the location manager allows applications to specify the amount of distance the device location must change before an update is triggered If for example the distance filter is set to 1000 meters the application will only receive a location update when the device travels 1000 meters or more from the location of the last update For example to specify a distance filter of 1500 meters locationManager distanceFilter 1500 0 The distance filter may be cancelled thereby returning to the default setting using the kCLDistanceFilterNone constant locationManager distanceFilter kCLDistanceFilterNone eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters The Location Manager Delegate Location manager updates and errors result in calls to two delegate methods defined within the CLLocationManagerDelegate protocol Templates for the two delegate methods that must be implemented to comply with this protocol are as follows func locationManager manager CLLocationManager didUpdateLocations locations AnyObject Handle location updates here func locationManager manager CLLocationManager didFailWithError error NSError Handle errors here Each time the location changes the didUpdateLocations delegate method is called and passed as an argument an array of CLLocation objects with the last object in the array containing the most recent location data Changes to the location tracking authorization status of an application are reported via a call to the optional didChangeAuthorizationStatus delegate method func locationManager manager CLLocationManager didChangeAuthorizationStatus status CLAuthorizationStatus App may no longer be authorized to obtain location information Check status here and respond accordingly Once a class has been configured to act as the delegate for

    Original URL path: http://www.techotopia.com/index.php/Getting_Location_Information_using_the_iOS_8_Core_Location_Framework_in_Swift (2016-02-13)
    Open archived version from archive



  •