Blacklight119
Blacklight119

Reputation: 17

Getting coordinates on touch event relative to scrollable map

Is there a way to get the coordinates of a touch event on a scrollable map?

Meaning when I touch at one point on the screen, getX() and getY() return the respective values and then when I scroll the map, the coordinates returned should be relative to the map, not the screen.
eg. I have a 750x750 background map, and my device screen size is 480x800.
when I first touch, say the coordinates returned are (100, 200). now when I scroll the map and touch somewhere else, I get the coordinates as 200, 200.
I want to get the coordinates with respect to the map and not the screen.

I've been trying to figure this out for a long time and have scoured the net and other sites in vain.

please help.
thanks in advance
\m/

i need the coordinates coz i'm developing a game in which i have a large map and objects placed on it. when i scroll the map, i need the objects to move along with in the same position. here is my code:

@Override
public boolean onTouchEvent(MotionEvent ev) {

    switch (ev.getAction()) {

    case MotionEvent.ACTION_DOWN:
         touchStart.set(ev.getX(), ev.getY());
     x = ev.getX();
     y = ev.getY();
        break;
    case MotionEvent.ACTION_MOVE:
        newX = ev.getX() - touchStart.x + prevPicStart.x;
        newY = ev.getY() - touchStart.y + prevPicStart.y;
        if ((newX <= 0 && newX > 0 - mBG.getWidth() + Craz.DISP_WIDTH)) {
            picStart.x = newX;
          }
        if ((newY <= 0 && newY > 0 - mBG.getHeight() + Craz.DISP_HEIGHT)) {
            picStart.y = newY;

        }
        invalidate();
        break;

    case MotionEvent.ACTION_UP:

        prevPicStart.x = picStart.x;
        prevPicStart.y = picStart.y;

        break;
    }
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    canvas.drawBitmap(mBG, picStart.x, picStart.y, paint);

    canvas.translate(picStart.x, picStart.y);

    mBDoor.draw(canvas);
}

Upvotes: 1

Views: 7200

Answers (1)

WarrenFaith
WarrenFaith

Reputation: 57672

Its pretty easy. When you scroll your map, you have an offset. If you scroll to the right (the background will move to the left), your offset will be negative. Lets say, you have an offset on x of -50, and you click the screen coordinates 100 you simply do the math:

mapCoordX = screenX - offsetX; // makes: 100 - (-50) = 150

just looking at the X coordinate, for Y it should be the same.

I have written a tutorial about a map of tiles and scrolling over it. Maybe you take a look at it, too.

Pseudocode!

for (int id = 0; id < mapSize; id++) {
  Tile tile = new Tile(id);
  startX = id * tileWidth;
  startY = id % rowLenght + id / rowLenght;
  tile.setBackground(createCroppedBitmap(background, startX, startY));
}

Upvotes: 2

Related Questions