2013-11-14 44 views
0

我是新来的stackoverflow,我希望你能回答我的问题。 我有以下移动代码。我想要一个条件乘以

public MovementView(Context context) { 
    super(context); 
    getHolder().addCallback(this); 
    circleRadius = circleRadius2 = 50; 
    circlePaint = new Paint(); 
    circlePaint2 = new Paint(); 
    circlePaint.setColor(Color.GREEN); 
    circlePaint2.setColor(Color.RED);   
    xVel = 10; 
    yVel = 10; 
    xVel2 = 20; 
    yVel2 = 20; 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    canvas.drawColor(Color.WHITE); 
    canvas.drawCircle(xPos, yPos, circleRadius, circlePaint); 
    canvas.drawCircle(xPos2, yPos2, circleRadius2, circlePaint2); 
} 
public void updatePhysics() { 
    xPos += xVel; 
    yPos += yVel; 
    if (yPos - circleRadius < 0 || yPos + circleRadius > height) { 
     if (yPos - circleRadius < 0) { 
      yPos = circleRadius; 
     }else{ 
      yPos = height - circleRadius; 
     } 
     yVel *= -1; 
    } 
    if (xPos - circleRadius < 0 || xPos + circleRadius > width) { 
     if (xPos - circleRadius < 0) { 
      xPos = circleRadius; 
     } else { 
      xPos = width - circleRadius; 
     } 
     xVel *= -1; 
    }   
    xPos2 += xVel2; 
    yPos2 += yVel2; 
    if (yPos2 - circleRadius2 < 0 || yPos2 + circleRadius2 > height) { 
     if (yPos2 - circleRadius2 < 0) { 
      yPos2 = circleRadius2; 
     }else{ 
      yPos2 = height - circleRadius2; 
     } 
     yVel2 *= -1; 
    } 
    if (xPos2 - circleRadius2 < 0 || xPos2 + circleRadius2> width) { 
     if (xPos2 - circleRadius2 < 0) { 
      xPos2 = circleRadius2; 
     } else { 
      xPos2 = width - circleRadius2; 
     } 
     xVel2 *= -1; 
    } 

} 

public void surfaceCreated(SurfaceHolder holder) { 
    Rect surfaceFrame = holder.getSurfaceFrame(); 
    width = surfaceFrame.width(); 
    height = surfaceFrame.height(); 
    xPos = xPos2 = width/2; 
    yPos = yPos2 = circleRadius; 
    updateThread = new UpdateThread(this); 
    updateThread.setRunning(true); 
    updateThread.start(); 
} 
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
} 
public void surfaceDestroyed(SurfaceHolder holder) { 
    boolean retry = true; 
    updateThread.setRunning(false); 
    while (retry) { 
     try { 
      updateThread.join(); 
      retry = false; 
     } catch (InterruptedException e) { 
     } 
    } 
} 

这定义了具有特定边界的两个圆的运动。现在我想添加更多的圈子,大约10到20.是否可以给一个变量而不是复制代码(就像我为两个圆圈做的那样)?

回答

0

有很多方法可以做到这一点。常用的方法是创建一个World对象并创建一个Circle类。

然后,世界可以创建任意数量的圆形物体。

要移动圆圈,您可以使用另一个控制对象,如“物理”,或者创建一个给每个圆圈的移动控制器。然后,世界将要求每个圈子移动,并可能将自己吸引到世界画布上。