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".
  • IOS 9 UIKit Dynamics – An Overview - Techotopia
    to be imposed in this case two views named view1 and view2 let gravity UIGravityBehavior items view1 view2 Once created the default vector can be changed if required at any time let vector CGVectorMake 0 0 0 5 gravity gravityDirection vector Finally the behavior needs to be added to the dynamic animator instance animator addBehavior gravity At any point during the application lifecycle dynamic items may be added to or removed from the behavior gravity addItem view3 gravity removeItem view Similarly the entire behavior may be removed from the dynamic animator animator removeBehavior gravity When gravity behavior is applied to a view and in the absence of opposing behaviors the view will immediately move in the direction of the specified gravity vector In fact as currently defined the view will fall out of the bounds of the reference view and disappear This can be prevented by setting up a collision behavior Configuring Collision Behavior UIKit Dynamics is all about making items move on the device display When an item moves there is a high chance it will collide either with another item or with the boundaries of the encapsulating reference view As previously discussed in the absence of any form of collision behavior a moving item can move out of the visible area of the reference view Such a configuration will also cause a moving item to simply pass over the top of any other items that happen to be in its path Collision behavior defined using the UICollisionBehavior class allows for such collisions to behave in ways more representative of the real world Collision behavior can be implemented between dynamic items such that certain items can collide with others or within boundaries allowing collisions to occur when a designated boundary is reached by an item Boundaries can be defined such that they correspond to the boundaries of the reference view or entirely new boundaries can be defined using lines and Bezier paths As with gravity behavior a collision is generally created and initialized with an array object containing the items to which the behavior is to be applied For example let collision UICollisionBehavior items view1 view2 animator addBehavior collision As configured view1 and view2 will now collide when coming into contact with each other What then happens will be decided by the physics engine depending on the elasticity of the items and the angle and speed of the collision In other words the engine will animate the items so that they behave as if they were physical objects subject to the laws of physics By default an item under the influence of a collision behavior will collide both with other items in the same collision behavior set and also with any boundaries set up To declare the reference view as a boundary simply set the translatesReferenceBoundsIntoBoundary property of the behavior instance to true collision translatesReferenceBoundsIntoBoundary true A boundary inset from the edges of the reference view may be defined using the setsTranslateReferenceBoundsIntoBoundaryWithInsets method passing through the required insets as an argument in the form of a UIEdgeInsets object The collisionMode property may be used to change default collision behavior by assigning one of the following constants UICollisionBehaviorMode Items Specifies that collisions only occur between items added to the collision behavior instance Boundary collisions are ignored UICollisionBehaviorMode Boundaries Configures the behavior to ignore item collisions recognizing only collisions with boundaries UICollisionBehaviorMode Everything Specifies that collisions occur between items added to the behavior and all boundaries This is the default behavior The following code for example enables collisions only for items collision collisionMode UICollisionBehaviorMode Items In the event that an application needs to react to a collision simply declare a class instance that conforms to the UICollisionBehaviorDelegate class by implementing the following methods and assign it as the delegate for the UICollisionBehavior object instance collisionBehavior beganContactForItem withBoundaryIdentifier atPoint collisionBehavior beganContactForItem withItem atPoint collisionBehavior endedContactForItem withBoundaryIdentifier collisionBehavior endedContactForItem withItem When implemented the application will be notified when collisions begin and end Note that in most cases the delegate methods will be passed information about the collision such as the location and the items or boundaries involved In addition aspects of the collision behavior such as friction and the elasticity of the colliding items such that they bounce on contact may be configured using the UIDynamicBehavior class This class will be covered in detail later in this chapter Configuring Attachment Behavior As the name suggests the UIAttachmentBehavior class allows dynamic items to be configured such that they behave as if attached These attachments can take the form of two items attached to each other or an item attached to an anchor point at specific coordinates within the reference view The attachment can take the form of an imaginary piece of cord that does not stretch or a spring attachment with configurable damping and frequency properties that control how bouncy the attached item is in response to motion By default the attachment point within the item itself is positioned at the center of the view This can however be changed to a different position causing the real world behavior outlined in Figure 65 2 to occur Figure 65 2 In general the physics engine will simulate animation to match what would typically happen in the real world As illustrated above the item will tilt when not attached in the center In the event that the anchor point moves the attached view will also move Depending on the motion the item will swing in a pendulum motion and assuming appropriate collision behavior configuration bounce off any boundaries it collides with as it swings As with all UIKit Dynamics behavior all the work to achieve this is performed for us by the physics engine The only effort required by the developer is to write a few lines of code to set up the behavior before adding it to the dynamic animator instance The following code for example sets up an attachment between two dynamic items let attachment UIAttachmentBehavior item view1 attachedToItem view2 animator addBehavior attachment The

    Original URL path: http://www.techotopia.com/index.php/IOS_9_UIKit_Dynamics_%E2%80%93_An_Overview (2016-02-13)
    Open archived version from archive


  • An iOS 9 UIKit Dynamics Tutorial - Techotopia
    blueColor frameRect CGRectMake 150 20 60 60 redBoxView UIView frame frameRect redBoxView backgroundColor UIColor redColor self view addSubview blueBoxView self view addSubview redBoxView animator UIDynamicAnimator referenceView self view let gravity UIGravityBehavior items blueBoxView redBoxView let vector CGVectorMake 0 0 1 0 gravity gravityDirection vector animator addBehavior gravity eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 Compile and run the application once again Note that after launching the gravity behavior causes the views to fall from the top of the reference view and out of view at the bottom of the device display In order to keep the views within the bounds of the reference view it is necessary to set up a collision behavior Implementing Collision Behavior In terms of collision behavior the example requires that collisions occur both when the views impact each other and when making contact with the boundaries of the reference view With these requirements in mind the collision behavior needs to be implemented as follows override func viewDidLoad super viewDidLoad var frameRect CGRectMake 10 20 80 80 blueBoxView UIView frame frameRect blueBoxView backgroundColor UIColor blueColor frameRect CGRectMake 150 20 60 60 redBoxView UIView frame frameRect redBoxView backgroundColor UIColor redColor self view addSubview blueBoxView self view addSubview redBoxView animator UIDynamicAnimator referenceView self view let gravity UIGravityBehavior items blueBoxView redBoxView let vector CGVectorMake 0 0 1 0 gravity gravityDirection vector let collision UICollisionBehavior items blueBoxView redBoxView collision translatesReferenceBoundsIntoBoundary true animator addBehavior collision animator addBehavior gravity Running the application should now cause the views to stop at the bottom edge of the reference view and bounce slightly after impact The amount by which the views bounce in the event of a collision can be changed by creating a UIDynamicBehavior class instance and changing the elasticity property The following code for example changes the elasticity of the blue box view so that it bounces to a higher degree than the red box override func viewDidLoad super viewDidLoad let collision UICollisionBehavior items blueBoxView redBoxView collision translatesReferenceBoundsIntoBoundary true let behavior UIDynamicItemBehavior items blueBoxView behavior elasticity 0 5 animator addBehavior behavior animator addBehavior collision animator addBehavior gravity Attaching a View to an Anchor Point So far in this tutorial we have added some behavior to the application but have not yet implemented any functionality that connects UIKit Dynamics to user interaction In this section however the example will be modified such that an attachment is created between the blue box view and the point of contact of a touch on the screen This anchor point will be continually updated as the user s touch moves across the screen thereby causing the blue box to follow the anchor point The first step in this process is to declare within the ViewController swift file some instance variables within which to store both the current location of the anchor point and a reference to a

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

  • An Introduction to iOS 9 Sprite Kit Programming - Techotopia
    bit masks can be employed to specify the types of nodes for which contact notification is required eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 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 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

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

  • An iOS 9 Sprite Kit Level Editor Game Tutorial - Techotopia
    the resulting General settings panel change the device orientation settings so that only the Landscape options are selected Figure 68 3 Modifying the GameScene SpriteKit Scene File As previously outlined Xcode has provided a SpriteKit scene file GameScene sks for a scene named GameScene together with a corresponding class declaration contained within the GameScene swift file The next task is to repurpose this scene to act as the welcome screen for the game Begin by selecting the GameScene sks file so that it loads into the SpriteKit Level Editor as shown in Figure 68 4 Figure 68 4 When working with the Level Editor to design SpriteKit scenes there are a number of key areas of importance each of which has been labelled in the above figure A Scene Canvas This is the canvas onto which nodes may be placed positioned and configured B Attribute Inspector Panel This panel provides a range of configuration options for the currently selected item in the editor panel This allows SKNode and SKAction objects to be customized from within the editor environment C Object Library The Object Library panel contains a range of node and effect types that can be dragged and dropped onto the scene Clicking on the far right button in the Object Library toolbar displays the Media Library containing items such as textures for sprites At this stage in the tutorial the only item in the Media Library is the Spaceship texture D Simulate Layout Button Toggles between the editor s simulation and layout editting modes Simulate mode provides a useful mechanism for previewing the scene behavior without the need to compile and run the application E Zoom Buttons Buttons to zoom in and out of the scene canvas F Live Editor The live editor allows actions and animations to be placed within a timeline and simulated within the editor environment It is possible for example to add animation and movement actions within the live editor and play them back live within the scene canvas G Timeline View Slider Pans back and forth through the view of the live editor timeline H Playback Speed When in Animation mode this control adjusts the playback speed of the animations and actions contained within the live editor panel With the scene selected in the scene canvas click on the Color swatch in the Attribute Inspector panel and use the color selection dialog to change the scene color to a shade of green From within the Object Library panel locate the Label node object and drag and drop an instance onto the center of the scene canvas With the label still selected change the Text property in the inspector panel to read SpriteKitDemo Tap Screen to Play Remaining within the inspector panel click on the T next to the font name and use the font selector to assign a 24 point Marker Felt Wide font to the label from the Fun font category Finally set the Name property for the label node to welcomeNode Save the scene file before proceeding With these changes complete the scene should resemble that of Figure 68 5 Figure 68 5 Creating the Archery Scene As previously outlined the first scene of the game is a welcome screen on which the user will tap to begin playing within a second scene Add a new class to the project to represent this second scene by selecting the File New File menu option In the file template panel make sure that the iOS Source option is selected in the left hand panel and that the Cocoa Touch Class template is selected in the main panel Click on the Next button and configure the new class to be a subclass of SKScene named ArcheryScene Click on the Next button and create the new class file within the project folder The new scene class will also require a corresponding SpriteKit scene file Select File New File once again this time selecting the iOS Resource option from the left hand panel and SpriteKit Scene from the main panel Figure 68 6 Click Next name the scene ArcheryScene and click on the Create button to add the scene file to the project Figure 68 6 Edit the newly added ArcheryScene swift file and modify it to import the SpriteKit Framework as follows import UIKit import SpriteKit class ArcheryScene SKScene Transitioning to the Archery Scene Clearly having instructed the user to tap the screen in order to play the game some code now needs to be written to make this happen This behavior will be added by implementing the touchesBegan method in the GameScene class Rather than move directly to ArcheryScene however some effects will be added in the form of an action and a transition When implemented the SKAction will cause the node to fade away from view whilst 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 asset catalog 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 code iOS9BookSamples zip Within the code sample archive locate the folder named sprite images 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 select the Assets xcassets catalog file in the Project Navigator to display the image assets panel Locate the archer atlas folder in a Finder window and drag and drop it onto the asset catalog panel so that it appears beneath the existing AppIcon entry as shown in the following figure Figure 68 7 Before proceeding be sure to select and delete the SpaceShip image set from the catalog eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 68 8 Figure 68 8 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 68 9 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 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 Attribute Inspector panel until the Physics Definition section comes into view Using the Body Type menu change the setting to Alpha mask Figure 68 10 Once the change has been made note that the sprite node is now outlined by a physical body shape matching the texture image Figure 68 11 Before proceeding with the next phase of the development process test that the scene behaves as required by clicking on the Animate 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 Layout button to leave simulation mode select the archer sprite and within the Physical Definition section turn the Pinned option on and the Dynamic Allows Rotation and Affected by Gravity options off Re run the animation to verify that the archer sprite now remains in place Save the scene file before proceeding Preparing the Archery Scene Select the ArcheryScene swift file and modify it as follows to add some private variables and implement the didMoveToView method import UIKit import SpriteKit class ArcheryScene SKScene var score 0 var ballCount 20 override func didMoveToView view SKView self initArcheryScene The above code calls another method named initArcheryScene which now needs to be implemented as follows within the ArcheryScene swift file ready for code which will be added later in the chapter func initArcheryScene Preparing the Animation Texture Atlas When the user touches the screen the archer sprite node will launch an arrow across the scene For the purposes of this example we want the loading and shooting of the arrow by the sprite character to be animated The texture atlas already contains the animation frames needed to implement this named sequentially from archer001 png through to archer012 png so the next step is to create an action to animate this sequence of frames One option would be to write some code to perform this task A much easier option however is to create an animation action using the SpriteKit Live Editor Begin by selecting the ArcheryScene sks file so that it loads into the editor Once loaded the first step is to add an AnimateWithTextures action within the timeline of the live editor panel Within the Object Library panel scroll down the list of objects until the AnimateWithTextures Action object comes into view Once located drag and drop an instance of the object onto the live editor timeline for the archerNode as indicated in Figure 68 12 Figure 68 12 With the animation action added to the timeline the action now needs to be configured with the texture sequence to be animated With the newly added action selected in the timeline switch the Object Library panel into Media Library mode so that the archer texture images are listed Use the Command A keyboard sequence to select all of the images in the library and then drag and drop those images onto the Textures box in the Animate with Textures attributes panel as shown in Figure 68 13 Figure 68 13 Test the animation by clicking on the Animate button Note that it is possible to move back and forth through the animation sequences by moving the position marker referenced by the arrow in Figure 68 14 Figure 68 14 Compile and run the app and tap on the screen to enter the archery scene On appearing the animation sequence will execute once In practice the animation sequence should only run when the user taps on the screen to launch an arrow Having this action within the timeline therefore does not provide the required behavior for the game Instead the animation action needs to be converted to a named action reference placed in an action file and triggered from within the touchesBegan method of the archer scene class Creating the Named Action Reference With the ArcherScene sks file loaded into the level editor Ctrl click on the Animate with Textures action in the timeline and select the Convert to Reference option from the popup menu Figure 68 15 In the Create Action panel name the action animateArcher and leave the File menu set to Create New File Click on the Create button and in the Save As panel navigate to the SpriteKitDemo subfolder of the main project folder and enter ArcherActions into the Save As field before clicking on Create Since the animation action is no longer required in the timeline of the archer scene select the ArcherScene sks file Ctrl click on the Animate with Texture action in the timeline and select Delete from the menu Testing Actions in an Action File The separation of an action from a scene raises the question of how the action can be tested within the live editor environment In fact this can easily be achieved using the Xcode action editor by temporarily assigning the action to a scene and a specific node To see this in practice select the newly created ArcherActions sks file to load it into the Action Editor panel When the editor first loads the action is not associated with any particular scene To associate the action with a scene click on the Select button and select the ArcheryScene sks file from the list of scenes in the project Figure 68 16 Once the archery scene file has been selected the archer node should appear with in the scene canvas Select this node and refer to the Attributes Inspector panel where the Preview Actions list should be visible Click on the button and in the popup panel select the archerAnimation action before clicking on the Assign button to assign the action to the node Figure 68 17 Test the action by clicking on the triangular play button located in the lower left hand corner of the scene canvas Once clicked the scene should animate through the texture sequence of the archer loading and shooting the arrow Triggering the Named Action from the Code With the previous steps completed the project now has a named action named animateArcher which can be triggered each time the screen is tapped by adding some code to the touchesBegan method of the ArcheryScene swift file With this file selected in the Project Navigator panel implement this method as follows override func touchesBegan touches Set UITouch withEvent event UIEvent if let archerNode self childNodeWithName archerNode let animate SKAction named animateArcher archerNode runAction animate Run the application and touch the screen within the Archery Scene Each time a touch is detected the archer sprite will run through the animation sequence of shooting an arrow eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 Creating the Arrow Sprite Node At this point in the tutorial the archer sprite node goes through an animation sequence of loading and shooting an arrow but no actual arrow is being launched across the scene In order to implement this a new sprite node needs to be added to the ArcheryScene This node will be textured with an image of an arrow and will be placed to the right of the archer sprite at the end of the animation sequence A physics body will be associated with the arrow and an impulse force applied to it to propel it across the scene as though shot by the archer s bow To demonstrate the alternative to using the action and live editors this task will be performed entirely in code Begin by locating the ArrowTexture png file in the sprite images

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

  • An iOS 9 Sprite Kit Collision Handling Tutorial - Techotopia
    the game logic needs to be notified when this happens A collision involves contact between two nodes that cannot occupy the same space in the scene In such a situation and subject to prevailing physics body properties the two nodes will typically bounce away from each other The type of contact for which notification is required is specified by assigning contact and collision bit masks to the physics body of one of the node categories involved in the contact For the purposes of this example we will specify that notification is required for both contact and collision between the arrow and ball categories func createArrowNode SKSpriteNode let archerNode self childNodeWithName archerNode let archerPosition archerNode position let archerWidth archerNode frame size width let arrow SKSpriteNode imageNamed ArrowTexture png arrow position CGPointMake archerPosition x archerWidth archerPosition y arrow name arrowNode arrow physicsBody SKPhysicsBody rectangleOfSize arrow frame size arrow physicsBody usesPreciseCollisionDetection true arrow physicsBody categoryBitMask arrowCategory arrow physicsBody collisionBitMask arrowCategory ballCategory arrow physicsBody contactTestBitMask arrowCategory ballCategory return arrow Implementing the Contact Delegate When the Sprite Kit physics system detects a collision or contact for which appropriate masks have been configured it needs a way to notify the application code that such an event has occurred It does this by calling methods on the class instance that has been registered 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 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 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 print 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

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

  • An iOS 9 Sprite Kit Particle Emitter Tutorial - Techotopia
    The birthrate defines the rate at which new particles are emitted by the node The greater the value the faster new particles are generated though it is recommended that the minimum number of particles needed to achieve the desired effect be used to avoid performance degradation The total number of particles to be emitted may also be specified A value of zero causes particles to be emitted indefinitely If a limit is specified the node will stop emitting particles when 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 eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 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 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 70 3 for example shows a color ramp with three color transitions specified Figure 70 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 is performed by adjusting the speed property Particle Blend Mode The Blend Mode property governs the way in which particles blend with other images colors and graphics in Sprite Kit game scenes Options available are as follows Alpha Blends transparent pixels in the particle with the background Add Adds the particle pixels to the corresponding background image pixels Subtract Subtracts the particle pixels from the corresponding background image pixels Multiply Multiplies the particle pixels by the corresponding background image pixels Results in a darker particle effect MultiplyX2 Creates a darker particle effect than the standard Multiply mode Screen Inverts pixels multiplies and inverts a second time Results in lighter particle effects Replace No blending with the background Only the particle s colors are used Experimenting with the Particle Emitter Editor Creating compelling special effects with the particle emitter is largely a case of experimentation As an example of adapting a template effect for another purpose we will now modify the fire effect in the RocketFlame sks file so that instead of resembling a camp fire it could instead be attached to the back of a sprite to represent the flame of a rocket launching into space Within Xcode select the previously created RocketFlame sks file so that it loads into the Particle Emitter Editor The animation should appear and resemble a camp fire as illustrated in Figure 70 2 1 The first step in modifying the effect is to change the angle of the flames so that they burn downwards To achieve this change the Start property of the Angle setting to 270 degrees The fire should now be inverted 2 Change the X value of the Position Range property to 5 so that the flames become narrower and more intense 3 Increase the Start value of the Speed property to 450 4 Change the Lifetime start property to 7 The effect now resembles the flames a user might expect to see shooting out of the back of a rocket against a nighttime sky Figure 70 4 Note also that the effects of motion of the emitter node may be simulated by clicking and dragging the node around the canvas Figure 70 4 Bursting a Ball using Particle Emitter Effects The final task is to update the SpriteKitDemo game so that the balls burst when they are hit by an arrow shot by the archer sprite The particles for the bursting ball will be represented by the BallFragment png file located in the sample code download archive in the sprite images folder

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

  • An iOS 9 MapKit Flyover Tutorial - Techotopia
    Building facing East at a pitch of 30 degrees and assigns it to the camera property of a map view object named mapView let distance CLLocationDistance 650 let pitch CGFloat 30 let heading 90 0 mapView mapType SatelliteFlyover let coordinate CLLocationCoordinate2D latitude 40 7484405 longitude 73 9856644 let camera MKMapCamera lookingAtCenterCoordinate coordinate fromDistance distance pitch pitch heading heading mapView camera camera An MKMapKit Flyover Example The example project implemented in the remainder of this chapter will demonstrate the use of the MKMapCamera class to display a 3D Satellite Flyover rendering of the Empire State Building The camera view will then slowly rotate around the building using an animation effect Begin the project by launching Xcode and creating a new Universal iOS application project named FlyoverDemo using the Single View Application template with the Swift language option selected eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 User Interface The first step in this tutorial is to design the user interface This is a very simple user interface consisting of an MKMapView instance and a single Button object Select the Main storyboard file and drag and drop components from the Object Library View Utilities Show Object Library onto the view Position and size the components and set the text on the button so that the user interface resembles that shown in Figure 83 3 Figure 83 3 Select the Map View object in the scene layout display the Resolve Auto Layout Issues menu and select the Reset to Suggested Constraints option listed under All Views in View Controller Display the Assistant Editor panel and establish an outlet connection from the Map View object named mapView With the Assistant Editor still displayed establish an action connection from the button object to a method named animateCamera With the connections configured further modify the ViewController swift file to import the MapKit framework as follows and to declare constants for the camera settings and a variable to contain a reference to the MKMapCamera object import UIKit import MapKit class ViewController UIViewController IBOutlet weak var mapView MKMapView let distance CLLocationDistance 650 let pitch CGFloat 65 let heading 0 0 var camera MKMapCamera override func viewDidLoad super viewDidLoad IBAction func animateCamera sender AnyObject override func didReceiveMemoryWarning super didReceiveMemoryWarning Dispose of any resources that can be recreated eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 Configuring the Map View and Camera The next step is to configure the MKMapView instance to display the map in SatelliteFlyover mode and then create and initialize the MKMapCamera object so that it is positioned above and to the side of the Empire State Building Once the camera has been initialized it

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

  • An Introduction to Extensions in iOS 9 - Techotopia
    make sharing easier for developers hosting their own sharing and social sites Share extensions appear within the activity view controller panel which is displayed when the user taps the Share button from within a host app Figure 84 2 for example shows a Share extension named Share It listed alongside the built in Twitter Facebook and Flickr share options within the activity view controller Figure 84 2 eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials 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 Share extensions can make use of the SLComposeServiceViewController class to implement the interface for posting content This displays a view Figure 84 3 containing a preview of the information to be posted and provides the ability to modify the content prior to posting it For more complex requirements a custom user interface can be designed using Interface Builder Figure 84 3 The actual mechanics of posting the content will be dependent on the way in which the target platform works Action Extension The Action extension point enables extensions to be created that fall into the Action category Action extensions allow the content within a host app to be transformed or viewed in a different way As with Share extensions Action extensions are accessed from the activity view controller via the Share button Figure 84 4 for example shows an example Action extension named Translator in the activity view controller of the iOS Notes app Figure 84 4 Action extensions are context sensitive in that they only appear as an option when the type of content in the host app matches one of the content types for which the extension has declared support An Action extension that works with images for example will not appear in the activity view controller panel for a host app that is displaying text based content Action extensions are covered in detail in the chapters entitled Creating an iOS 9 Action Extension and Receiving Data from an iOS 9 Action Extension Photo Editing Extension The Photo Editing extension point allows the photo editing capabilities of an application to be accessed from within the built in iOS Photos app Photo Editing extensions are displayed when the user selects an image in the Photos app chooses the edit option and taps on the button in the top left hand corner of the Photo editing screen Figure 84 5 shows the Photos app displaying two Photo Editing extension options Figure 84 5 Photo Editing Extensions are covered in detail in the chapter entitled Creating an iOS 9 Photo Editing Extension Document Provider Extension The Document Provider extension makes it possible for a containing app to act as a document repository for other applications running on the device Depending on the level of support implemented in the extension host apps can import export open and move documents to and from the storage repository provided by

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



  •