首页 > 解决方案 > 如何阻止对象离开屏幕?

问题描述

public class MovingBagView extends View {

    private Bitmap bag[] = new Bitmap[2];
    private int bagX;
    private int bagY = 1000;
    private int bagSpeed;
    private Boolean touch = false;
    private int canvasWidth, canvasHeight;
    private Bitmap backgroundImage;
    private Paint scorePaint = new Paint();
    private Bitmap life[] = new Bitmap[2];

    public MovingBagView(Context context) {
        super(context);
        bag[0] = BitmapFactory.decodeResource(getResources(), R.drawable.bag1);
        bag[1] = BitmapFactory.decodeResource(getResources(), R.drawable.bag2);
        backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
        scorePaint.setColor(Color.BLACK);
        scorePaint.setTextSize(40);
        scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
        scorePaint.setAntiAlias(true);
        life[0] = BitmapFactory.decodeResource(getResources(), R.drawable.heart);
        life[1] = BitmapFactory.decodeResource(getResources(), R.drawable.heart_grey);
        bagX = 10;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvasWidth = canvas.getWidth();
        canvasHeight = canvas.getHeight();
        canvas.drawBitmap(backgroundImage, 0, 0, null);
        int minBagX = bag[0].getWidth();
        int maxBagX = canvasWidth - bag[0].getWidth() * 3;
        bagX = bagX + bagSpeed;
        if (bagX < minBagX) {
            bagX = minBagX;
        }
        if (bagX < maxBagX) {
            bagX = maxBagX;
        }
        bagSpeed = bagSpeed + 2;
        if (touch) {
            canvas.drawBitmap(bag[1], bagX, bagY, null);
        }
        else {
            canvas.drawBitmap(bag[0], bagX, bagY, null);
        }
        canvas.drawText("Score : ", 20, 60, scorePaint);
        canvas.drawBitmap(life[0], 500, 10, null);
        canvas.drawBitmap(life[0], 570, 10, null);
        canvas.drawBitmap(life[0], 640, 10, null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            touch = true;
            bagSpeed = -12;
        }
        return true;
    }
}

我可以点击屏幕将对象向左移动,我点击它的次数越多,它应该向左移动得越远。但是,问题是对象向右移动太多,并且离开了屏幕。我希望它停在边缘,所以它仍然在屏幕上可见。此外,对象位于屏幕的中心底部,如何将其定位到左下角?您可以通过查看下面的 GIF 来了解它是如何工作的。

游戏应用

标签: javaandroid

解决方案


此条件永远不会应用于您提供的代码。它继续超过最大值。

if (bagX < maxBagX) {
       bagX = maxBagX;
   }

它应该如下所示:

if (bagX >= maxBagX) {
       bagX = maxBagX;
   }

而maxBagX的值应该是canvasWidth - bag[0].getWidth()为了实现包本身的右边缘。(除非您出于不同的原因使用乘法 3 次,否则这应该是解决方案。)


推荐阅读