2013-05-29 41 views
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(); 
} 

}

回答

2

你真的要在每一个通槽的onDraw()产生randX和Randy新的随机值?如果我理解你的权利,这一点应该被移动到构造函数:

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

编辑:另外,去掉“INT” S像这样:

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 
    } 
}