0

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);

I draw mousePath to see where the mousePath is and this is the result I get (it is the box in green and where the mouse actually is in the general area of the blue circle)

enter image description here

This is the much more severe point, as it seems the closer I get to (0,0) the closer mousePath gets to being at where the mouse actually is.

So how do I get the mouse to be in the correct location?

Ryan
  • 727
  • 2
  • 14
  • 31

1 Answers1

0

After more searching it turns out this question is a duplicate of: https://stackoverflow.com/a/24895485/4188097.

The browser always returns the mouse position in untransformed coordinates. Your drawings have been done in transformed space. If you want to know where your mouse is in transformed space, you can convert untransformed mouse coordinates to transformed coordinates like this:

var mouseXTransformed = (mouseX-panX) / scaleFactor;
var mouseYTransformed = (mouseY-panY) / scaleFactor;
Ryan
  • 727
  • 2
  • 14
  • 31