如何让苹果从屏幕上方掉落?

How to make an apple fall from the top of the screen?

我想让一个苹果从屏幕顶部掉到底部。我发现以下解决方案效果很好。但是只有一个问题,如果我将变量 changingY 更改为 localCoordinates2.getY() 苹果不再移动,那么我怎样才能让苹果掉下来呢?

    canvas.drawBitmap(localGoodApple.getGraphic(), localCoordinates2.getX(),changingY, null);
    if(changingY < canvas.getHeight() ) {
        changingY +=10; // The changingY is a field of type integer 
    }else
    {
        changingY = 0;
    }

如果将 changingY 更改为 localCoordinates2.getY() 苹果将不会移动,因为 getY() 只是返回 localCoordinates2 上 ​​y 的值,而不是参考值,因此您对getY() 实际上不会改变 y.

将您的代码更改为此(假设 setY 是一种方法):

canvas.drawBitmap(localGoodApple.getGraphic(), localCoordinates2.getX(), localCoordinates2.getY(), null);
if(localCoordinates2.getY() < canvas.getHeight() ) {
    localCoordinates2.setY(localCoordinates2.getY() + 10);
} else
{
    localCoordinates2.setY(0);
}