-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathObjManager.m
1114 lines (855 loc) · 36 KB
/
ObjManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ObjManager.m
// Papercut
//
// Created by Jeff Bumgardner on 9/16/12.
// Copyright (c) 2012 Jeff Bumgardner. All rights reserved.
//
// Class that manages objects at a high level (the "world"),
// including sounds, world timers and world states
// Also pauses / resumes animations when app enters background
//
#import "ObjManager.h"
#import "Paper.h"
#import "Border.h"
#import "Vector2D.h"
#import "Messenger.h"
#import "Behavior.h"
#import "Timer.h"
static ObjManager *mySharedWorld = nil;
@implementation ObjManager
@synthesize objects, objects_coll, objects_pinch, objects_shake, objects_neighbors, objects_wiggle;
@synthesize objects_sounds, objects_sounds_splash;
@synthesize queue_shake, queue_clean, queue_view, accel, accelX, osFlags, world_timers;
@synthesize spawnID, timerID, border, borderWidth, borderBound, viewWidth, viewHeight;
@synthesize fps, bounceOffset, gravityFilter, elapsedTime, cleanMin, cleanMax;
@synthesize maxNotes, numObjects;
+ (id) theWorld {
@synchronized([ObjManager class]) {
if (!mySharedWorld) { mySharedWorld = [[self alloc] initWithBlank]; }
}
return mySharedWorld;
}
+ (id) alloc
{
@synchronized([ObjManager class])
{
NSAssert(mySharedWorld == nil, @"Attempted to allocate a second instance of the ObjManager.");
mySharedWorld = [super alloc];
return mySharedWorld;
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (ObjManager*) initWithBlank {
//self = [super init];
if (self = [super init]) {
objects = [[NSMutableDictionary alloc] init];
objects_coll = [[NSMutableDictionary alloc] init];
objects_pinch = [[NSMutableDictionary alloc] init];
objects_shake = [[NSMutableDictionary alloc] init];
objects_wiggle = [[NSMutableDictionary alloc] init];
objects_sounds = [[NSMutableDictionary alloc] init];
objects_sounds_splash = [[NSMutableDictionary alloc] init];
queue_view = [[NSMutableDictionary alloc] init];
queue_shake = [[NSMutableArray alloc] init];
queue_clean = [[NSMutableArray alloc] init];
world_timers = [[NSMutableDictionary alloc] init];
spawnID = 100; // start of counter for dynamically spawned object IDs
timerID = 1;
viewWidth = 0;
viewHeight = 0;
cleanMin = 4;
cleanMax = 10;
numObjects = 0;
[self turnOffAllStates];
_optInteract = YES;
_optSound = YES;
// Accelerometer
#ifdef ACCEL_ON
accel = [UIAccelerometer sharedAccelerometer];
#endif
accelX = 0.0;
// Audio FX setup
// Use 3 different audio players so sounds can overlap
//
NSString *fxFilePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat:@"FX_Pop2"]
ofType: [NSString stringWithFormat:@"wav"]];
NSURL *fxFileURL = [[NSURL alloc] initFileURLWithPath: fxFilePath];
_fx_audio01 = [[AVAudioPlayer alloc] initWithContentsOfURL:fxFileURL error:nil];
[_fx_audio01 setDelegate:self];
[_fx_audio01 prepareToPlay];
fxFilePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat:@"FX_Start"]
ofType: [NSString stringWithFormat:@"wav"]];
fxFileURL = [[NSURL alloc] initFileURLWithPath: fxFilePath];
_fx_audio02 = [[AVAudioPlayer alloc] initWithContentsOfURL:fxFileURL error:nil];
[_fx_audio02 setDelegate:self];
[_fx_audio02 prepareToPlay];
fxFilePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat:@"FX_Pop1"]
ofType: [NSString stringWithFormat:@"wav"]];
fxFileURL = [[NSURL alloc] initFileURLWithPath: fxFilePath];
_fx_audio03 = [[AVAudioPlayer alloc] initWithContentsOfURL:fxFileURL error:nil];
[_fx_audio03 setDelegate:self];
[_fx_audio03 prepareToPlay];
// Sounds for Splash menu
[self loadSplashSounds];
}
return self;
}
- (void) resetObjManager {
// since this is a singleton class at the app-level, we have
// to reset all objects and variables whenever the user
// returns to the main menu
[objects removeAllObjects];
[objects_coll removeAllObjects];
[objects_pinch removeAllObjects];
[objects_shake removeAllObjects];
[objects_neighbors removeAllObjects];
[objects_wiggle removeAllObjects];
[objects_sounds removeAllObjects];
[queue_view removeAllObjects];
[queue_shake removeAllObjects];
[queue_clean removeAllObjects];
[world_timers removeAllObjects];
spawnID = 100; // start of counter for dynamically spawned object IDs
timerID = 1;
viewWidth = 0;
viewHeight = 0;
cleanMin = 4;
cleanMax = 10;
numObjects = 0;
[self turnOffAllStates];
if (_optSound) {
[_bg_audio01 stop];
[_bg_audio02 stop];
}
_bg_audio01 = nil;
_bg_audio02 = nil;
fps = 0.0;
bounceOffset = 0.0;
gravityFilter = 0.0;
elapsedTime = 0.0;
accelX = 0.0;
//NSLog(@"Reset ObjM");
return;
}
- (void) resetObjProperties {
// this method should not be run during a
// scene reset
_objProps = nil;
_objAnimProps = nil;
_objTouchProps = nil;
_objGroups = nil;
_objRandom = nil;
_objSounds = nil;
_objTimers = nil;
//NSLog(@"Reset ObjM Props");
}
- (void) loadSounds {
NSString *soundFilePath;
NSURL *fileURL;
// get # of sounds in the array
int i = _objSounds[0].soundID;
for (int j=1; j<=i; j++) {
soundFilePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat:@"%s", _objSounds[j].soundPath]
ofType: [NSString stringWithFormat:@"%s", _objSounds[j].fileType]];
fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
[objects_sounds setObject:fileURL forKey:[NSNumber numberWithInt:_objSounds[j].soundID]];
}
}
- (void) playSound:(int)sID {
[self playSound:sID atVolume:1.0];
}
- (void) playSound:(int)sID atVolume:(CGFloat)vol {
if (_optSound) {
NSURL *soundURL;
soundURL = [objects_sounds objectForKey:[NSNumber numberWithInt:sID]];
// Determine which FX Player to use based on which are already active
if (![_fx_audio01 isPlaying]) {
_fx_audio01 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[_fx_audio01 setVolume:1.0];
[_fx_audio01 setNumberOfLoops:0];
if (vol < 1.0) {
[_fx_audio01 setVolume:vol];
}
[_fx_audio01 prepareToPlay];
[_fx_audio01 play];
}
else if (![_fx_audio02 isPlaying]) {
_fx_audio02 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[_fx_audio02 setVolume:1.0];
[_fx_audio02 setNumberOfLoops:0];
if (vol < 1.0) {
[_fx_audio02 setVolume:vol];
}
[_fx_audio02 prepareToPlay];
[_fx_audio02 play];
}
else {
_fx_audio03 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[_fx_audio03 setVolume:1.0];
[_fx_audio03 setNumberOfLoops:0];
if (vol < 1.0) {
[_fx_audio03 setVolume:vol];
}
[_fx_audio03 prepareToPlay];
[_fx_audio03 play];
}
}
}
- (void) loadSplashSounds {
// setup the sounds needed on the splash screen
NSString *soundFilePath;
NSURL *fileURL;
// STORY
soundFilePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat:@"FX_Pop2"]
ofType: [NSString stringWithFormat:@"wav"]];
fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
[objects_sounds_splash setObject:fileURL forKey:[NSNumber numberWithInt:1]];
// START
soundFilePath = [[NSBundle mainBundle] pathForResource: [NSString stringWithFormat:@"FX_Start"]
ofType: [NSString stringWithFormat:@"wav"]];
fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
[objects_sounds_splash setObject:fileURL forKey:[NSNumber numberWithInt:2]];
}
- (void) playSplashSound:(int)sID {
NSURL *soundURL;
soundURL = [objects_sounds_splash objectForKey:[NSNumber numberWithInt:sID]];
_fx_audio01 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[_fx_audio01 setNumberOfLoops:0];
[_fx_audio01 prepareToPlay];
[_fx_audio01 play];
}
- (BOOL)isStateOn:(ObjState)os { return ((osFlags & os) == os); }
- (void)turnOnState:(ObjState)os { if (![self isStateOn:os]) { osFlags |= os; } }
- (void)turnOffState:(ObjState)os { if([self isStateOn:os]) { osFlags ^= os; } }
- (void)turnOffAllStates { osFlags = 0; }
- (void) addToView:(Paper *)paperPiece {
// this queue adds objects to the view controller after message processing
[queue_view setObject:paperPiece forKey:[NSNumber numberWithInt:paperPiece.spawnID]];
}
- (void) addToShakeQueue:(int)objID {
// this queue tracks objects that can be shaken out
[queue_shake addObject:[NSNumber numberWithInt:objID]];
}
- (void) addToCleanQueue:(int)objID {
// this queue tracks objects that should be removed after
// a certain count has been reached (i.e. little fish to be eaten)
[queue_clean addObject:[NSNumber numberWithInt:objID]];
}
- (void) addWorldTimer:(Timer *)objTimer forType:(WorldTimer)wt {
[world_timers setObject:objTimer forKey:[NSNumber numberWithInt:wt]];
}
- (void) delWorldTimer:(WorldTimer)wt {
[world_timers removeObjectForKey:[NSNumber numberWithInt:wt]];
}
- (void) turnWorldTimer:(WorldTimer)wt toOn:(BOOL)isOn {
Timer *wTimer = [world_timers objectForKey:[NSNumber numberWithInt:wt]];
if (isOn) { [wTimer turnTimerOn]; }
else { [wTimer turnTimerOff]; }
}
- (BOOL) isWorldTimerOn:(WorldTimer)wt {
Timer *wTimer = [world_timers objectForKey:[NSNumber numberWithInt:wt]];
return [wTimer isTimerOn];
}
- (void) updateWorldTimers:(CGFloat)interval {
Timer *wTimer;
for (NSNumber *key in world_timers) {
wTimer = [world_timers objectForKey:key];
if ([wTimer isTimerOn]) {
[wTimer timerUpdate:interval];
}
}
}
- (void) processWorldTimers {
Timer *wTimer;
Messenger *messenger = [Messenger theMessenger];
for (NSNumber *key in world_timers) {
wTimer = [world_timers objectForKey:key];
if ([wTimer timerComplete]) {
switch (wTimer.wtMessageType) {
case mtSpawn:
[messenger queueObject:0 message:wTimer.wtMessageType turnOn:YES target:wTimer.wtTargetID wasSpawned:YES];
break;
case mtNone: // no message type is a simple wait timer
[wTimer turnTimerOff];
break;
default:
break;
}
[wTimer randomizeInterval];
[wTimer timerReset];
}
}
}
- (void) addObj:(Paper *)paperPiece forDictionary:(NSMutableDictionary *)objDict {
// generic add Paper to any object dictionary
NSNumber *newID;
newID = [NSNumber numberWithInt:paperPiece.spawnID];
[objDict setObject:paperPiece forKey:newID];
}
- (void) addObj:(Paper *)paperPiece wasSpawned:(BOOL)spawned {
// add paper piece to objects
NSNumber *newID;
if (spawned) {
newID = [NSNumber numberWithInt:spawnID];
paperPiece.spawnID = spawnID;
spawnID++;
}
else {
newID = [NSNumber numberWithInt:paperPiece.objID];
paperPiece.spawnID = paperPiece.objID;
}
[objects setObject:paperPiece forKey:newID];
// add to the objLimit
if (paperPiece.objLimit) { numObjects++; }
}
- (void) delObj:(Paper *)paperPiece {
// delete paper piece from objects
if (paperPiece.objLimit) {
if (numObjects > 0) { numObjects--; }
}
[objects removeObjectForKey:[NSNumber numberWithInt:paperPiece.spawnID]];
}
- (void) initBorder {
border = [[Border alloc] initWithFrame:CGRectMake(0, 0, 768, 1024) ];
[border initProps:_objProps[0]];
border.backgroundColor = [UIColor clearColor];
// set manager border properties
borderWidth = _objProps[0].spawnX;
borderBound = _objProps[0].spawnY;
return;
}
// Initalize all Paper objects based on the PaperProps tables
- (void) initScene {
[self turnOffState:osPaused];
// create temp objects
Paper *tPaper;
// loop through each property record, create each Paper piece and add it to the manager
// the first row (index = 0) is always the border row, so start at index = 1
int totalPieces = _objProps[0].bobAmp; // bobAmp in border row is # of objects in table
for (unsigned int i = 1; i <= totalPieces; i++) {
// if the piece should appear upon view initialization,
// then initialize and add to manager
if (_objProps[i].init) {
tPaper = [[Paper alloc] initWithProps:_objProps[i]
AnimProps:_objAnimProps[_objProps[i].animID]
TouchProps:_objTouchProps[_objProps[i].tsID]
Parent:nil];
[self addObj:tPaper wasSpawned:NO];
}
// add objID to queue_shake if necessary
if (_objProps[i].spawnByShake) {
[self addToShakeQueue:_objProps[i].objID];
}
}
// create world timers
int totalTimers = _objTimers[0].objTargetID;
for (unsigned int i = 1; i <= totalTimers; i++) {
WorldTimer timerType = _objTimers[i].wTimer;
Timer *wTimer = [[Timer alloc] initWorldTimer:timerType
worldMessage:_objTimers[i].mType
worldTarget:_objTimers[i].objTargetID
withInterval:_objTimers[i].wtInterval
withIntervalMax:_objTimers[i].wtIntervalMax
withIntervalMin:_objTimers[i].wtIntervalMin];
[self addWorldTimer:wTimer forType:timerType];
[self turnWorldTimer:timerType toOn:YES];
}
return;
}
// Check if an object was touched by the user
- (Paper*) objTouched:(CGPoint)touchPos {
Paper *eachPiece;
for (NSNumber *key in objects) {
eachPiece = [objects objectForKey:key];
if((CGRectContainsPoint(eachPiece.frame, touchPos))
&& (eachPiece.moveType != Move_Static) && (eachPiece.moveType != Move_Anim)) {
// we found the piece that was touched, so exit
return eachPiece;
}
else {
// only for animated pieces that can be killed (i.e. balloon fish)
CGRect layerFrame = [[eachPiece.layer presentationLayer] frame];
if((CGRectContainsPoint(layerFrame, touchPos))
&& (eachPiece.killOnTouch) && (eachPiece.moveType == Move_Anim)) {
return eachPiece;
}
}
}
return nil; // no piece was touched
}
// Returns the object specified by an objID value of type int
- (Paper*) getObject:(int)objID {
return [objects objectForKey:[NSNumber numberWithInt:objID]];
}
// Collision detection and velocity recalc
- (void) collidePiece:(Paper *)piece1 withPiece:(Paper *)piece2 {
// create temp vectors
Vector2D *tVel1, *tVel2, *iVelSum, *eVelSum;
Vector2D *fVel1, *fVel2;
// initialize starting vectors and calculate momentum
tVel1 = [[Vector2D alloc] initWithX:piece1.behavior.vel.x Y:piece1.behavior.vel.y];
[tVel1 mult:piece1.mass];
tVel2 = [[Vector2D alloc] initWithX:piece2.behavior.vel.x Y:piece2.behavior.vel.y];
[tVel2 mult:piece2.mass];
// initialize all other temp vectors with [0 0]
iVelSum = [[Vector2D alloc] init];
eVelSum = [[Vector2D alloc] init];
fVel1 = [[Vector2D alloc] init];
fVel2 = [[Vector2D alloc] init];
// calculate the final velocity vector of piece2 after collision
iVelSum = [[tVel1 copy] add:tVel2];
eVelSum = [[tVel1 copy] sub:tVel2];
CGFloat coefficient = -RESTITUTION; // coefficient of restitution for a linear collision
[eVelSum mult:coefficient];
[eVelSum mult:piece1.mass];
[eVelSum sub:iVelSum];
CGFloat mDiff = -piece2.mass - piece1.mass;
fVel2 = [[eVelSum copy] div:mDiff];
// calculate the final velocity vector of piece1 after collision
fVel1 = [[iVelSum copy] sub:fVel2];
// update Paper vectors
piece1.behavior.vel.x = fVel1.x;
piece1.behavior.vel.y = fVel1.y;
piece2.behavior.vel.x = fVel2.x;
piece2.behavior.vel.y = fVel2.y;
return;
}
- (void)updateDirection:(Paper *)imagePiece {
if (((imagePiece.behavior.flipX) && (imagePiece.behavior.vel.x < 0.0)) ||
((!(imagePiece.behavior.flipX)) && (imagePiece.behavior.vel.y < 0.0))) {
imagePiece.dir = -1 * imagePiece.orientation;
}
else if (((imagePiece.behavior.flipX) && (imagePiece.behavior.vel.x > 0.0)) ||
((!(imagePiece.behavior.flipX)) && (imagePiece.behavior.vel.y > 0.0))) {
imagePiece.dir = 1 * imagePiece.orientation;
}
else {
// do nothing, keep the current direction if stopped
}
}
- (BOOL)leftTopHalf:(Paper *)imagePiece {
// YES if piece is on the left or top half of screen
// used to adjust the direction of the image
CGPoint cPoint = [imagePiece getCenterPoint];
if (imagePiece.behavior.flipX) {
// left vs right
if (cPoint.x < (viewWidth * 0.5)) { return YES; }
else { return NO; }
}
else {
// top vs bottom
if (cPoint.y < (viewHeight * 0.5)) { return YES; }
else { return NO; }
}
}
- (CGPoint)keepInBounds:(Paper *)pPiece forBounds:(ViewCheckType)vcType {
CGPoint cPoint = [pPiece getCenterPoint];
// reverse the velocity elements if the image hits the border
// and bounce it away from the border so it doesn't get stuck
if (![pPiece.behavior viewCheck:vcType]) {
pPiece.transformEnabled = NO;
if ([pPiece.behavior axisHitCheck:vcType] == yAxis) {
if (pPiece.collision) {
[pPiece.behavior.vel setX:(-pPiece.behavior.vel.x)];
if (cPoint.x >= (viewWidth*0.5)) {
cPoint.x -= bounceOffset;
}
else {
cPoint.x += bounceOffset;
}
}
else {
// only bounce if not being tilted (to prevent stutter)
if ((pPiece.bindType == Bind_Always) && (fabsf(accelX) < TILT_THRESHOLD)) {
[pPiece.behavior.vel setX:(-pPiece.behavior.vel.x)*0.6];
if (cPoint.x >= (viewWidth*0.5)) {
cPoint.x -= bounceOffset;
}
else {
cPoint.x += bounceOffset;
}
}
else {
[pPiece.behavior.vel setX:0.0];
}
}
}
else {
if (vcType == vcKeepOnGround) {
[pPiece.behavior.vel setY:0.0];
}
else {
[pPiece.behavior.vel setY:(-pPiece.behavior.vel.y)];
if (cPoint.y >= (viewHeight*0.5)) {
cPoint.y -= bounceOffset-2;
}
else {
cPoint.y += bounceOffset-2;
}
}
}
}
return cPoint;
}
- (CGAffineTransform)imageTransform:(Paper *)imagePiece {
CGAffineTransform transformPiece = [self imageTransform:imagePiece withScale:1.0];
return transformPiece;
}
- (CGAffineTransform)imageTransform:(Paper *)imagePiece withScale:(CGFloat)scale {
CGAffineTransform transformPiece;
CGFloat currTransSX, currTransSY;
int imageDir = imagePiece.dir;
// don't transform based on direction if Peek is on
if (([imagePiece.behavior isOn:btPeek]) || (imagePiece.behavior.fixedDir)) {
if ([self leftTopHalf:imagePiece]) {
imageDir = imagePiece.orientation;
}
else {
imageDir = -imagePiece.orientation;
}
}
// create an initial transform based on the rotation angle if necessary
if (imagePiece.behavior.rotateAngle != 0.0) {
transformPiece = CGAffineTransformMakeRotation(imagePiece.behavior.rotateAngle);
}
else {
transformPiece = CGAffineTransformIdentity;
}
if (scale == 1.0) {
// handle any peekers explicitly because they don't
// play nice with others
if (imagePiece.behavior.peekTime > 0.0) {
currTransSX = scale;
currTransSY = scale;
}
else if (imagePiece.pinch) {
// needed to keep pinched objects the proper size
// while they aren't being pinched
currTransSX = imagePiece.transform.a;
currTransSY = imagePiece.transform.d;
}
else {
currTransSX = 1.0;
currTransSY = 1.0;
}
}
else {
currTransSX = scale;
currTransSY = scale;
}
if ([imagePiece.behavior isOn:btAxisflip]) {
// now flip the piece based on the axis
if (imagePiece.behavior.flipX) {
transformPiece = CGAffineTransformScale(transformPiece,
(imageDir * fabsf(currTransSX)),
(imagePiece.behavior.flip * fabsf(currTransSY)));
}
else {
transformPiece = CGAffineTransformScale(transformPiece,
(imagePiece.behavior.flip * fabsf(currTransSX)),
(imageDir * fabsf(currTransSY)));
}
}
else {
// if piece doesn't flip, just switch the direction as necessary
if (imagePiece.behavior.flipX) {
transformPiece = CGAffineTransformScale(transformPiece,
(imageDir * fabsf(currTransSX)),
currTransSY);
}
else {
transformPiece = CGAffineTransformScale(transformPiece,
currTransSX,
(imageDir * fabsf(currTransSY)));
}
}
return transformPiece;
}
- (void)updateGroup:(Paper *)mstrPiece {
[self updateGroup:mstrPiece transform:CGAffineTransformIdentity];
}
- (void)updateGroup:(Paper *)mstrPiece
transform:(CGAffineTransform)mstrTransform {
// setup variables
Paper *gPaper;
CGPoint gPaperCenter;
PaperGroups gGrp = _objGroups[mstrPiece.groupID];
int i = gGrp.numSubs;
CGFloat mstrTransSX, mstrTransSY;
for (int j = 1; j<=i; j++) {
if (j == 1) { gPaper = [self getObject:gGrp.objIDSub01]; }
if (j == 2) { gPaper = [self getObject:gGrp.objIDSub02]; }
gPaperCenter = mstrPiece.center;
// use scale values of the transform in case parent object is
// scaled via pinch/zoom, etc, so we can adjust the
// position offsets accordingly
mstrTransSX = fabsf(mstrTransform.a) * gPaper.childSpawn.x;
mstrTransSY = fabsf(mstrTransform.d) * gPaper.childSpawn.y;
if (mstrPiece.behavior.flipX) {
gPaperCenter.x += mstrTransSX * mstrPiece.dir;
gPaperCenter.y += mstrTransSY;
}
else {
gPaperCenter.x += mstrTransSX;
gPaperCenter.y += mstrTransSY * mstrPiece.dir;
}
gPaper.transform = mstrTransform;
CGFloat mstrVel = mstrPiece.behavior.vel.lengthSquared;
if ((!gPaper.isAnimating) && (mstrVel > 0.0)) {
[gPaper startAnimating];
}
else if ((gPaper.isAnimating) && (mstrVel == 0.0)) {
[gPaper stopAnimating];
//gPaper.layer.speed = 0.0;
}
else {
// do nothing
}
[gPaper setCenter:gPaperCenter];
}
}
// Spawning new Paper objects due to user input
- (Paper*)spawnPiece:(Paper *)touchedPiece isChild:(BOOL)child {
Paper *sPaper;
sPaper = [self spawnPiece:touchedPiece objID:touchedPiece.childImage isChild:child];
return sPaper;
}
// Spawning new Paper objects due to user input
- (Paper*)spawnPiece:(Paper *)touchedPiece objID:(int)childImg isChild:(BOOL)child {
Paper *sPaper;
// initialize the spawn object
if (child) {
sPaper = [[Paper alloc] initWithProps:_objProps[childImg]
AnimProps:_objAnimProps[_objProps[childImg].animID]
TouchProps:_objTouchProps[_objProps[childImg].tsID]
Parent:touchedPiece];
}
else {
sPaper = [[Paper alloc] initWithProps:_objProps[childImg]
AnimProps:_objAnimProps[_objProps[childImg].animID]
TouchProps:_objTouchProps[_objProps[childImg].tsID]
Parent:nil];
}
// add spawned Paper to object manager and return it to the viewcontroller
[self addObj:sPaper wasSpawned:YES];
return sPaper;
}
// MASTER SPAWN METHOD
- (Paper*)spawnPiece:(Paper *)parentPiece objID:(int)obj childID:(int)child wasSpawned:(BOOL)spawn atPoint:(CGPoint)pos {
Paper *sPaper;
int objectID;
if (child > 0) { objectID = child; }
else { objectID = obj; }
// initialize the spawn object
if (child > 0) {
sPaper = [[Paper alloc] initWithProps:_objProps[objectID]
AnimProps:_objAnimProps[_objProps[objectID].animID]
TouchProps:_objTouchProps[_objProps[objectID].tsID]
Parent:parentPiece];
}
else {
sPaper = [[Paper alloc] initWithProps:_objProps[objectID]
AnimProps:_objAnimProps[_objProps[objectID].animID]
TouchProps:_objTouchProps[_objProps[objectID].tsID]
Parent:nil];
}
if (!CGPointEqualToPoint(pos, CGPointZero)) {
[sPaper setCenter:pos];
}
// add spawned Paper to object manager and return it to the viewcontroller
[self addObj:sPaper wasSpawned:spawn];
return sPaper;
}
// Spawning an object explicitly
- (Paper*) spawnPiece:(int)objID {
Paper *sPaper;
sPaper = [self spawnPiece:objID wasSpawned:YES];
return sPaper;
}
// Spawning an object explicitly
- (Paper*) spawnPiece:(int)objID wasSpawned:(BOOL)spawn {
Paper *sPaper;
// initialize the spawn object
sPaper = [[Paper alloc] initWithProps:_objProps[objID]
AnimProps:_objAnimProps[_objProps[objID].animID]
TouchProps:_objTouchProps[_objProps[objID].tsID]
Parent:nil];
// add spawned Paper to object manager and return it to the viewcontroller
[self addObj:sPaper wasSpawned:spawn];
return sPaper;
}
// Spawning an object explicitly at a point
- (Paper*) spawnPiece:(int)objID atPoint:(CGPoint)pos {
Paper *sPaper;
// initialize the spawn object
sPaper = [[Paper alloc] initWithProps:_objProps[objID]
AnimProps:_objAnimProps[_objProps[objID].animID]
TouchProps:_objTouchProps[_objProps[objID].tsID]
Parent:nil];
[sPaper setCenter:pos];
// add spawned Paper to object manager and return it to the viewcontroller
[self addObj:sPaper wasSpawned:YES];
return sPaper;
}
- (void) killPiece:(Paper *)piece {
switch (piece.objID) {
case 6:
case 7:
case 9:
case 10:
case 12:
case 14:
case 35:
case 39:
case 46: // bubbles / balloon fish
{
//NSLog(@"Bubble Pop: %d", piece.objID);
// select a sound
int randPop = arc4random_uniform(4)+15;
[self playSound:randPop];
[UIView animateWithDuration:0.2
delay:0.0
options:UIViewAnimationOptionCurveLinear
animations:^{
piece.alpha = 0.0;
}
completion:^(BOOL finished){
piece.remove = YES;
}];
}
default:
break;
}
}
// for separation / alignment / cohesion behaviors
// determines which objects are closest to a specific object
- (void) tagNeighbors:(Paper*)piece ofQueue:(NSMutableArray*)queue {
Vector2D *sCenter = [Vector2D withX:piece.center.x Y:piece.center.y];
for (int i = 0; i < queue.count; i++) {
int sID = [[queue objectAtIndex:i] intValue];
Paper *nPiece = [self getObject:sID];
nPiece.tagged = NO;
if (piece.spawnID != nPiece.spawnID) { // shouldn't tag itself
Vector2D *dist = [Vector2D withX:nPiece.center.x Y:nPiece.center.y];
[dist sub:sCenter];
if ([dist lengthSquared] < 900) {
nPiece.tagged = YES;
}
}
}
}
- (void) changeZPosition:(NSMutableDictionary *)objDict toPos:(int)zPos {
// changes the Z Position of an object to prevent
// it from overlapping a menu view controller
Paper *zPiece;
for (NSNumber *key in objDict) {
zPiece = [objDict objectForKey:key];
zPiece.layer.zPosition = zPos;
}
}
// Saves active animations when app is pushed to background
- (void) pauseAnimations {
Paper *eachPiece;
for (NSNumber *key in objects) {
eachPiece = [objects objectForKey:key];
if ((eachPiece.paperType == Paper_Image) && (eachPiece.animated)) {
// Loop through each animation key and store current state in a dictionary in each Paper
for (NSArray *eachKey in eachPiece.layer.animationKeys) {
//NSLog(@"Key Pause Paper: %d: %@",eachPiece.spawnID, eachKey);
NSString *animKey = [NSString stringWithFormat:@"%@",eachKey];
CAAnimation *animLayer = [[eachPiece.layer animationForKey:animKey] copy];
[eachPiece.animLayerKeys setObject:animLayer forKey:[NSString stringWithFormat:@"%@",animKey]];
}
// Save when the animation stopped
CFTimeInterval pausedTime = [eachPiece.layer convertTime:CACurrentMediaTime() fromLayer:nil];