package me.hammerle.supersnuvi.util; import me.hammerle.supersnuvi.tiles.Tile; public class Utils { public static float interpolate(float from, float to, float factor) { return from + (to - from) * factor; } public static int toBlock(float c) { return (int) (c / Tile.SIZE); } public static float toCoord(int b) { return b * Tile.SIZE; } public static float getSquaredDistance(float x1, float y1, float x2, float y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } public static Face getCollidingFace( float xMin1, float yMin1, float xMax1, float yMax1, float xMin2, float yMin2, float xMax2, float yMax2) { float diffUp = yMax1 - yMin2; float diffRight = xMax2 - xMin1; float diffDown = yMax2 - yMin1; float diffLeft = xMax1 - xMin2; float min = diffUp; Face f = Face.UP; if(min > diffRight) { min = diffRight; f = Face.RIGHT; } if(min > diffDown) { min = diffDown; f = Face.DOWN; } if(min > diffLeft) { f = Face.LEFT; } int c = 0; c += (min == diffUp) ? 1 : 0; c += (min == diffRight) ? 1 : 0; c += (min == diffDown) ? 1 : 0; c += (min == diffLeft) ? 1 : 0; if(c >= 2) { return Face.NULL; } return f; } public static boolean intersect(float x11, float y11, float x12, float y12, float x21, float y21, float x22, float y22) { if(compareFloats(x11, x12)) { if(compareFloats(x21, x22)) { return false; } else { if(!isBetween(x11, x21, x22)) { return false; } float k = (y21 - y22) / (x21 - x22); float d = y22 - k * x22; float y = d + x11 * k; return isBetween(y, y11, y12) && isBetween(y, y21, y22); } } else { if(compareFloats(x21, x22)) { if(!isBetween(x21, x11, x12)) { return false; } float k = (y11 - y12) / (x11 - x12); float d = y12 - k * x12; float y = d + x21 * k; return isBetween(y, y11, y12) && isBetween(y, y21, y22); } else { float k1 = (y11 - y12) / (x11 - x12); float k2 = (y21 - y22) / (x21 - x22); if(compareFloats(k1, k2)) { return false; } float d1 = y12 - k1 * x12; float d2 = y22 - k2 * x22; float x = (d1 - d2) / (k2 - k1); if(!isBetween(x, x11, x12) || !isBetween(x, x21, x22)) { return false; } float y = k1 * x + d1; return isBetween(y, y11, y12) && isBetween(y, y21, y22); } } } private static final float ERROR = 1.0f / 512.0f; private static boolean isBetween(float y, float y1, float y2) { float min = Math.min(y1, y2) - ERROR; float max = Math.max(y1, y2) + ERROR; return y >= min && y <= max; } private static boolean compareFloats(float a, float b) { return Math.abs(a - b) < ERROR; } }