0

这已经是我第三次问这样的问题了。我已经阅读了所有类似的问题,之前的帮助很有用,但这次我想为这个应用程序添加一个新功能。我有一个应用程序可以让球绕圈移动。

现在我想将球放在屏幕上的任意位置,然后绕一圈移动。我想我的逻辑大部分是正确的,但是球跳得不规律——不管我玩了多少数学。代码如下。

有谁知道我做错了什么?

public class DrawingTheBall extends View {

Bitmap bball; 

int randX, randY;
double theta;


public DrawingTheBall(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    bball = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);

    randX = 1 + (int)(Math.random()*500); 
    randY = 1 + (int)(Math.random()*500);
    theta = 45;
}

  public void onDraw(Canvas canvas){
    super.onDraw(canvas);

    Rect ourRect = new Rect();
    ourRect.set(0, 0, canvas.getWidth(), canvas.getHeight()/2);
    float a = 50;
    float b = 50;
    float r = 50;

    int x = 0;
    int y = 0;

    theta = theta + Math.toRadians(2);


    Paint blue = new Paint();
    blue.setColor(Color.BLUE);
    blue.setStyle(Paint.Style.FILL);

    canvas.drawRect(ourRect, blue);

    if(x < canvas.getWidth()){

        x = randX + (int) (a +r*Math.cos(theta));
    }else{
        x = 0;
    }
    if(y < canvas.getHeight()){

        y = randY + (int) (b +r*Math.sin(theta));
    }else{
        y = 0;
    }
    Paint p = new Paint();
    canvas.drawBitmap(bball, x, y, p);
    invalidate();
}

}

4

1 回答 1

2

您真的是要在每次通过 onDraw() 时为 randX 和 randY 生成新的随机值吗?如果我理解正确,则应将此位移至构造函数中:

int randX = 1 + (int)(Math.random()*500); 
int randY = 1 + (int)(Math.random()*500);

编辑:另外,删除“int”:

randX = 1 + (int)(Math.random()*500); 
randY = 1 + (int)(Math.random()*500);

这种方式将为您的类级变量分配值,而不是创建局部变量(永远不会被读取)。如果这没有意义,这里有一个更清晰的解释:

class foo {
    int x = 1;      // this is a class-level variable
    public foo() {
        bar1();
        System.out.println(x);  // result: 1
        bar2();
        System.out.println(x);  // result: 2
    }
    public void bar1() {
        int x = 2;  // This instantiated a new 
                    // local variable "x", it did not 
                    // affect the global variable "x"
    }
    public void bar2() {
        x = 2;      // This changed the class var
    }
}
于 2013-05-29T19:55:48.050 回答