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 int yellowX = 500, yellowY, yellowSpeed = -16;
private Paint yellowPaint = new Paint();
private int score;
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);
yellowPaint.setColor(Color.YELLOW);
yellowPaint.setAntiAlias(false);
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;
score = 0;
}
@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() * 2;
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);
}
yellowY = yellowY - yellowSpeed;
if (hitBallChecker(yellowX, yellowY)) {
score = score + 10;
yellowY = -100;
}
if (yellowY < 0) {
yellowY = canvasHeight + 21;
yellowX = (int)Math.floor(Math.random() * (maxBagX - minBagX)) + maxBagX;
}
canvas.drawCircle(yellowX, yellowY, 15, yellowPaint);
canvas.drawText("Score : " + 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);
}
public boolean hitBallChecker(int x, int y) {
if (bagY < y && y < (bagY + bag[0].getHeight()) && bagX < x && x < (bagX + bag[0].getWidth())) {
return true;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touch = true;
bagSpeed = -22;
}
return true;
}
}
我已经弄清楚了如何使球从屏幕顶部掉落。该代码应该使多个黄色球从屏幕顶部掉落,但是只有一个黄色球掉落。随机的黄色小球应该从顶部掉落,并且从不同的位置掉落。您可以在下面查看其预览:
答案 0 :(得分:0)
要实现此目的,您应该考虑创建一个自定义对象Ball
public class Ball{
public int x;
public int y;
public int speed;
public Ball(int x, int y, int speed){
this.x = x;
this.y = y;
this.speed = speed;
}
}
然后,您可以在ArrayList中添加多个Ball,然后在draw()
中迭代遍历数组中的每个Ball,并对每个Ball进行相同的操作。
for(int i = 0; i < balls.length(); i++){
Ball ball = balls.get(i);
ball.y -= ball.speed;
// check for collisions
// draw ball
}