Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public RayCollision rayCast(Double2 coords, Rotation angle, int maxRange) {
- // distances to the horizontal/vertical walls
- RayCollision h = new RayCollision(), v = new RayCollision();
- // intersections with "horizontal" walls
- if (angle.sina != 0) {
- // up and down are shuffled because of the coordinates system
- boolean downwards = angle.sina > 0;
- // coordinates of the first possible collision
- double invSinA = 1 / angle.sina, invTanA = angle.cosa * invSinA;
- double y = downwards ? Math.ceil(coords.y) : Math.floor(coords.y);
- double x = coords.x + (y - coords.y) * invTanA;
- Double2 current = new Double2(x, y);
- int tilesDistance = 0;
- // every next collisions are placed evenly (intercept theorem)
- Double2 step = new Double2((downwards ? 1 : -1) * invTanA, downwards ? 1 : -1);
- while (tilesDistance <= maxRange) {
- Int2 tileCoords = current.add(0, downwards ? 0.1 : -0.1).toInt();
- if (!tileField.isEmpty(tileCoords)) {
- h.tile = tileCoords;
- h.hitPoint = downwards ? current.x % 1 : 1 - current.x % 1;
- break;
- }
- current = current.add(step);
- tilesDistance++;
- }
- if (tilesDistance <= maxRange) {
- h.d = Math.abs((current.y - coords.y) * invSinA);
- }
- }
- // intersections with "vertical" walls
- if (angle.cosa != 0) {
- boolean right = angle.cosa > 0;
- // first collision
- double invCosA = 1 / angle.cosa, tanA = angle.sina * invCosA;
- double x = right ? Math.ceil(coords.x) : Math.floor(coords.x);
- double y = coords.y + (x - coords.x) * tanA;
- Double2 current = new Double2(x, y);
- int tilesDistance = 0;
- // next collisions
- Double2 step = new Double2(right ? 1 : -1, (right ? 1 : -1) * tanA);
- while (tilesDistance <= maxRange) {
- Int2 tileCoords = current.add(right ? 0.1 : -0.1, 0).toInt();
- if (!tileField.isEmpty(tileCoords)) {
- v.tile = tileCoords;
- v.hitPoint = right ? 1 - current.y % 1 : current.y % 1;
- break;
- }
- current = current.add(step);
- tilesDistance++;
- }
- if (tilesDistance <= maxRange) {
- v.d = Math.abs((current.x - coords.x) * invCosA);
- }
- }
- if (h.d < v.d) {
- return h;
- } else {
- return v;
- }
- }
- Double2 pos = player.getCoords();
- Rotation angle = player.getRotation();
- Rotation angleDelta = new Rotation(FOV / stripsCount);
- for (int i = 0; i < stripsCount; i++) {
- // multiplying by cosine scales the distances an removes the fish eye effect
- WalkingGameplay.RayCollision rayCollision = gameplay.rayCast(pos, angle, 10);
- angle = angle.combine(angleDelta);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement