开发者

finding sprite position relative to background image

can anyone tell me how to find out the relative position of a sprite imag开发者_StackOverflowe with respect to a background image? i.e. when the background is panned (scrolled) the image should move along with the background.


Is the Sprite a child of the background image? If not, you can use a method called localtoGlobal which converts the point object from the Sprite's (local) coordinates to the background's (global) coordinates.

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html#localToGlobal%28%29


One possible solution is to use virtual x and y sprite positions, and have an origin x and y position (which would be the top left of the screen).

When you want to scroll your screen, you just modify the origin x and y position.

Then anywhere you draw something to the screen, you need to subtract the origin position from the virtual position.

Eg.

canvas.drawBitmap(bitmap, x - originX, y - originY, paint);

Whenever you move any sprite you manipulate their 'virtual' x and y positions. If you translate the virtual x, y to actual screen x, y by subtracting the origin everything will move together.

Now for example, if you wanted your background to scroll from right to left, you'd just add to originX every frame.


okay...for making the sprite movce along with the background when scrolled, the code is:

initialize

PointF touchStart = new PointF();
PointF picStart = new PointF();
PointF prevPicStart = new PointF();

and implement this in the onTouchEvent() method:

@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 - BG_image.getWidth() + ActivityClass.DISP_WIDTH)) {
            picStart.x = newX;
        }

        if ((newY <= 0 && newY > 0 - BG_image.getHeight() + ActivityClass.DISP_HEIGHT)) {
            picStart.y = newY;
        }

        invalidate();
        break;
    }

    case MotionEvent.ACTION_UP:

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

        break;

    }
    return true;
}

onDraw() method:

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

    canvas.translate(picStart.x, picStart.y);
   person.draw(canvas);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