[英]Move object in a circle from random location
這是我第三次問這樣的問題。 我已經閱讀了所有類似的問題,之前的幫助很有用,但這次我想為這個應用添加一個新功能。 我有一個應用程序,讓一個球移動一圈。
現在我想將球放在屏幕上的隨機位置,然后移動一圈。 我認為我的邏輯大多是正確的但是球不規律地跳了起來 - 無論我多少用數學。 代碼如下。
有誰知道我做錯了什么?
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();
}
}
你是否真的想在每次傳遞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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.