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".
  • Drawing iOS 7 2D Graphics with Core Graphics - Techotopia
    form of CGFloat variables An additional C structure named CGPoint is used to contain both the x and y coordinates to specify a point on the display Similarly the CGSize structure stores two CGFloat values designating the width and height of an element on the screen Further the position and dimension of a rectangle can be defined using the CGRect structure which contains a CGPoint the location and CGSize the dimension of a rectangular area Of key importance when working with points and dimensions is that these values do not correspond directly to screen pixels In other words there is not a one to one correlation between pixels and points Instead the underlying framework decides based on a scale factor where a point should appear and at what size relative to the resolution of the display on which the drawing is taking place This enables the same code to work on both higher and lower resolution screens for example an iPhone 3GS screen and an iPhone 5S retina display without the programmer having to worry about it For more precise drawing requirements iOS version 4 and later allows the scale factor for the current screen to be obtained from UIScreen UIView UIImage and CALayer classes allowing the correlation between pixels and points to be calculated for greater drawing precision For iOS 3 or older the scale factor is always returned as 1 0 The Graphics Context Almost without exception all Quartz API function calls require that the graphics context be passed as an argument Each view has its own context which is responsible for performing the requested drawing tasks and subsequently rendering those drawings onto the corresponding view The graphics context can be obtained with a call to the UIGraphicsGetCurrentContext function which returns a result of type CGContextRef CGContextRef graphics context UIGraphicsGetCurrentContext 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 Working with Colors in Quartz 2D The Core Graphics CGColorRef data type is used to store colors when drawing with Quartz This data type holds information about the colorspace of the color RGBA CMYK or gray scale together with a set of component values that specify both the color and the transparency of that color For example the color red with no transparency would be defined with the RGBA components 1 0 0 0 0 0 1 0 A colorspace can be created via a Quartz API function call For example to create an RGB colorspace CGColorSpaceRef colorspace CGColorSpaceCreateDeviceRGB If the function fails to create a colorspace it will return a NULL value In the case of a successful creation the colorspace must be released when no longer required via a call to the CGColorSpaceRelease function CGColorSpaceRelease colorspace Gray scale and CMYK color spaces may similarly be created using the CGColorSpaceCreateDeviceGray and CGColorSpaceCreateDeviceCMYK functions respectively Once the colorspace

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


  • An iOS 7 Graphics Tutorial using Core Graphics and Core Image - Techotopia
    with the color red void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextMoveToPoint context 100 100 CGContextAddLineToPoint context 150 150 CGContextAddLineToPoint context 100 200 CGContextAddLineToPoint context 50 150 CGContextAddLineToPoint context 100 100 CGContextSetFillColorWithColor context UIColor redColor CGColor CGContextFillPath context The above code produces the following graphics on the device or simulator display when executed Figure 52 6 The following code draws a rectangle with a blue border and then once again fills the rectangular space with red void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGRect rectangle CGRectMake 60 170 200 80 CGContextAddRect context rectangle CGContextStrokePath context CGContextSetFillColorWithColor context UIColor redColor CGColor CGContextFillRect context rectangle When added to the example application the resulting display should appear as follows Figure 52 7 Drawing an Arc An arc may be drawn by specifying two tangent points and a radius using the CGContextAddArcToPoint function for example void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 100 100 CGContextAddArcToPoint context 100 200 300 200 100 CGContextStrokePath context The above code will result in the following graphics output Figure 52 8 Drawing a Cubic Bézier Curve A cubic Bézier curve may be drawn by moving to a start point and then passing two control points and an end point through to the CGContextAddCurveToPoint function void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 10 10 CGContextAddCurveToPoint context 0 50 300 250 300 400 CGContextStrokePath context The above code will cause the curve illustrated in Figure 52 9 to be drawn when compiled and executed in our example application Figure 52 9 Drawing a Quadratic Bézier Curve A quadratic Bézier curve is drawn using the CGContextAddQuadCurveToPoint function providing a control and end point as arguments having first moved to the start point void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 10 200 CGContextAddQuadCurveToPoint context 150 10 300 200 CGContextStrokePath context The above code when executed will display a curve that appears as illustrated in the following figure Figure 52 10 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 Dashed Line Drawing So far in this chapter we have performed all our drawing with a solid line Quartz also provides support for drawing dashed lines This is achieved via the Quartz CGContextSetLineDash function which takes as its arguments the following context The graphics context of the view on which the drawing is to take place phase A floating point value that specifies how far into the dash pattern the line starts lengths An array containing values for the lengths of the painted and unpainted sections of the line For example an array containing 5 and 6 would cycle through 5 painted unit spaces followed 6 unpainted unit spaces count A count of the number of items in the lengths array For example a 2 6 4 2 lengths array applied to a curve drawing of line thickness 5 0 will appear as follows Figure 52 11 The corresponding drawRect code that drew the above line reads as follows void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGContextSetLineWidth context 20 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGFloat dashArray 2 6 4 2 CGContextSetLineDash context 3 dashArray 4 CGContextMoveToPoint context 10 200 CGContextAddQuadCurveToPoint context 150 10 300 200 CGContextStrokePath context Drawing Shadows In addition to drawing shapes Core Graphics can also be used to create shadow effects This is achieved using the CGContextSetShadow function passing through a graphics context offset values for the position of the shadow relative to the shape for which the shadow is being drawn and a value specifying the degree of blurring required for the shadow effect Colored shadows may similarly be created using the CGContextSetShadowWithColor function which takes an additional argument in the form of a CGColor object The following code for example draws an ellipse with a shadow void drawRect CGRect rect CGContextRef context UIGraphicsGetCurrentContext CGSize myShadowOffset CGSizeMake 10 15 CGContextSaveGState context CGContextSetShadow context myShadowOffset 5 CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGRect rectangle CGRectMake 60 170 200 80 CGContextAddEllipseInRect context rectangle CGContextStrokePath context CGContextRestoreGState context When executed the above code will produce the effect illustrated in Figure 52 12 Figure 52 12 The color of the shadow could be changed for the sake of an example to red by calling CGContextSetShadowWithColor instead of CGContextSetShadow as follows CGContextSetShadowWithColor context myShadowOffset 5 UIColor redColor CGColor Drawing Gradients Gradients are implemented using the Core Graphics CGGradient class which provides support for linear radial and axial gradients Use of the CGGradient class essentially involves the specification of two or more colors together with a set of location values The location values are used to indicate the points at which the gradient should switch from one color to another as the gradient is drawn along an axis line where 0 0 represents the start of the axis and 1 0 the end point Assume for the purposes of an example that you wish to create a gradient that transitions through three different colors along the gradient axis with each color being given an equal amount of space within the gradient In this situation three locations would be specified The first would be 0 0 to represent the start of the gradient Two more locations would then need to be specified for the transition points to the remaining colors In order to equally divide the axis amongst the colors these would need to be set to 0 3333 and 0 6666 respectively Having configured a CGGraident instance a linear gradient is then drawn via a call to the CGContentDrawLinearGradient function passing through the colors locations and start and end points as arguments The following code for example draws a

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

  • Basic iOS 7 Animation using Core Animation - Techotopia
    the scale of a UIView object named myView by a factor of 2 in both height and width myView transform CGAffineTransformMakeScale 2 2 Similarly the UIView object may be rotated using the CGAffineTransformMakeRotation function which takes as an argument the angle in radians by which the view is to be rotated The following code for example rotates a view by 90 degrees myView transform CGAffineTransformMakeRotation 90 M PI 180 The key point to keep in mind with transformations is that they become animated effects when performed within an animation block The transformations evolve over the duration of the animation and follow the specified animation curve in terms of timing Combining Transformations Two transformations may be combined to create a single transformation effect via a call to the CGAffineTransformConcat function This function takes as arguments the two transformation objects that are to be combined The result may then be assigned to the transform property of the UIView object to be transformed The following code fragment for example both scales and rotates a UIView object named myView CGAffineTransform scaleTrans CGAffineTransformMakeScale 2 2 CGAffineTransform rotateTrans CGAffineTransformMakeRotation angle M PI 180 myView transform CGAffineTransformConcat scaleTrans rotateTrans Affine transformations offer an extremely powerful and flexible mechanism for creating animations and it is just not possible to do justice to these capabilities in a single chapter In order to learn more about affine transformations a good starting place is the Transforms chapter of Apple s Quartz 2D Programming Guide Creating the Animation Example Application The remainder of this chapter is dedicated to the creation of an iOS application intended to demonstrate the use of Core Animation The end result is a simple application on which a blue square appears When the user touches a location on the screen the box moves to that location Through the use of affine transformations the box will rotate 180 degrees as it moves to the new location whilst also changing in size Begin by launching Xcode and creating a new Single View Application for either the iPhone or iPad with both product and class prefix named Animate 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 Implementing the Interface File For the purposes of this application we will need a UIView to represent the blue square and variables to contain the rotation angle and scale factor by which the square will be transformed These need to be declared in the AnimateViewController h file as follows import UIKit UIKit h interface AnimateViewController UIViewController property nonatomic float scaleFactor property nonatomic float angle property strong nonatomic UIView boxView end Drawing in the UIView Having declared the UIView reference we now need to initialize an instance object and draw a blue square located at a specific location on the screen We also need to initialize our scaleFactor and angle variables and add boxView

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

  • IOS 7 UIKit Dynamics - An Overview - Techotopia
    dynamic items on which the behavior is to be imposed in this case two views named view1 and view2 UIGravityBehavior gravity UIGravityBehavior alloc initWithItems view1 view2 Once created the default vector can be changed if required at any time CGVector vector CGVectorMake 1 0 0 5 gravity setGravityDirection 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 view2 Similarly the entire behavior may be removed from the dynamic animator animator removeItem 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 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 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 UICollisionBehavior collision UICollisionBehavior alloc initWithItems 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 YES collision translatesReferenceBoundsIntoBoundary YES 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 UICollisionBehaviorModeItems Specifies that collisions only occur between items added to the collision behavior instance Boundary collisions are ignored UICollisionBehaviorModeBoundaries Configures the behavior to ignore item collisions recognizing only collisions with boundaries UICollisionBehaviorModeEverything 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 UICollisionBehaviorModeItems 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 54 2 to occur Figure 54 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

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

  • An iOS 7 UIKit Dynamics Tutorial - Techotopia
    initWithFrame frameRect blueBoxView backgroundColor UIColor blueColor frameRect CGRectMake 150 20 60 60 redBoxView UIView alloc initWithFrame frameRect redBoxView backgroundColor UIColor redColor self view addSubview blueBoxView self view addSubview redBoxView animator UIDynamicAnimator alloc initWithReferenceView self view UIGravityBehavior gravity UIGravityBehavior alloc initWithItems blueBoxView redBoxView CGVector vector CGVectorMake 0 0 1 0 gravity setGravityDirection vector animator addBehavior gravity 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 void viewDidLoad super viewDidLoad CGRect frameRect CGRectMake 10 20 80 80 blueBoxView UIView alloc initWithFrame frameRect blueBoxView backgroundColor UIColor blueColor frameRect CGRectMake 150 20 60 60 redBoxView UIView alloc initWithFrame frameRect redBoxView backgroundColor UIColor redColor self view addSubview blueBoxView self view addSubview redBoxView animator UIDynamicAnimator alloc initWithReferenceView self view UIGravityBehavior gravity UIGravityBehavior alloc initWithItems blueBoxView redBoxView CGVector vector CGVectorMake 0 0 1 0 gravity setGravityDirection vector UICollisionBehavior collision UICollisionBehavior alloc initWithItems blueBoxView redBoxView collision translatesReferenceBoundsIntoBoundary YES 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 void viewDidLoad super viewDidLoad UICollisionBehavior collision UICollisionBehavior alloc initWithItems blueBoxView redBoxView collision translatesReferenceBoundsIntoBoundary TRUE UIDynamicItemBehavior behavior UIDynamicItemBehavior alloc initWithItems blueBoxView behavior elasticity 0 5 animator addBehavior behavior animator addBehavior collision animator addBehavior gravity 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 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 UIKitDynamicsViewController h file some instance variables within which

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

  • An Introduction to iOS 7 Sprite Kit Programming - Techotopia
    range of additional possibilities in terms of the behavior that can be associated with a node When a node is assigned a physics body it will by default behave as though subject to the prevailing forces of gravity within the scene In addition the node can be configured to behave as though having a physical boundary This boundary can be defined as a circle a rectangle or a polygon of any shape Once a node has a boundary collisions between other nodes can be detected and the physics engine used to apply real world physics to the node such as causing it to bounce when hitting other nodes The use of contact bit masks can be employed to specify the types of nodes for which contact notification 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 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

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

  • An iOS 7 Sprite Kit Game Tutorial - Techotopia
    and a transition When implemented the SKAction will cause the node to fade away from view whilst an SKTransition 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 method to the WelcomeScene m file void touchesBegan NSSet touches withEvent UIEvent event SKNode welcomeNode self childNodeWithName welcomeNode if welcomeNode nil SKAction fadeAway SKAction fadeOutWithDuration 1 0 welcomeNode runAction fadeAway completion SKScene archeryScene ArcheryScene alloc initWithSize self size SKTransition doors SKTransition doorwayWithDuration 1 0 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 created in the createWelcomeNode method 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 SKNode welcomeNode self 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 SKAction 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 and an appropriately configured SKTransition object The transition to the new scene is then initiated SKAction fadeAway SKAction fadeOutWithDuration 1 0 welcomeNode runAction fadeAway completion SKScene archeryScene ArcheryScene alloc initWithSize self size SKTransition doors SKTransition doorwayWithDuration 1 0 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 the transition to the ArcheryScene takes effect Once again we are presented with a black scene that now needs to be implemented Preparing the Archery Scene The initial preparation of the ArcheryScene class largely mirrors that of the WelcomeScene Select the ArcheryScene m file and modify it as follows to add some private variables and implement the didMoveToView method and import the WelcomeScene h interface file import ArcheryScene h import WelcomeScene h interface ArcheryScene property BOOL sceneCreated property int score property int ballCount end implementation ArcheryScene void didMoveToView SKView view if self sceneCreated self score 0 self ballCount 40 self initArcheryScene self sceneCreated YES end The above code initializes the score to zero and the number of balls to be released to 40 before calling another method named initArcheryScene which now needs to be implemented as follows within the ArcheryScene m file void initArcheryScene self backgroundColor SKColor whiteColor self scaleMode SKSceneScaleModeAspectFill SKSpriteNode archerNode self createArcherNode archerNode position CGPointMake CGRectGetMinX self frame 55 CGRectGetMidY self frame self addChild archerNode Within this method the background color of the scene is set to white and the scene is scaled to fill the parent SKView area Next a method named createArcherNode is called Once implemented this method will create a new SKSpriteNode instance and assign a texture to it so that it appears as an archer with a bow and arrows ready to be launched at the targets The method then sets the position of the archer sprite so that it appears near the left hand edge of the scene before adding it as a child to the SKScene parent 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 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 ios7 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 Figure 57 5 Figure 57 5 By default the project should be configured to generate the texture atlas when the application is compiled Verify that this is the case by selecting the project name at the top of the project navigator panel followed by Build Settings in the main panel Enter spritekit deployment into the search field and make sure that the Enable Texture Atlas Generation option is set to YES Figure 57 6 for the SpriteKitDemo target Figure 57 6 Obtaining a Texture from the Atlas When the archer sprite is first initialized it needs to be textured with the archer001 png file from the texture atlas This takes place in the createArcherNode method which now needs to be implemented This method will create a new SKSpriteNode object and reference the archer001 png texture file located in the texture atlas Remaining within the ArcheryScene m file implement this method as follows SKSpriteNode createArcherNode SKSpriteNode archerNode SKSpriteNode alloc initWithImageNamed archer001 png archerNode name archerNode return archerNode Perform a test run of the application and verify that the archer sprite now appears at the side of the scene as illustrated in Figure

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

  • An iOS 7 Sprite Kit Collision Handling Tutorial - Techotopia
    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 m file to declare the class as the contact delegate void didMoveToView SKView view if self sceneCreated self score 0 self ballCount 40 self physicsWorld gravity CGPointVectori 0 1 0 self physicsWorld contactDelegate self self initArcheryScene self sceneCreated YES 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 h interface file needs to be modified to indicate that the class now implements the SKPhysicsContactDelegate protocol import SpriteKit SpriteKit h interface ArcheryScene SKScene SKPhysicsContactDelegate end Returning to the ArcheryScene m implement the didBeginContact method as follows void didBeginContact SKPhysicsContact contact SKSpriteNode firstNode secondNode firstNode SKSpriteNode contact bodyA node secondNode SKSpriteNode contact bodyB node if contact bodyA categoryBitMask arrowCategory contact bodyB categoryBitMask ballCategory CGPoint contactPoint contact contactPoint float contact y contactPoint y float target y secondNode position y float margin secondNode frame size height 2 25 if contact y target y margin contact y target y margin NSLog Hit self 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

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



  •