这是我第三次提出这样的问题。我已经阅读了所有类似的问题,之前的帮助很有用,但这次我想为这个应用添加一个新功能。我有一个应用程序可以使球移动一圈。
现在我想将球放在屏幕上的随机位置,然后移动一圈。我认为我的逻辑大多是正确的但是球不规律地跳了起来 - 无论我多少用数学。代码如下。
有谁知道我做错了什么?
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();
}
}
答案 0 :(得分:2)
你是否真的想在每次传递onDraw()时为randX和randY生成新的随机值?如果我理解你,那么这一点应该移到构造函数中:
int randX = 1 + (int)(Math.random()*500);
int randY = 1 + (int)(Math.random()*500);
编辑:另外,删除&#34; int&#34; 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
}
}