-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcrawlspaceLib.lua
1870 lines (1469 loc) · 63.1 KB
/
crawlspaceLib.lua
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
--[[ ########## Crawl Space Library ########## ]--
Version 1.1.3
Written and supported by Adam Buchweitz and Crawl Space Games
http://crawlspacegames.com
http://twitter.com/crawlspacegames
For inquiries about Crawl Space, email us at
For support with this library, email me at
Copyright (C) 2011 Crawl Space Games - All Rights Reserved
Library is MIT licensed
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
All functionality is documented below. For syntax help use .help()
For a list of included features, use the .listFeatures() method.
Note:
If your project usees an old version of the Director class by Ricardo Rauber
and use timer.cancelAll() you will cancel timers from the
director! Either modify your version of the director class,
or use the one included with this library.
--[ ########## Special Thanks ########## ]--
Thanks to Kenn Wagenheim, Jay Jennings, Bruce Martin, Piotr Machowski, and
the folks from SimpleLoop for all your input, contributions, and testing.
You guys are great!
]]--
-- Set this to false to bypass the welcome message
local showIntro = false
-- Set this to false to bypass the random Lua/CoronaSDK tips
local startupTips = false
-- Enable debug print messages, as well as on-device prints
local debug = true
-- CSL is the actual object returned
local CSL = {}
-- The cache of native and Corona APIs
cache = {}
--[[ ########## Getting Help ########## ]--
Start with:
local CSL = require "crawlspaceLib"
CSL.help()
]]
local helpArr = {}
CSL.help = function(item)
if not item then
cache.print("\n\nUse this help feature for syntax additions in Crawl Space functions.")
cache.print('\n\nUSAGE EXAMPLE:\n\n\tcrawlspaceLib.help("newText")')
else
cache.print('\n\nCrawlSpace Help: '..item..'\n')
if helpArr[item] then cache.print('\t'..helpArr[item]) else
cache.print('Sorry, I cannot find that item. Available items are:')
for k,v in pairs(helpArr) do cache.print('\n -- '..k) end
end
end
end
--[[ ########## Global Screen Dimensions ########## ]--
Use these global variables to position your elements. They are dynamic
to all resolutions. Android devices are usually taller, so use screenTop to
set the position where you expect 0 to be. The iPad is wider than iPhones,
so use screenLeft. Also the width and height need to factor these differences
in as well, so use screenWidth and screenHeight. Lastly, centerX and centerY
are simply global remaps of display.contentCenterX and Y.
:: USAGE ::
myObject.x, myObject.y = screenX + 10, screenY + 10 -- Position 10 pixels from the top left corner on all devices
display.newText("centered text", centerX, centerY, 36) -- Center the text
display.newRect(screenX, screenY, screenWidth, screenHeight) -- Cover the screen, no matter what size
]]
centerX = display.contentCenterX
centerY = display.contentCenterY
screenX = display.screenOriginX
screenY = display.screenOriginY
screenWidth = display.contentWidth - screenX * 2
screenHeight = display.contentHeight - screenY * 2
screenLeft = screenX
screenRight = screenX + screenWidth
screenTop = screenY
screenBottom = screenY + screenHeight
cache.contentWidth = display.contentWidth
cache.contentHeight = display.contentHeight
display.contentWidth = screenWidth
display.contentHeight = screenHeight
--[[ ########## Global Content Scale and Suffix ########## ]--
Checks the content scaling and sets a global var "scale". In addition,
if you use sprite sheets and was retina support, append the global "suffix"
variable when calling your datasheet, and it will pull the hi-res version
when it's needed. On the topic of devices and scals, when in the simulator,
the global variable "simulator" is set to true.
]]
scale, suffix = display.contentScaleX, ""
if scale < 1 then if scale > .5 then suffix = "@1_5x" else suffix = "@2x" end end
--magicWidth, magicHeight = 760*scale, 1140*scale
magicWidth, magicHeight = 380, 570
if system.getInfo("environment") == "simulator" then simulator = true end
--[[ ########## Saving and Loading ########## ]--
This bit has been mostly barrowed from the Ansca documentation,
we simply made it easier to use.
You keep one table of information, with as many properties
as you like. Simply pass this table into to Save() and it
will be taken care of. To load it, just call Load() which
returns the table.
:: SAVING EXAMPLE ::
local myData = {}
myData.bestScore = 500
myData.volume = .8
Save(myData)
:: LOADING EXAMPLE ::
local myData = Load()
print(myData.bestScore) <== 500
print(myData.volume) <== .8
]]
helpArr.Save = 'Save(table [, filename])'
helpArr.save = 'Did you mean "Save" ?'
local tonum = tonumber
local split = function(str, pat)
local t = {}
local fpat = "(.-)" .. (pat or " ")
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then table.insert(t,cap) end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t,cap)
end
return t
end
string.split = split
Save = function(table, fileName)
local filePath = system.pathForFile( fileName or "data.txt", system.DocumentsDirectory )
local file = io.open( filePath, "w" )
for k,v in pairs( table or Data ) do
if type(v) == "table" then
for k2,v2 in pairs( v ) do
file:write( k .. ":" .. k2 .. "=" .. tostring(v2) .. "~" )
end
else
file:write( k .. "=" .. tostring(v) .. "~" )
end
end
io.close( file )
end
helpArr.Load = 'local mySavedData = Load([filename])'
helpArr.load = 'Did you mean "Load"?'
Load = function(fileName)
local filePath = system.pathForFile( fileName or "data.txt", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
if file then
local dataStr = file:read( "*a" )
local datavars = split(dataStr, "~")
local dataTableNew = {}
for k,v in pairs(datavars) do
if string.find(tostring(v),":") then
local table = split(v, ":")
local pair = split(table[2], "=")
if pair[2] == "true" then pair[2] = true
elseif pair[2] == "false" then pair[2] = false
elseif tonum(pair[2]) then pair[2] = tonum(pair[2]) end
if not dataTableNew[tonum(table[1]) or table[1]] then dataTableNew[tonum(table[1]) or table[1]] = {} end
dataTableNew[tonum(table[1]) or table[1]][tonum(pair[1]) or pair[1]] = pair[2]
else
local pair = split(v, "=")
if pair[2] == "true" then pair[2] = true
elseif pair[2] == "false" then pair[2] = false
elseif tonum(pair[2]) then pair[2] = tonum(pair[2]) end
dataTableNew[tonum(pair[1]) or pair[1]] = pair[2]
end
end
io.close( file ) -- important!
if not fileName then
for k,v in pairs(dataTableNew) do Data[k] = v; setVar{k,v,true} end
end
return dataTableNew
else
print("No data to load yet.")
return false
end
end
Defaults = function(d)
for k,v in pairs(d) do
Data[k] = v
setVar{k,v,true}
end
end
Data = {}
--[[ ########## Reference Point Shorthand ########## ]--
All this block does it set shorthand notations for all reference points.
The main purpose of this is for passing short values into display objects.
:: EXAMPLE 1 ::
myObject:setReferencePoint(display.tl)
]]
helpArr.referencePoint = 'myDisplayObject:setReferencePoint(display.tl)'
helpArr.referencePoints = '"tl", "tc", "tb", "cl", "c", "cr", "bl", "bc", "br"\n\n\tAlso added to the display package: display.tl'
display.tl = display.TopLeftReferencePoint
display.tc = display.TopCenterReferencePoint
display.tr = display.TopRightReferencePoint
display.cl = display.CenterLeftReferencePoint
display.c = display.CenterReferencePoint
display.cr = display.CenterRightReferencePoint
display.bl = display.BottomLeftReferencePoint
display.bc = display.BottomCenterReferencePoint
display.br = display.BottomRightReferencePoint
--[[ ########## Crawlspace Display Objects Methods ########## ]--
Here is where the magic happens to all display objects. All methods are given
a fadeIn() and fadeOut() method, to be used with optional parameters. You can
include a callback if you'd like, or tell your fadeOut() to automatically remove
the object when it's completed.
If dynamic resolutions scare you, then you may use the setPos() method attached
to every display object. It will take care of the dynamic part - just style it
once. Also if you find yourself centering a lot of objects, you can call their
center() method and either pass in "x", "y", or nothing to center both axis'.
:: USAGE ::
myObject:fadeIn([time, callback])
myObject:fadeOut([time, callback, autoRemove])
myObject:center("x")
myObject:setPos(100, 200)
:: EXAMPLE 1 ::
myImage = display.newImage("myImage")
myImage:center()
myImage:fadeIn()
timer.performWithDelay( 2000, myImage.fadeOut )
:: EXAMPLE 2 ::
local myRectangle = display.newRect(0,0,100,50)
myRectangle:setPos(25, 25)
]]
local random, floor, ceil, abs, sqrt, atan2, pi = math.random, math.floor, math.ceil, math.abs, math.sqrt, math.atan2, math.pi
helpArr.setFillColor = 'myRect:setFillColor( hex )\n\n\tor\n\n\tmyRect:setFillColor( red, green, blue [, alpha] )'
local hexTable = {f=15,e=14,d=13,c=12,b=11,a=10}
hexToRGB = function(h, format)
local r,g,b,a
local hex = string.lower(string.gsub(h,"#",""))
if hex:len() >= 6 then
r = tonum(hex:sub(1, 2), 16)
g = tonum(hex:sub(3, 4), 16)
b = tonum(hex:sub(5, 6), 16)
a = tonum(hex:sub(7, 8), 16)
elseif hex:len() == 3 then
r = tonum(hex:sub(1, 1) .. hex:sub(1, 1), 16)
g = tonum(hex:sub(2, 2) .. hex:sub(2, 2), 16)
b = tonum(hex:sub(3, 3) .. hex:sub(3, 3), 16)
a = 255
end
if format == "table" then
return {r,g,b,a or 255}
else
return r,g,b,a or 255
end
end
local crawlspaceFillColor = function(self,r,g,b,a)
local r,g,b,a = r,g,b,a
if type(r) == "string" then
local hex = string.lower(string.gsub(r,"#",""))
if hex:len() >= 6 then
r = tonum(hex:sub(1, 2), 16)
g = tonum(hex:sub(3, 4), 16)
b = tonum(hex:sub(5, 6), 16)
a = tonum(hex:sub(7, 8), 16) or 255
elseif hex:len() == 3 then
r = tonum(hex:sub(1, 1) .. hex:sub(1, 1), 16)
g = tonum(hex:sub(2, 2) .. hex:sub(2, 2), 16)
b = tonum(hex:sub(3, 3) .. hex:sub(3, 3), 16)
a = 255
end
end
self:cachedFillColor(r,g,b,a or 255)
end
local injectedDisplayMethods = {}
injectDisplayMethod = function(name, method)
if type(method) ~= "function" then
error("Please pass a method to inject")
else
injectedDisplayMethods[#injectedDisplayMethods+1] = {name, method}
end
end
local tranc = transition.cancel
local displayMethods = function( obj )
local d = obj
d.distanceTo = function(self,x,y) return ceil(sqrt( ((y - self.y) * (y - self.y)) + ((x - self.x) * (x - self.x)))) end
d.angleTo = function(self,x,y) return ceil(atan2( (y - self.y), (x - self.x) ) * 180 / pi) + 90 end
d.setPos = function(self,x,y) d.x, d.y = screenX+x, screenY+y end
d.setScale = function(self,x,y) d.xScale, d.yScale = x, y or x end
d.setScaleP = d.setScale
d.setSize = function(self,height,width) d.height, d.width = height, width end
d.center = function(self,axis) if axis == "x" then d.x=centerX elseif axis == "y" then d.y=centerY else d.x,d.y=centerX,centerY end end
d.fader={}
d.fadeIn = function( self, num, callback ) tranc(d.fader); d.alpha=0; d.fader=transition.to(d, {alpha=1, time=num or d.fadeTime or 500, onComplete=callback}) end
d.fadeOut = function( self, time, callback, autoRemove) d.callback = callback; if type(callback) == "boolean" then d.callback = function() display.remove(d) end elseif autoRemove then d.callback = function() callback(); display.remove(d); d=nil end end tranc(d.fader); d.fader=transition.to(d, {alpha=0, time=time or d.fadeTime or 500, onComplete=d.callback}) end
d.setStageFocus = function() display.getCurrentStage():setFocus(d) end
d.removeStageFocus = function() display.getCurrentStage():setFocus(nil) end
if d.setFillColor then d.cachedFillColor = d.setFillColor; d.setFillColor = crawlspaceFillColor end
if #injectedDisplayMethods > 0 then
for i,v in ipairs(injectedDisplayMethods) do
if d[v[1]] then d["cached"..v[1]] = d[v[1]] end
d[v[1]] = v[2]
end
end
end
--[[ ########## CrawlSpace Reference Points ########## ]--
Shorthand for all reference points.
As an added bonus, if your image cannot be created, it will print out
a nice warning message with wheatever image path was at fault.
:: EXAMPLE 1 ::
myObject:setReferencePoint(display.tl)
]]
local referencePoints = function( obj, point )
local rp = display[point] or display.c
if obj then obj:setReferencePoint(rp); return true
else print("\n\n\n\n\n My deepest apologies, but there was a problem creating your display object... \n could you have mistyped your path?\n\n\n\n\n"); return false end
end
--[[ ########## NewGroup Override ########## ]--
At long last you may insert multiple objects into a group with
a single line! There is no syntax change, and you may still insert
object when instantiating the group.
:: USAGE ::
myGroup:insert([index, ] myObject [, mySecondObject, myThirdObject, resetTransform])
:: EXAMPLE 1 ::
local myGroup = display.newGroup()
myGroup:insert(myImage, myRect, myRoundedRect, myImageRect)
:: EXAMPLE 2 ::
local myGroup = display.newGroup(firstObject, secondObject)
myGroup:insert(thirdObject, forthObject)
:: EXAMPLE 3 ::
local myGroup = display.newGroup()
myGroup:insert( 1, myObject, mySecondObject) -- inserting all objects at position 1
:: EXAMPLE 4 ::
local myGroup = display.newGroup()
myGroup:insert( myObject, mySecondObject, true) -- resetTransform still works too!
]]
helpArr.insert = 'myGroup:insert([index,] object1 [, object2, object3, resetTransform])'
local crawlspaceInsert = function(...)
local t = {...}
local b, reset = 0, nil
if type(t[#t]) == "boolean" then b = 1; reset = t[#t] end
if type(t[2]) == "number" then for i=3, #t-b do t[1]:cachedInsert(t[2],t[i],reset); if reset and t[i].text then t[i].xScale, t[i].yScale=.5,.5 end end
else for i=2, #t-b do t[1]:cachedInsert(t[i],reset); if reset and t[i].text then t[i].xScale, t[i].yScale=.5,.5 end end
end
end
cache.newGroup = display.newGroup
display.newGroup = function(...)
local g = cache.newGroup(...)
g.cachedInsert = g.insert
g.insert = crawlspaceInsert
displayMethods( g )
return g
end
--[[ ########## NewLine Override ########## ]--
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
display.newLine(centerX, centerY, centerX + 20, centerY [, "tl"])
]]
cache.newLine = display.newLine
display.newLine = function( parent, x1, y1, x2, y2, rp )
local parent, x1, y1, x2, y2, rp = parent, x1, y1, x2, y2, rp
if tonum(parent) then x1, y1, x2, y2, rp, parent = parent, x1, y1, x2, y2, nil end
local l = cache.newLine(x1, y1, x2, y2 )
if referencePoints( l, rp ) then displayMethods( l ) end
if parent then parent:insert(l) end
return l
end
--[[ ########## NewCircle Override ########## ]--
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
display.newCircle(centerX, centerY, 20 [, "tl"])
]]
cache.newCircle = display.newCircle
display.newCircle = function( parent, x, y, r, rp )
local parent, x, y, r, rp = parent, x, y, r, rp
if tonum(parent) then x, y, r, rp, parent = parent, x, y, r, nil end
local c = cache.newCircle( 0, 0, r )
if referencePoints( c, rp ) then displayMethods( c ) end
if parent then parent:insert(c) end
c.x, c.y = x, y
return c
end
--[[ ########## NewRect Override ########## ]--
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
display.newRect(0, 0, 100, 50 [, "tl"])
]]
helpArr.newRect = 'display.newRect(x-position, y-position, width, height [,referencePoint])'
cache.newRect = display.newRect
display.newRect = function( parent, x, y, w, h, rp )
local parent, x, y, w, h, rp = parent, x, y, w, h, rp
if tonum(parent) then x, y, w, h, rp, parent = parent, x, y, w, h, nil end
local r = cache.newRect( x, y, w, h )
if referencePoints( r, rp or "tl" ) then displayMethods( r ) end
if parent then parent:insert(r) end
r.x, r.y = x, y
parent, x, y, w, h, rp = nil, nil, nil, nil, nil, nil
return r
end
--[[ ########## NewRoundedRect Override ########## ]--
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
display.newRoundedRect( 0, 0, 100, 50, 10 [, "tl"])
]]
helpArr.newRoundedRect = 'display.newRoundedRect(x-position, y-position, width, height, radius [, referencePoint])'
cache.newRoundedRect = display.newRoundedRect
display.newRoundedRect = function( parent, x, y, w, h, r, rp )
local parent, x, y, w, h, r, rp = parent, x, y, w, h, r, rp
if tonum(parent) then x, y, w, h, r, rp, parent = parent, x, y, w, h, r, nil end
local r = cache.newRoundedRect( 0, 0, w, h, r ); r.x,r.y=x,y
if referencePoints( r, rp ) then displayMethods( r ) end
if parent then parent:insert(r) end
r.x, r.y = x, y
parent, x, y, w, h, rp = nil, nil, nil, nil, nil, nil
return r
end
--[[ ########## NewImage Override ########## ]--
The enhancement to newImage is that if you omit the x and y,
they will be set to the dynamic rasolution values for 0, 0.
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
display.newImage("myImage.png" [, 100, 50, "tl"])
]]
helpArr.newImage = 'display.newImage(filename [, x-position, y-position, referencePoint])\n\n\tNote that x and y positions are defaulted to the dynamic resolution value of the top left corner of the screen.'
cache.newImage = display.newImage
display.newImage = function( parent, path, x, y, rp )
local parent, path, x, y, rp = parent, path, x, y, rp
if type(parent) == "string" then path, x, y, rp, parent = parent, path, x, y, nil end
local i = cache.newImage( path, x or screenX, y or screenY )
if referencePoints( i, rp ) then displayMethods( i ) end
if parent then parent:insert(i) end
local parent, path, x, y, rp = nil, nil, nil, nil, nil
return i
end
--[[ ########## NewImageRect Override ########## ]--
Enhanced newImageRect has the option to omit the width and height.
They wil be defaulted to the "magic" sizes of 380 wide by 570 tall.
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
display.newImageRect([parentGroup], "myImage.png" [, 100, 50, "tl"])
:: EXAMPLE 2 ::
display.newImageRect("myImage.png")
]]
helpArr.newImageRect = 'display.newImage(filename [, width, height, referencePoint])\n\n\tNote that width and height values are defaulted to 380 and 570 respectively. These values corrospond to the "magic formula" commonly used to dynamic resolutions.'
helpArr.newImage = 'display.newImage(filename [, x-position, y-position, referencePoint])'
cache.newImageRect = display.newImageRect
display.newImageRect = function( parent, path, baseDir, w, h, rp )
local parent, path, baseDir, w, h, rp, i = parent, path, baseDir, w, h, rp
if type(parent) == "string" then path, baseDir, w, h, rp, parent = parent, path, baseDir, w, h, nil end
if type(baseDir) == "userdata" then
i = cache.newImageRect( path, baseDir, w or 380, h or 570 )
else
w, h, rp = baseDir, w, h
i = cache.newImageRect( path, w or 380, h or 570 )
end
if referencePoints( i, rp ) then displayMethods( i ) end
if parent then parent:insert(i) end
local parent, path, baseDir, w, h, rp = nil, nil, nil, nil, nil, nil
return i
end
--[[ ########## Sprite Override ########## ]--
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE 1 ::
sprite.newSprite( mySpriteSet [, "tl"])
]]
local sprite = require "sprite"
cache.newSprite = sprite.newSprite
sprite.newSprite = function( spriteSet, rp )
local s = cache.newSprite( spriteSet )
if referencePoints( s, rp ) then displayMethods( s ) end
return s
end
--[[ ########## Auto Retina Text ########## ]--
This feature doesn't require much explanation. It overrides the default
CoronaSDK display.newText and replaces it with auto retina text,
which is simply doubling the text size and scaling it down.
The only extra step is setting the position AFTER text is scaled,
which solves a positioning problem after scaling.
As with all display objects, you may append a string argument to set
it's reference point.
:: EXAMPLE ::
display.newText("My New Text", 100, 100, native.systemFont, 36 [, "cr" ] )
]]
helpArr.setTextColor = 'myText:setTextColor( hex )\n\n\tor\n\n\tmyText:setTextColor( red, green, blue )'
local crawlspaceTextColor = function(self,r,g,b)
local r,g,b = r,g,b
if type(r) == "string" then
local hex = string.lower(string.gsub(r,"#",""))
if hex:len() == 6 then
r = tonum(hex:sub(1, 2), 16)
g = tonum(hex:sub(3, 4), 16)
b = tonum(hex:sub(5, 6), 16)
elseif hex:len() == 3 then
r = tonum(hex:sub(1, 1) .. hex:sub(1, 1), 16)
g = tonum(hex:sub(2, 2) .. hex:sub(2, 2), 16)
b = tonum(hex:sub(3, 3) .. hex:sub(3, 3), 16)
end
end
self:cachedTextColor(r,g,b)
r,g,b = nil, nil, nil
end
helpArr.newText = 'display.newText(string, x-position, y-position, font, size [, referencePoint ] )'
cache.newText = display.newText
display.newText = function( parent, text, xPos, yPos, width, height, font, size, rp )
local t
local parent, text, xPos, yPos, width, height, font, size, rp = parent, text, xPos, yPos, width, height, font, size, rp
if type(parent) ~= "table" then
text, xPos, yPos, width, height, font, size, rp = parent, text, xPos, yPos, width, height, font, size
if type(width) == "number" then
t = cache.newText(text, 0, 0, width * 2, height * 2, font, size * 2)
else
rp = font
t = cache.newText(text, 0, 0, width, height * 2)
end
else
if type(width) == "number" then
t = cache.newText(parent, text, 0, 0, width, height, font, size * 2)
else
rp = font
t = cache.newText(parent, text, 0, 0, width, height * 2)
end
end
referencePoints( t, rp ); displayMethods(t)
t.xScale, t.yScale, t.x, t.y = 0.5, 0.5, xPos, yPos
t.cachedTextColor = t.setTextColor
t.setTextColor = crawlspaceTextColor
parent, text, xPos, yPos, font, size, rp = nil, nil, nil, nil, nil, nil
return t
end
--[[ ########## New Paragraphs ########## ]--
Making paragraphs is now pretty easy. You can call the paragraph
by itself, passing in the text size as the last parameter, or you
can apply various formatting properties. Right now the list of
available properties are:
font = myCustomFont
lineHeight = 1.4
align = ["left", "right", "center"]
color = { 255, 0, 0 }
The method returns a group, which cannot be directly editted (yet),
but can be handled like any other group. You may position it,
transition it, insert it into another group, etc. Additionally,
All paragraph text is accessible, though not edditable, with
myParagraph.text
:: USAGE ::
display.newParagraph( text, charactersPerLine, size or parameters )
:: EXAMPLE 1 ::
local format = {}
format.font = flyer
format.size = 36
format.lineHeight = 2
format.align = "center"
local myParagraph = display.newParagraph( "Welcome to the Crawl Space Library!", 15, format)
myParagraph:center("x")
myParagraph:fadeIn()
:: EXAMPLE 2 ::
local myParagraph = display.newParagraph( "I don't care about formatting this paragraph, just place it", 20, 24 )
]]
helpArr.newParagraph = 'display.newParagraph( string, charactersWide, { [font=font, size=size, lineHeight=lineHeight, align=align] })\n\n\tor\n\n\tdisplay.newParagraph( string, charactersWide, size )'
local textAlignments = {left="cl",right="cr",center="c",centered="c",middle="c"}
display.newParagraph = function( string, width, params )
local format; if type(params) == "number" then format={size = params} else format=params end
local splitString, lineCache, tempString = split(string, " "), {}, ""
for i=1, #splitString do
if splitString[i] == "\n" then
local s = string.gsub(splitString[i], '\n', '')
lineCache[#lineCache+1]=tempString; tempString=s
elseif #tempString + #splitString[i] > width then lineCache[#lineCache+1]=tempString; tempString=splitString[i].." "
else tempString = tempString..splitString[i].." " end
end
lineCache[#lineCache+1]=tempString
local g, align = display.newGroup(), textAlignments[format.align or "left"]
for i=1, #lineCache do
g.text=(g.text or "")..lineCache[i]
local t = display.newText(lineCache[i],0,( format.size * ( format.lineHeight or 1 ) ) * i,format.font, format.size, align)
format.color = format.color or format.textColor or {255, 255, 255}
t:setTextColor(format.color[1],format.color[2],format.color[3])
g:insert(t)
end
return g
end
--[[ ########## Timer Hijack ########## ]--
This override is here to snag every timer and cache it into
an array for later cancelling. There is no change in syntax,
none of your code will break.
Sometimes you will want to cancel all timers EXCEPT a few,
in which case simply pass in "false" when you create your timer.
:: EXAMPLE 1 ::
local myFunction = function()
print("my function") <== This will never print
end
timer.performWithDelay(5000, myFunction)
timer.cancelAll()
:: EXAMPLE 2 ::
local myFunction = function()
print("my function") <== This will never print
end
local mySecondFunction = function()
print("my second function") <== This will print!
end
timer.performWithDelay(5000, myFunction)
timer.performWithDelay(5000, mySecondFunction, false)
timer.cancelAll()
:: EXAMPLE 3 ::
local seconds = 0
local count = function()
seconds = seconds + 1
print(seconds)
end
myTimer = timer.performWithDelay(1000, count, 0, false) -- You may still use the repeat counter
timer.cancelAll()
]]
helpArr.timer = 'timer.performWithDelay( delay, function [, repeats, omitFromCancelAll])'
local timerArray = {}
cache.performWithDelay = timer.performWithDelay
timer.performWithDelay = function( time, callback, repeats, add )
local repeats, add = repeats, add
if type(repeats) == "boolean" then add = repeats; repeats = nil end
local t = cache.performWithDelay(time, callback, repeats)
t._begin = system.getTimer()
t._delay = t._delay or time
t.cancel = function()
timer.cancel(t)
local v = table.search(timerArray, t)
if v then table.remove(timerArray, v) end
t, v = nil, nil
end
t.pause = function()
t._remaining = (t._count or 1 * t._delay) - (system.getTimer() - t._begin)
timer.cancel(t)
t.paused = true
end
t.resume = function()
if t.paused then
local tmp = t._delay
if repeats then
else
t = cache.performWithDelay(t._remaining, callback, add)
end
t._delay = tmp
t._begin = system.getTimer()
t.paused, t._remaining, tmp = nil, nil, nil
end
end
if add == true then
timerArray[#timerArray+1] = t
end
return t
end
helpArr.cancelAll = 'timer.cancelAll()'
timer.cancelAll = function()
while #timerArray > 0 do
timer.cancel(table.remove(timerArray,1))
end
end
--[[ ########## Safe Timer Cancel ########## ]--
There will inevitably come a time when you write something like:
if myTimer then timer.cancel(myTimer) end
Instead of wasting time thinking about if the timer exists yet,
just cancel it like normal. If is doesn't exist, you will receive
a kind warning letting you know, but there be no error
:: EXAMPLE 1 ::
local myTimer
timer.cancel(myTimer) -- Even though the timer does not yet exist, there will be no error
myTimer = timer.performWithDelay(10000, myFunction)
timer.cancel(myTimer) -- It will now cancel like normal
]]
cache.timerCancel = timer.cancel
timer.cancel = function(t) if t and t._time then cache.timerCancel(t) end end
--[[ ########## Transitions ########## ]--
to, from, cancel
multiple, safe, pause, resume, cancel
reverse, loop, bounce
]]
--[[ ########## Multiple Transition ########## ]--
]]
cache.transitionFrom = transition.from
transition.from = function(tweens, params)
if tweens then
if #tweens > 0 then
for i,v in ipairs(tweens) do
if params.targetSelf then params.onComplete = v end
cache.transitionFrom(v, params)
end
else
return cache.transitionFrom(tweens, params)
end
end
end
cache.transitionTo = transition.to
transition.to = function(tweens, params)
if tweens then
if #tweens > 0 then
for i,v in ipairs(tweens) do
if params.targetSelf then params.onComplete = v end
cache.transitionTo(v, params)
end
else
return cache.transitionTo(tweens, params)
end
end
end
cache.transitionCancel = transition.cancel
transition.cancel = function(tweens)
if tweens then
if #tweens > 0 then
for i,v in ipairs(tweens) do
cache.transitionCancel(v)
end
else
cache.transitionCancel(tweens)
end
end
end
--[[ ########## Crossfade Background Music ########## ]--
Crossfading your background music gives your games a lot more polish. Using
the Crawl Space Library, this is easy! The first two audio channels are
reserved automatically, and when you call the method it keeps track of
which one is not in use for the next crossfade. You should even call this
method for the first play of the background music.
The Crawl Space Library also registers a variable called "volume", and that
is where the cross fader gets the start / end points. So if your app has
a slider that changes the volume, do not forget to change the volume variable!
:: EXAMPLE 1 ::
audio.crossFadeBackground("myBackgroundMusic")
:: EXAMPLE 2 ::
setVar{"volume", .5, true}
audio.crossFadeBackground("myBackgroundMusic")
]]
local audio = require "audio"
local audioChannel, otherAudioChannel, currentSong, curAudio, prevAudio = 1
audio.crossFadeBackground = function( path, params )
if CSL.retrieveVariable("music") then
params = params or {}
local musicPath = path or CSL.retrieveVariable("musicPath")
if currentSong == musicPath and audio.getVolume{channel=audioChannel} > 0.1 then return false end
audio.fadeOut({channel=audioChannel, time=500})
if audioChannel==1 then audioChannel,otherAudioChannel=2,1 else audioChannel,otherAudioChannel=1,2 end
audio.setVolume( CSL.retrieveVariable("volume"), {channel=audioChannel})
curAudio = audio.loadStream( musicPath )
audio.play(curAudio, {channel=audioChannel, loops=(params.loops or -1), fadein=500, onComplete=(params.onComplete or function()end)})
prevAudio = curAudio
currentSong = musicPath
audio.currentBackgroundChannel = audioChannel
end
end
audio.reserveChannels(2)
audio.currentBackgroundChannel = 1
--[[ ########## True or False SFX ########## ]--
Your game probably will have a toggle to turn on and off sound effect,
but it's a major pain to check the variable everytime you want to
play one. If you, instead, adjust the auto-registered "sfx" variable,
audio.playSFX will handle the checking for you. Additionaly, playSFX
can handle a string or a preloaded sound. If you are playing the sounds
often, you should still preload it.
:: EXAMPLE 1 ::