7
Extracted from: Build iOS Games with Sprite Kit Unleash Your Imagination in Two Dimensions This PDF file contains pages extracted from Build iOS Games with Sprite Kit, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit http://www.pragprog.com. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printed versions; the content is otherwise identical. Copyright © 2014 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina

Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

Extracted from:

Build iOS Games with Sprite KitUnleash Your Imagination in Two Dimensions

This PDF file contains pages extracted from Build iOS Games with Sprite Kit,published by the Pragmatic Bookshelf. For more information or to purchase a

paperback or PDF copy, please visit http://www.pragprog.com.

Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printed versions; the

content is otherwise identical.

Copyright © 2014 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,

without the prior consent of the publisher.

The Pragmatic BookshelfDallas, Texas • Raleigh, North Carolina

Page 2: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement
Page 3: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

Build iOS Games with Sprite KitUnleash Your Imagination in Two Dimensions

Jonathan PennJosh Smith

The Pragmatic BookshelfDallas, Texas • Raleigh, North Carolina

Page 4: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-marks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team createbetter software and have more fun. For more information, as well as the latest Pragmatictitles, please visit us at http://pragprog.com.

The team that produced this book includes:

Rebecca Gulick (editor)Potomac Indexing, LLC (indexer)Cathleen Small (copyeditor)David J Kelly (typesetter)Janet Furlow (producer)Ellie Callahan (support)

For international rights, please contact [email protected].

Copyright © 2014 The Pragmatic Programmers, LLC.All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form, or by any means, electronic, mechanical, photocopying,recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.ISBN-13: 978-1-94122-210-2Encoded using the finest acid-free high-entropy binary digits.Book version: P1.0—July 2014

Page 5: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

Playing Sound Effects in the SceneWhen you’re ready to implement one-shot sound effects in your game, there’sno need to reach for the iOS audio APIs. Sprite Kit gives us everything weneed with a special sound action. Let’s add some shooting and explosioneffects for the collisions.

First, we need to make sure the sound files are in the Xcode project. If you’recreating the project yourself on the fly, drag the obstacleExplode.m4a, shipEx-plode.m4a, and shoot.m4a files into the Xcode file sidebar. Make sure theSpaceRun target checkbox is checked, like in Figure 7, Dragging and droppingfiles into the Xcode project, on page ?. Xcode doesn’t always check that boxfor you for some file types.

Next, we need three properties on our scene object to hold the sound actions.Let’s add these property definitions to the class extension of RCWMyScene.m.

02-Actions/step06/SpaceRun/RCWMyScene.m@interface RCWMyScene ()@property (nonatomic, weak) UITouch *shipTouch;@property (nonatomic) NSTimeInterval lastUpdateTime;@property (nonatomic) NSTimeInterval lastShotFireTime;@property (nonatomic, strong) SKAction *shootSound;➤

@property (nonatomic, strong) SKAction *shipExplodeSound;➤

@property (nonatomic, strong) SKAction *obstacleExplodeSound;➤

@end

We’re creating these properties because loading a sound file into an actiontakes a moment and can introduce a brief pause in the gameplay the firsttime the sound is loaded and cached. We want to preload the sounds ourselvesto get the delay out of the way up front during initialization, and we’ll keep astrong reference to the actions so they aren’t purged from Sprite Kit’s soundcache for any reason. We know we always need these sounds available forthis scene.

With the properties in place, create the sound actions and assign them to theproperties in the -initWithSize: method.

02-Actions/step06/SpaceRun/RCWMyScene.m- (id)initWithSize:(CGSize)size{

if (self = [super initWithSize:size]) {self.backgroundColor = [SKColor blackColor];NSString *name = @"Spaceship.png";SKSpriteNode *ship = [SKSpriteNode spriteNodeWithImageNamed:name];ship.position = CGPointMake(size.width/2, size.height/2);ship.size = CGSizeMake(40, 40);

• Click HERE to purchase this book now. discuss

Page 6: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

ship.name = @"ship";[self addChild:ship];

self.shootSound =➤

[SKAction playSoundFileNamed:@"shoot.m4a" waitForCompletion:NO];➤

self.obstacleExplodeSound =➤

[SKAction playSoundFileNamed:@"obstacleExplode.m4a"➤

waitForCompletion:NO];➤

self.shipExplodeSound =➤

[SKAction playSoundFileNamed:@"shipExplode.m4a" waitForCompletion:NO];➤

}return self;

}

