java - 如何阻止对象离开屏幕?
问题描述
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 来了解它是如何工作的。
解决方案
此条件永远不会应用于您提供的代码。它继续超过最大值。
if (bagX < maxBagX) {
bagX = maxBagX;
}
它应该如下所示:
if (bagX >= maxBagX) {
bagX = maxBagX;
}
而maxBagX的值应该是canvasWidth - bag[0].getWidth()
为了实现包本身的右边缘。(除非您出于不同的原因使用乘法 3 次,否则这应该是解决方案。)
推荐阅读
- html - Box Html Css Fix For the Noob
- sql - oracle中如何将长数据转换为char || ORA-00932: 不一致的数据类型: 预期的 CHAR 得到了 LONG
- java - 退出应用程序时出现启动屏幕活动
- angular - 如何构建具有不同环境的角度项目
- python - 将 csv 文件中的字符串与日志文件匹配的正确方法是什么?
- node.js - 使用“pg:psql”命令连接 heroku 数据库时“连接超时”
- sql-server - 使用 SQL Server Ping IP 地址
- ajax - 如何在这个 wordpress 循环中添加加载更多按钮 ajax 按钮?
- c# - 相同表/类的 SQL 表设计
- c# - C# 为 ASP.NET Core 使用 System.Data.DataSet?