Click here to Skip to main content
14,392,270 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have an android game where the canvas is scaled to look the same on all devices using this code:
canvas.scale((float)(getWidth()/(double)WIDTH), (float)(getHeight()/(double)HEIGHT))


where WIDTH and HEIGHT are 1920 and 1080 respectively. My problem is that for all my touch collisions (i.e. a user touching a shape) is handled using Paths and Regions:
public static boolean collided(Path a, Path b) {
    Region clip = new Region(0,0,3000, 3000);
    Region rA = new Region();
    rA.setPath(a, clip);
    Region rB = new Region();
    rB.setPath(b, clip);
    return !rA.quickReject(rB) && rA.op(rB, Region.Op.INTERSECT);
}


Now I also have another scale method (that barely has any effect from what I can tell, but on occasion does have an influence) to scale coordinates and dimensions:
public static double scale(double x) {
    return dpToPx(x)/Resources.getSystem().getDisplayMetrics().density;
}


My problem is that with all of this scaling I can't seem to get the mouse to be in the correct position. Here is the code I use to create the mouse Path that handles collision between the mouse and other shapes:

mouse.set(x, y);
mousePath.reset();
mousePath.addRect(mouse.x - 10, mouse.y - 10, mouse.x + 10, mouse.y + 10, Path.Direction.CW);


The mousePath box however ends up being nowhere near where the mouse/touch actually is. It gets farther away from the touch the farther the touch is from (0,0).

What I have tried:

scaling the (x,y) coordinates various way and using a matrix on the path like below.

Try 1
mouse.set(scale(x), scale(y));
mousePath.reset();
mousePath.addRect(mouse.x - 10, mouse.y - 10, mouse.x + 10, mouse.y + 10, Path.Direction.CW);


Try 2
mouse.set(x,y);
mousePath.reset();
mousePath.addRect(mouse.x - 10, mouse.y - 10, mouse.x + 10, mouse.y + 10, Point.Direction.CW);
Matrix matrix = new Matrix();
matrix.setScale((float)(getWidth()/(double)WIDTH), (float)(getHeight()/(double)HEIGHT);
mousePath.transfrom(matrix);


Each of these produced different results that were both very wrong and I am at a loss. Please help
Posted
Updated 6-Aug-17 17:05pm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100