我的应用程序İ想让球在特定区域(矩形)内移动。直到现在,球在矩形下方的背景区域中在屏幕周围移动。我试过几次改变坐标,但它没有用。任何人都可以帮助我让球在矩形内移动吗?
class DrawView extends View {
int x,y,x1,y1;
int a=431,b=641, a1=54,b1=54;
int sayac=0;
Canvas can;
Paint paint = new Paint();
Rect r = new Rect(60, 60, 400, 610);
Paint por= new Paint();
// Font bold;
public DrawView(Context context) {
super(context);
paint.setColor(Color.RED);
}
private void update() {
if(a>605){x=-(int)(Math.random()*7+5); }
if(a<55){x=(int)(Math.random()*7+5); }
if(b>395){y=-(int)(Math.random()*7+5); }
if(b<55){y=(int)(Math.random()*7+5); }
if(a1>605){x1=-(int)(Math.random()*7+5); }
if(a1<55){x1=(int)(Math.random()*7+5); }
if(b1>395){y1=-(int)(Math.random()*7+5); }
if(b1<55){y1=(int)(Math.random()*7+5); }
a+=x;
b+=y;
a1+=x1;
b1+=y1;
}
@Override
protected void onDraw(Canvas canvas) {
paint.setTextSize(20);
paint.setColor(Color.YELLOW);
canvas.drawCircle(a, b, 50, paint);
paint.setColor(Color.BLUE);
canvas.drawText("Pamukcu", a-41, b+7, paint);
/* paint.setColor(Color.RED);
canvas.drawLine(40, 40, 600, 40, paint);
paint.setStrokeWidth(10f);
canvas.drawLine(40, 600, 600, 600, paint);
canvas.drawLine(40, 40, 40, 600, paint);
canvas.drawLine(600, 40, 40, 600, paint);
*/
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.MAGENTA);
canvas.drawRect(r, paint);
update();
try{
Thread.sleep(1);
}catch(InterruptedException e){ }
invalidate();
private void update() {
if(a>605){x=-(int)(Math.random()*7+5); }
if(a<55){x=(int)(Math.random()*7+5); }
if(b>395){y=-(int)(Math.random()*7+5); }
if(b<55){y=(int)(Math.random()*7+5); }
if(a1>605){x1=-(int)(Math.random()*7+5); }
if(a1<55){x1=(int)(Math.random()*7+5); }
if(b1>395){y1=-(int)(Math.random()*7+5); }
if(b1<55){y1=(int)(Math.random()*7+5); }
a+=x;
b+=y;
a1+=x1;
b1+=y1;
}
@Override
protected void onDraw(Canvas canvas) {
paint.setTextSize(20);
paint.setColor(Color.YELLOW);
canvas.drawCircle(a, b, 50, paint);
paint.setColor(Color.BLUE);
canvas.drawText("Ball", a-41, b+7, paint);
答案 0 :(得分:0)
如果你想要球只能在矩形内移动,你可以这样做:
int rectangleX = 100;
int rectangleY = 100;
int rectangleWidht = 200;
int rectangleHeight = 300;
private void KeepBallInsideRectangle() {
if (ballX < rectanlgeX) ballX = rectangleX;
if (ballX > rectangleX+rectangleWidth) ballX = rectangleX+rectangleWidth;
if (ballY < rectanlgeY) ballY = rectangleY;
if (ballY > rectangleY+rectanglHeight) ballY = rectangleY+rectangleHeight;
}
您只需检查球的位置是否在矩形之外,然后将其位置设置为矩形的边框。