EOS 2  1.1.0
Einfache Objektbasierte Sprache
CollisionDetection.java
gehe zur Dokumentation dieser Datei
1 package de.lathanda.eos.game.geom;
2 
3 import de.lathanda.eos.game.Game;
4 import de.lathanda.eos.game.Sprite;
5 import java.util.SortedSet;
6 import java.util.TreeSet;
7 
34 public class CollisionDetection {
35 
39  private final SortedSet<Sprite> list = new TreeSet<>();
40  private final Game game;
44  public CollisionDetection(Game game) {
45  this.game = game;
46  }
47 
56  public void addObject(Sprite sprite) {
57  list.add(sprite);
58  }
59 
66  public void removeObject(Sprite sprite) {
67  list.remove(sprite);
68  }
69 
76  public void checkCollision() {
77  /*
78  * result is the only set that scales with O(n²), but we cannot avoid
79  * that effect, as there can be so many collisions
80  */
81 
82  SortedSet<ShapeOrder> xList = new TreeSet<>();
83  SortedSet<Shape> open = new TreeSet<>();
84  Collision col;
85 
86  // phase 1: sort objects
87  Shape shape;
88  for (Sprite w : list) {
89  shape = w.getShape();
90  if (shape != null) {
91  shape.setSprite(w);
92  xList.add(new ShapeOrder(ShapeOrder.OrderType.X0, shape));
93  xList.add(new ShapeOrder(ShapeOrder.OrderType.X1, shape));
94  } else {
95  // this is legal
96  // it can be used in order to temporary prevent collisions
97  }
98  }
99 
100  // phase 2: scan for potential collisions
101  // we enter every potential x collision into a tree structure
102  for (ShapeOrder shapeOrder : xList) {
103  switch (shapeOrder.bracket) {
104  case OPEN:
105  open.add(shapeOrder.shape);
106  break;
107  case CLOSE:
108  open.remove(shapeOrder.shape);
109 
110  // every id that is open collides with this id
111  for (Shape id : open) {
112  if (id.getBottom() < shapeOrder.shape.getTop() && shapeOrder.shape.getBottom() < id.getTop()) {
113  col = new Collision(shapeOrder.shape, id);
114  // the rectangle bounds intersect, now we check if they
115  // really collide
116  // this avoids testing every pair with the really slow
117  // exact calculations
118  if (col.verifyCollision()) {
119  if (!col.a.getSprite().processCollision(col.b.getSprite(), game)) {
120  col.b.getSprite().processCollision(col.a.getSprite(), game);
121  }
122  }
123  }
124  }
125  break;
126  }
127  }
128  }
129 }
void setSprite(Sprite sprite)
Definition: Shape.java:91
Impressum