gpt4 book ai didi

java - 如何阻止对象离开屏幕?

转载 作者:搜寻专家 更新时间:2023-11-01 09:21:56 25 4
gpt4 key购买 nike

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 来了解它是如何工作的。

game application

最佳答案

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

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

它应该是这样的:

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

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

关于java - 如何阻止对象离开屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54345823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com