forked from Seneca-CDOT/thecollectors
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodebase.pde
More file actions
4587 lines (3999 loc) · 126 KB
/
Copy pathcodebase.pde
File metadata and controls
4587 lines (3999 loc) · 126 KB
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
/**
* Actors represent something or someone,
* and can consist of one or more states,
* each associated with a particular sprite,
* and each associated with particular
* behaviour.
*
* The Actor class is abstract: you must
* implement your own subclass before you
* can make use of it.
*/
abstract class Actor extends Positionable {
boolean debug = false;
// debug bounding box alignment
float halign=0, valign=0;
// are we colliding with another actor?
boolean colliding = false;
// regular interaction with other actors
boolean interacting = true;
// only interact with players
boolean onlyplayerinteraction = false;
// bypass regular interaction for ... frames
int disabledCounter = 0;
// should we be removed?
boolean remove = false;
// is this actor persistent with respect to viewbox draws?
boolean persistent = true;
boolean isPersistent() { return persistent; }
// the layer this actor is in
LevelLayer layer;
// The active state for this actor (with associated sprite)
State active;
// all states for this actor
HashMap<String, State> states;
// actor name
String name = "";
// simple constructor
Actor(String _name) {
name = _name;
states = new HashMap<String, State>();
}
// full constructor
Actor(String _name, float dampening_x, float dampening_y) {
this(_name);
setImpulseCoefficients(dampening_x, dampening_y);
}
/**
* Add a state to this actor's repetoire.
*/
void addState(State state) {
state.setActor(this);
boolean replaced = (states.get(state.name) != null);
states.put(state.name, state);
if(!replaced || (replaced && state.name == active.name)) {
if (active == null) { active = state; }
else { swapStates(state); }
updatePositioningInformation();
}
}
/**
* Get a state by name.
*/
State getState(String name) {
return states.get(name);
}
/**
* Get the current sprite image
*/
PImage getSpriteMask() {
if(active == null) return null;
return active.sprite.getFrame();
}
/**
* Tell this actor which layer it is operating in
*/
void setLevelLayer(LevelLayer layer) {
this.layer = layer;
}
/**
* Tell this actor which layer it is operating in
*/
LevelLayer getLevelLayer() {
return layer;
}
/**
* Set the actor's current state by name.
*/
void setCurrentState(String name) {
State tmp = states.get(name);
if (active != null && tmp != active) {
tmp.reset();
swapStates(tmp);
} else { active = tmp; }
}
/**
* Swap the current state for a different one.
*/
void swapStates(State tmp) {
// get pertinent information
Sprite osprite = active.sprite;
boolean hflip = false, vflip = false;
if (osprite != null) {
hflip = osprite.hflip;
vflip = osprite.vflip;
}
// upate state to new state
active = tmp;
Sprite nsprite = tmp.sprite;
if (nsprite != null) {
if (hflip) nsprite.flipHorizontal();
if (vflip) nsprite.flipVertical();
updatePositioningInformation();
// if both old and new states had sprites,
// make sure the anchors line up.
if (osprite != null) {
handleSpriteSwap(osprite, nsprite);
}
}
}
/**
* Move actor if this state changes
* makes the actor bigger than before,
* and we're attached to boundaries.
*/
void handleSpriteSwap(Sprite osprite, Sprite nsprite) {
float ax1 = osprite.hanchor,
ay1 = osprite.vanchor,
ax2 = nsprite.hanchor,
ay2 = nsprite.vanchor;
float dx = (ax2-ax1)/2.0, dy = (ay2-ay1)/2.0;
x -= dx;
y -= dy;
}
/**
* update the actor dimensions based
* on the currently active state.
*/
void updatePositioningInformation() {
width = active.sprite.width;
height = active.sprite.height;
halign = active.sprite.halign;
valign = active.sprite.valign;
}
/**
* constrain the actor position based on
* the layer they are located in.
*/
void constrainPosition() {
float w2 = width/2, lw = layer.width;
if (x < w2) { x = w2; }
if (x > lw - w2) { x = lw - w2; }
}
/**
* Get the bounding box for this actor
*/
float[] getBoundingBox() {
if(active==null) return null;
float[] bounds = active.sprite.getBoundingBox();
// transform the bounds, based on local translation/scale/rotation
if(r!=0) {
float x1=bounds[0], y1=bounds[1],
x2=bounds[2], y2=bounds[3],
x3=bounds[4], y3=bounds[5],
x4=bounds[6], y4=bounds[7];
// rotate
bounds[0] = x1*cos(r) - y1*sin(r);
bounds[1] = x1*sin(r) + y1*cos(r);
bounds[2] = x2*cos(r) - y2*sin(r);
bounds[3] = x2*sin(r) + y2*cos(r);
bounds[4] = x3*cos(r) - y3*sin(r);
bounds[5] = x3*sin(r) + y3*cos(r);
bounds[6] = x4*cos(r) - y4*sin(r);
bounds[7] = x4*sin(r) + y4*cos(r);
}
// translate
bounds[0] += x+ox; bounds[1] += y+oy; // top left
bounds[2] += x+ox; bounds[3] += y+oy; // top right
bounds[4] += x+ox; bounds[5] += y+oy; // bottom right
bounds[6] += x+ox; bounds[7] += y+oy; // bottom left
// done
return bounds;
}
/**
* check overlap between sprites,
* rather than between actors.
*/
float[] overlap(Actor other) {
float[] overlap = super.overlap(other);
if(overlap==null || active==null || other.active==null) {
return overlap;
}
//
// TODO: add in code here that determines
// the intersection point for the two
// sprites, and checks the mask to see
// whether both have non-zero alph there.
//
return overlap;
}
/**
* What happens when we touch another actor?
*/
void overlapOccurredWith(Actor other, float[] direction) {
colliding = true;
}
/**
* What happens when we get hit
*/
void hit() { /* can be overwritten */ }
/**
* attach an actor to a boundary, so that
* impulse is redirected along boundary
* surfaces.
*/
void attachTo(Boundary boundary, float[] correction) {
// don't add boundaries we're already attached to
if(boundaries.contains(boundary)) return;
// record attachment
boundaries.add(boundary);
// stop the actor
float[] original = {this.ix - (fx*ixF), this.iy - (fy*iyF)};
stop(correction[0], correction[1]);
// then impart a new impulse, as redirected by the boundary.
float[] rdf = boundary.redirectForce(original[0], original[1]);
addImpulse(rdf[0], rdf[1]);
// call the blocked handler
gotBlocked(boundary, correction, original);
// and then make sure to update the actor's position, as
// otherwise it looks like we've stopped for 1 frame.
update();
}
/**
* This boundary blocked our path.
*/
void gotBlocked(Boundary b, float[] intersection, float[] original) {
// subclasses can implement, but don't have to
}
/**
* collisions may force us to stop this
* actor's movement. the actor is also
* moved back by dx/dy
*/
void stop(float dx, float dy) {
// we need to prevent IEEE floats polluting
// the position information, so even though
// the math is perfect in principle, round
// the result so that we're not going to be
// off by 0.0001 or something.
float resolution = 50;
x = int(resolution*(x+dx))/resolution;
y = int(resolution*(y+dy))/resolution;
ix = 0;
iy = 0;
aFrameCount = 0;
}
/**
* Sometimes actors need to be "invulnerable"
* while going through an animation. This
* is achieved by setting "interacting" to false
*/
void setInteracting(boolean _interacting) {
interacting = _interacting;
}
/**
* set whether or not this actor interacts
* with the level, or just the player
*/
void setPlayerInteractionOnly(boolean v ) {
onlyplayerinteraction = v;
}
/**
* Does this actor temporary not interact
* with any Interactors? This function
* is called by the layer level code,
* and should not be called by anything else.
*/
boolean isDisabled() {
if(disabledCounter > 0) {
disabledCounter--;
return true;
}
return false;
}
/**
* Sometimes we need to bypass interaction for
* a certain number of frames.
*/
void disableInteractionFor(int frameCount) {
disabledCounter = frameCount;
}
/**
* it's possible that an actor
* has to be removed from the
* level. If so, we call this method:
*/
void removeActor() {
animated = false;
visible = false;
states = null;
active = null;
remove = true;
}
/**
* Draw preprocessing happens here.
*/
void draw(float vx, float vy, float vw, float vh) {
if(!remove) handleInput();
super.draw(vx,vy,vw,vh);
}
/**
* Can this object be drawn in this viewbox?
*/
boolean drawableFor(float vx, float vy, float vw, float vh) {
return true;
}
/**
* Draw this actor.
*/
void drawObject() {
if(active!=null) {
active.draw(disabledCounter>0);
/*
if(debug) {
noFill();
stroke(255,0,0);
float[] bounds = getBoundingBox();
beginShape();
vertex(bounds[0]-x,bounds[1]-y);
vertex(bounds[2]-x,bounds[3]-y);
vertex(bounds[4]-x,bounds[5]-y);
vertex(bounds[6]-x,bounds[7]-y);
endShape(CLOSE);
}
*/
}
}
// ====== KEY HANDLING ======
protected final boolean[] locked = new boolean[256];
protected final boolean[] keyDown = new boolean[256];
protected int[] keyCodes = {};
// if pressed, and part of our known keyset, mark key as "down"
private void setIfTrue(int mark, int target) {
if(!locked[target]) {
if(mark==target) {
keyDown[target] = true; }}}
// if released, and part of our known keyset, mark key as "released"
private void unsetIfTrue(int mark, int target) {
if(mark==target) {
locked[target] = false;
keyDown[target] = false; }}
// lock a key so that it cannot be triggered repeatedly
protected void ignore(char key) {
int keyCode = int(key);
locked[keyCode] = true;
keyDown[keyCode] = false; }
// add a key listener
protected void handleKey(char key) {
int keyCode = int(key),
len = keyCodes.length;
int[] _tmp = new int[len+1];
arrayCopy(keyCodes,0,_tmp,0,len);
_tmp[len] = keyCode;
keyCodes = _tmp;
}
// check whether a key is pressed or not
protected boolean isKeyDown(char key) {
int keyCode = int(key);
return keyDown[keyCode];
}
protected boolean noKeysDown() {
for(boolean b: keyDown) { if(b) return false; }
for(boolean b: locked) { if(b) return false; }
return true;
}
// handle key presses
void keyPressed(char key, int keyCode) {
for(int i=0;i<keyCodes.length;i++){
//setIfTrue(keyCode,keyCodes[i]);
setIfTrue(int(key),keyCodes[i]);
}
}
// handle key releases
void keyReleased(char key, int keyCode) {
for(int i=0;i<keyCodes.length;i++){
//unsetIfTrue(keyCode,keyCodes[i]);
unsetIfTrue(int(key),keyCodes[i]);
}
}
/**
* Does the indicated x/y coordinate fall inside this drawable thing's region?
*/
boolean over(float _x, float _y) {
if (active == null) return false;
return active.over(_x - getX(), _y - getY());
}
void mouseMoved(int mx, int my) {}
void mousePressed(int mx, int my, int button) {}
void mouseDragged(int mx, int my, int button) {}
void mouseReleased(int mx, int my, int button) {}
void mouseClicked(int mx, int my, int button) {}
// ====== ABSTRACT METHODS ======
// token implementation
void handleInput() { }
// token implementation
void handleStateFinished(State which) { }
// token implementation
void pickedUp(Pickup pickup) { }
}
/**
* Boundaries are unidirectionally passable,
* and are positionable in the same way that
* anything else is.
*/
class Boundary extends Positionable {
private float PI2 = 2*PI;
// things can listen for collisions on this boundary
ArrayList<BoundaryCollisionListener> listeners;
/**
* Add a collision listener to this boundary
*/
void addListener(BoundaryCollisionListener l) { listeners.add(l); }
/**
* remove a collision listener from this boundary
*/
void removeListener(BoundaryCollisionListener l) { listeners.remove(l); }
/**
* notify all listners that a collision occurred.
*/
void notifyListeners(Actor actor, float[] correction) {
for(BoundaryCollisionListener l: listeners) {
l.collisionOccured(this, actor, correction);
}
}
// extended adminstrative values
float dx, dy, length;
float xw, yh;
float minx, maxx, miny, maxy;
float angle, cosa, sina, cosma, sinma;
// <1 means friction, =1 means frictionless, >1 means speed boost!
float glide;
// boundaries can be linked
Boundary prev, next;
float boundingThreshold = 1.5;
boolean disabled = false;
/**
* When we build a boundary, we record a
* vast number of shortcut values so we
* don't need to recompute them constantly.
*/
Boundary(float x1, float y1, float x2, float y2) {
// coordinates
x = x1;
y = y1;
xw = x2;
yh = y2;
// deltas
dx = x2-x1;
dy = y2-y1;
length = sqrt(dx*dx+dy*dy);
updateBounds();
updateAngle();
glide = 1.0;
listeners = new ArrayList<BoundaryCollisionListener>();
}
/**
* Update our bounding box information
*/
void updateBounds() {
xw = x + dx;
yh = y + dy;
minx = min(x, xw);
maxx = max(x, xw);
miny = min(y, yh);
maxy = max(y, yh);
}
/**
* Update our angle in the world
*/
void updateAngle() {
angle = atan2(dy, dx);
if (angle < 0) angle += 2*PI;
cosma = cos(-angle);
sinma = sin(-angle);
cosa = cos(angle);
sina = sin(angle);
}
void setPosition(float _x, float _y) {
super.setPosition(_x,_y);
updateBounds();
}
void moveBy(float dx, float dy) {
super.moveBy(dx,dy);
updateBounds();
}
/**
* This boundary is part of a chain, and
* the previous boundary is:
*/
void setPrevious(Boundary b) { prev = b; }
/**
* This boundary is part of a chain, and
* the next boundary is:
*/
void setNext(Boundary b) { next = b; }
/**
* Enable this boundary
*/
void enable() { disabled = false; }
/**
* Disable this boundary
*/
void disable() { disabled = true; }
/**
* Is this positionable actually
* supported by this boundary?
*/
// FIXME: this is not the correct implementation
boolean supports(Positionable thing) {
float[] bbox = thing.getBoundingBox(), nbox = new float[8];
// shortcut on "this thing has already been removed"
if (bbox == null) return false;
// First, translate all coordinates so that they're
// relative to the boundary's (x,y) coordinate.
bbox[0] -= x; bbox[1] -= y;
bbox[2] -= x; bbox[3] -= y;
bbox[4] -= x; bbox[5] -= y;
bbox[6] -= x; bbox[7] -= y;
// Then, rotate the bounding box so that it's
// axis-aligned with the boundary line.
nbox[0] = bbox[0] * cosma - bbox[1] * sinma;
nbox[1] = bbox[0] * sinma + bbox[1] * cosma;
nbox[2] = bbox[2] * cosma - bbox[3] * sinma;
nbox[3] = bbox[2] * sinma + bbox[3] * cosma;
nbox[4] = bbox[4] * cosma - bbox[5] * sinma;
nbox[5] = bbox[4] * sinma + bbox[5] * cosma;
nbox[6] = bbox[6] * cosma - bbox[7] * sinma;
nbox[7] = bbox[6] * sinma + bbox[7] * cosma;
// Get new bounding box minima/maxima
float mx = min(min(nbox[0],nbox[2]),min(nbox[4],nbox[6])),
MX = max(max(nbox[0],nbox[2]),max(nbox[4],nbox[6])),
my = min(min(nbox[1],nbox[3]),min(nbox[5],nbox[7])),
MY = max(max(nbox[1],nbox[3]),max(nbox[5],nbox[7]));
// Now, determine whether we're "off" the boundary...
boolean outOfBounds = (mx > length) || (MX < 0) || (MY<-1.99);
// if the thing's not out of bounds, it's supported.
return !outOfBounds;
}
/**
* If our direction of travel goes through the boundary in
* the "allowed" direction, don't bother collision detection.
*/
boolean allowPassThrough(float ix, float iy) {
float[] aligned = CollisionDetection.translateRotate(0,0,ix,iy, 0,0,dx,dy, angle,cosma,sinma);
return (aligned[3] < 0);
}
/**
* redirect a force along this boundary's surface.
*/
float[] redirectForce(float fx, float fy) {
float[] redirected = {fx,fy};
if(allowPassThrough(fx,fy)) { return redirected; }
float[] tr = CollisionDetection.translateRotate(0,0,fx,fy, 0,0,dx,dy, angle,cosma,sinma);
redirected[0] = glide * tr[2] * cosa;
redirected[1] = glide * tr[2] * sina;
return redirected;
}
/**
* redirect a force along this boundary's surface for a specific actor
*/
float[] redirectForce(Positionable p, float fx, float fy) {
return redirectForce(fx,fy);
}
/**
* Can this object be drawn in this viewbox?
*/
boolean drawableFor(float vx, float vy, float vw, float vh) {
// boundaries are invisible to begin with.
return true;
}
/**
* draw this platform
*/
void drawObject() {
strokeWeight(1);
stroke(255);
line(0, 0, dx, dy);
// draw an arrow to indicate the pass-through direction
float cs = cos(angle-PI/2), ss = sin(angle-PI/2);
float fx = 10*cs;
float fy = 10*ss;
line((dx-fx)/2, (dy-fy)/2, dx/2 + fx, dy/2 + fy);
float fx2 = 6*cs - 4*ss;
float fy2 = 6*ss + 4*cs;
line(dx/2+fx2, dy/2+fy2, dx/2 + fx, dy/2 + fy);
fx2 = 6*cs + 4*ss;
fy2 = 6*ss - 4*cs;
line(dx/2+fx2, dy/2+fy2, dx/2 + fx, dy/2 + fy);
}
/**
* Useful for debugging
*/
String toString() { return x+","+y+","+xw+","+yh; }
}
/**
* Things can listen to boundary collisions for a boundary
*/
interface BoundaryCollisionListener {
void collisionOccured(Boundary boundary, Actor actor, float[] intersectionInformation);
}/**
* A bounded interactor is a normal Interactor with
* one or more boundaries associated with it.
*/
abstract class BoundedInteractor extends Interactor implements BoundaryCollisionListener {
// the list of associated boundaries
ArrayList<Boundary> boundaries;
// are the boundaries active?
boolean bounding = true;
// simple constructor
BoundedInteractor(String name) { this(name,0,0); }
// full constructor
BoundedInteractor(String name, float dampening_x, float dampening_y) {
super(name, dampening_x, dampening_y);
boundaries = new ArrayList<Boundary>();
}
// add a boundary
void addBoundary(Boundary boundary) {
boundary.setImpulseCoefficients(ixF,iyF);
boundaries.add(boundary);
}
// add a boundary, and register as listener for collisions on it
void addBoundary(Boundary boundary, boolean listen) {
addBoundary(boundary);
boundary.addListener(this);
}
// FIXME: make this make sense, because setting 'next'
// should only work on open-bounded interactors.
void setNext(BoundedInteractor next) {
if(boundaries.size()==1) {
boundaries.get(0).setNext(next.boundaries.get(0));
}
}
// FIXME: make this make sense, because setting 'previous'
// should only work on open-bounded interactors.
void setPrevious(BoundedInteractor prev) {
if(boundaries.size()==1) {
boundaries.get(0).setPrevious(prev.boundaries.get(0));
}
}
// enable all boundaries
void enableBoundaries() {
bounding = true;
for(Boundary b: boundaries) {
b.enable();
}
}
// disable all boundaries
void disableBoundaries() {
bounding = false;
for(int b=boundaries.size()-1; b>=0; b--) {
Boundary boundary = boundaries.get(b);
boundary.disable();
}
}
/**
* We must make sure to remove all
* boundaries when we are removed.
*/
void removeActor() {
disableBoundaries();
boundaries = new ArrayList<Boundary>();
super.removeActor();
}
// draw boundaries
void drawBoundaries(float x, float y, float w, float h) {
for(Boundary b: boundaries) {
b.draw(x,y,w,h);
}
}
/**
* Is something attached to one of our boundaries?
*/
boolean havePassenger() {
// no passengers
return false;
}
/**
* listen to collisions on bounded boundaries
*/
abstract void collisionOccured(Boundary boundary, Actor actor, float[] intersectionInformation);
// when we update our coordinates, also
// update our associated boundaries.
void update() {
super.update();
// how much did we actually move?
float dx = x-previous.x;
float dy = y-previous.y;
// if it's not 0, move the boundaries
if(dx!=0 && dy!=0) {
for(Boundary b: boundaries) {
// FIXME: somehow this goes wrong when the
// interactor is contrained by another
// boundary, where the actor moves, but the
// associated boundary for some reason doesn't.
b.moveBy(dx,dy);
}
}
}
}
/**
* Alternative collision detection
*/
static class CollisionDetection {
private static boolean debug = false;
/**
* Static classes need global sketch binding
*/
private static PApplet sketch;
public static void init(PApplet s) { sketch = s; }
/**
* Perform actor/boundary collision detection
*/
static void interact(Boundary b, Actor a)
{
// no interaction if actor was removed from the game.
if (a.remove) return;
// no interaction if actor has not moved.
if (a.x == a.previous.x && a.y == a.previous.y) return;
float[] correction = blocks(b,a);
if(correction != null) {
b.notifyListeners(a, correction);
a.attachTo(b, correction);
}
}
/**
* Is this boundary blocking the specified actor?
*/
static float[] blocks(Boundary b, Actor a)
{
float[] current = a.getBoundingBox(),
previous = a.previous.getBoundingBox(),
line = {b.x, b.y, b.xw, b.yh};
return CollisionDetection.getLineRectIntersection(line, previous, current);
}
/**
* Perform line/rect intersection detection. Lines represent boundaries,
* and rather than doing "normal" line/rect intersection using a
* "box on a trajectory" that normal actor movement looks like, we pretend
* the actor box remains stationary, and move the boundary in the opposite
* direction with the same speed, which gives us a "boundary box", so that
* we can perform box/box overlap detection instead.
*/
static float[] getLineRectIntersection(float[] line, float[] previous, float[] current)
{
if(debug) sketch.println(sketch.frameCount + " ***");
if(debug) sketch.println(sketch.frameCount + "> testing against: "+arrayToString(line));
if(debug) sketch.println(sketch.frameCount + "> previous: "+arrayToString(previous));
if(debug) sketch.println(sketch.frameCount + "> current : "+arrayToString(current));
// First, let's do some dot-product math, to find out whether or not
// the actor's bounding box is even in range of the boundary.
float x1=line[0], y1=line[1], x2=line[2], y2=line[3],
fx = current[0] - previous[0],
fy = current[1] - previous[1],
pv=PI/2.0,
dx = x2-x1,
dy = y2-y1,
rdx = dx*cos(pv) - dy*sin(pv),
rdy = dx*sin(pv) + dy*cos(pv);
// is the delta in a permitted direction? If so, we don't have to do
// intersection detection because there won't be any.
float dotproduct = getDotProduct(rdx, rdy, fx, fy);
if(dotproduct<0) { return null; }
// then: in-range checks. If not in range, no need to do the more
// complicated intersection detections checks.
// determine range w.r.t. the starting point of the boundary.
float[] dotProducts_S_P = getDotProducts(x1,y1,x2,y2, previous);
float[] dotProducts_S_C = getDotProducts(x1,y1,x2,y2, current);
// determine range w.r.t. the end point of the boundary.
float[] dotProducts_E_P = getDotProducts(x2,y2,x1,y1, previous);
float[] dotProducts_E_C = getDotProducts(x2,y2,x1,y1, current);
// determine 'sidedness', relative to the boundary.
float[] dotProducts_P = getDotProducts(x1,y1,x1+rdx,y1+rdy, previous);
float[] dotProducts_C = getDotProducts(x1,y1,x1+rdx,y1+rdy, current);
// compute the relevant feature values based on the dot products:
int inRangeSp = 4, inRangeSc = 4,
inRangeEp = 4, inRangeEc = 4,
abovePrevious = 0, aboveCurrent = 0;
for(int i=0; i<8; i+=2) {
if (dotProducts_S_P[i] < 0) { inRangeSp--; }
if (dotProducts_S_C[i] < 0) { inRangeSc--; }
if (dotProducts_E_P[i] < 0) { inRangeEp--; }
if (dotProducts_E_C[i] < 0) { inRangeEc--; }
if (dotProducts_P[i] <= 0) { abovePrevious++; }
if (dotProducts_C[i] <= 0) { aboveCurrent++; }}
if(debug) sketch.println(sketch.frameCount +"> dotproduct result: start="+inRangeSp+"/"+inRangeSc+", end="+inRangeEp+"/"+inRangeEc+", sided="+abovePrevious+"/"+aboveCurrent);
// make sure to short-circuit if the actor cannot
// interact with the boundary because it is out of range.
boolean inRangeForStart = (inRangeSp == 0 && inRangeSc == 0);
boolean inRangeForEnd = (inRangeEp == 0 && inRangeEc == 0);
if (inRangeForStart || inRangeForEnd) {
if(debug) sketch.println(sketch.frameCount +"> this boundary is not involved in collisions for this frame (out of range).");
return null;
}
// if the force goes against the border's permissible direction, but
// both previous and current frame actor boxes are above the boundary,
// then we don't have to bother with intersection detection.
if (abovePrevious==4 && aboveCurrent==4) {
if(debug) sketch.println(sketch.frameCount +"> this box is not involved in collisions for this frame (inherently safe 'above' locations).");
return null;
} else if(0 < abovePrevious && abovePrevious < 4) {
if(debug) sketch.println(sketch.frameCount +"> this box is not involved in collisions for this frame (never fully went through boundary).");
return null;
}
// Now then, let's determine whether overlap will occur.
boolean found = false;
// We're in bounds: if 'above' is 4, meaning that our previous
// actor frame is on the blocking side of a boundary, and
// 'aboveAfter' is 0, meaning its current frame is on the other
// side of the boundary, then a collision MUST have occurred.
if (abovePrevious==4 && aboveCurrent==0) {
// note that in this situation, the overlap may look
// like full containment, where the actor's bounding
// box is fully contained by the boundary's box.
found = true;
if(debug) sketch.println(sketch.frameCount +"> collision detected (due to full containment).");
}
else {
// We're in bounds: do box/box intersection checking
// using the 'previous' box and the boundary-box.
dx = previous[0] - current[0];
dy = previous[1] - current[1];
// form boundary box
float[] bbox = {line[0], line[1],
line[2], line[3],
line[2]+dx, line[3]+dy,
line[0]+dx, line[1]+dy};
// do any of the "previous" edges intersect
// with any of the "boundary box" edges?
int i,j;
float[] p = previous, b = bbox, intersection;
for(i=0; i<8; i+=2) {
for(j=0; j<8; j+=2) {
intersection = getLineLineIntersection(p[i], p[i+1], p[(i+2)%8], p[(i+3)%8], b[j], b[j+1], b[(j+2)%8], b[(j+3)%8], false, true);
if (intersection != null) {
found = true;
if(debug) sketch.println(sketch.frameCount +"> collision detected on a box edge (box overlap).");
}
}
}
}
// Have we signaled any overlap?
if (found) {
float[] distances = getCornerDistances(x1,y1,x2,y2, previous, current);
int[] corners = rankCorners(distances);
if(debug) {
sketch.print(sketch.frameCount + "> ");
for(int i=0; i<4; i++) {
sketch.print(corners[i]+"="+distances[corners[i]]);
if(i<3) sketch.print(", "); }
sketch.println();
}
// Get the corner on the previous and current actor bounding
// box that will "hit" the boundary first.