我想创建一些球,当它碰到边缘时,它会返回,而当它们彼此碰到时,它们会返回!我能够创建第一个!但我认为由于循环,大量创建球会消耗大量内存!谁能向我介绍一些更好的实施方法?
public class BouncingBall extends View{
private int xMin = 0;
private int xMax;
private int yMin = 0;
private int yMax;
private float ballRadius = 50;
private float ballX = ballRadius + 200;
private float ballY = ballRadius + 400;
private float ballSpeedX ;
private float ballSpeedY ;
private RectF ballBounds ;
private Paint paint;
private Random rand ;
public BouncingBall(Context context,float ballSpeedX, float ballSpeedY,float ballRadius,float ballX,float ballY){
super(context);
ballBounds = new RectF();
paint = new Paint();
this.ballSpeedY = ballSpeedY;
this.ballSpeedX = ballSpeedX;
this.ballRadius = ballRadius;
this.ballX = ballX;
this.ballY = ballY;
rand = new Random();
int pickColor = rand.nextInt(3);
switch (pickColor){
case 0 :
paint.setColor(Color.parseColor("#6575ec"));
break;
case 1 :
paint.setColor(Color.parseColor("#f7c644"));
break;
case 2:
paint.setColor(Color.parseColor("#f54458"));
break;
default:
paint.setColor(Color.parseColor("#6575ec"));
}
}
@Override
protected void onDraw(Canvas canvas) {
ballBounds.set(ballX-ballRadius, ballY-ballRadius,ballX+ballRadius,ballY+ballRadius);
canvas.drawOval(ballBounds,paint);
update();
try {
Thread.sleep(10);
}catch (InterruptedException e){
}
invalidate();
}
private void update(){
ballX += ballSpeedX;
ballY += ballSpeedY;
if (ballX + ballRadius > xMax){
ballSpeedX = -ballSpeedX;
ballX = xMax-ballRadius;
}else if (ballX - ballRadius < xMin){
ballSpeedX = -ballSpeedX;
ballX = xMin+ballRadius;
}
if (ballY + ballRadius > yMax){
ballSpeedY = -ballSpeedY;
ballY = yMax-ballRadius;
}else if (ballY - ballRadius < yMin){
ballSpeedY = -ballSpeedY;
ballY = yMin+ballRadius;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
xMax = w-1;
yMax = h-1;
}
}