The -playSoundFileName:waitForCompletion: method takes a name for a sound file inthe bundle for the first parameter. This can be any file that the iOS soundAPIs understand, such as MP3, M4A, AIF, CAF, WAV, and more. While thereare performance considerations when choosing sound-file types for the low-level iOS APIs, we don’t have to worry about that for short one-shot sounds.M4A files are small, high quality, and quite sufficient for our use.

Notice how we set the waitForCompletion: parameter to NO for all these actions.This controls how the action fits in with the rest of the actions playing on thenode. In this particular case, it doesn’t really matter because we’re justplaying the sounds by themselves. But if they were part of an action sequence,then setting waitForCompletion: to YES would pause the sequence until the soundfile stopped playing. That can be useful if you are chaining sounds togetherone after the other for effect. But for self-contained sound actions like this,we set the parameter to NO so that Sprite Kit knows we just want to triggerthe sound and move on immediately.

With the sound actions initialized and ready to go, we’ll add two lines to our-checkCollisions method to run the sound actions on the scene when either theship or an obstacle explodes.

02-Actions/step06/SpaceRun/RCWMyScene.m[selfenumerateChildNodesWithName:@"obstacle"usingBlock:^(SKNode *obstacle, BOOL *stop) {

if ([ship intersectsNode:obstacle]) {self.shipTouch = nil;[ship removeFromParent];[obstacle removeFromParent];[self runAction:self.shipExplodeSound];➤

}[selfenumerateChildNodesWithName:@"photon"usingBlock:^(SKNode *photon, BOOL *stop) {

• 6

• Click HERE to purchase this book now. discuss

Page 7: Build iOS Games with Sprite Kit - Pragmatic Bookshelfmedia.pragprog.com/titles/pssprite/sound.pdf · 2014. 7. 22. · Playing Sound Effects in the Scene When you’re ready to implement

if ([photon intersectsNode:obstacle]) {[photon removeFromParent];[obstacle removeFromParent];[self runAction:self.obstacleExplodeSound];➤

*stop = YES;}

}];}];

We’re passing the sound action we want to play to the -runAction: method onthe scene. That’s all it takes to play a sound!

Notice that we’re playing the sounds on the scene itself, and not on the othernodes. That’s because we’re removing those nodes from the scene, and anynode that doesn’t belong on an active scene doesn’t run its actions.

Let’s do the same thing to play a sound every time we shoot our photontorpedoes.

02-Actions/step06/SpaceRun/RCWMyScene.m- (void)shoot{

SKNode *ship = [self childNodeWithName:@"ship"];

SKSpriteNode *photon = [SKSpriteNode spriteNodeWithImageNamed:@"photon"];photon.name = @"photon";photon.position = ship.position;

[self addChild:photon];SKAction *fly = [SKAction moveByX:0

y:self.size.height+photon.size.heightduration:0.5];

SKAction *remove = [SKAction removeFromParent];SKAction *fireAndRemove = [SKAction sequence:@[fly, remove]];[photon runAction:fireAndRemove];

[self runAction:self.shootSound];➤

}

We’re passing the sound action stored in the self.shootSound property to the-runAction: method on the scene.

Playing simple one-shot sounds is so easy with Sprite Kit. You can find outmore about supported file formats in Apple’s documentation.4

You’re almost finished learning about node actions. For our last trick, we’llimplement power-ups for the player’s weapon.

4. https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/Usin-gAudio.html

• Click HERE to purchase this book now. discuss

Playing Sound Effects in the Scene • 7