让我说我有2个球1个名字gball另一个蓝色。 我基本上试图做的是每次我的gball中心点(x,y) 在蓝色里面 blueb将改变位置到一个随机的地方 问题是blueb不会改变位置和音频剂量工作(MyAudio是启动音频的类)。 这是我的代码;
@Override
public void run() {
Random r = new Random();
int rX = r.nextInt(350 + 1);
int rY = r.nextInt(450 + 1);
while (isRunnning) {
if(!ourHolder.getSurface().isValid())
continue;
Canvas canvas=ourHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
if(x !=0 && y!=0){
Bitmap test=BitmapFactory.decodeResource(getResources(),R.raw.ball);
canvas.drawBitmap(test, x-test.getWidth()/2, y-test.getHeight()/2, null);
Bitmap blueb=BitmapFactory.decodeResource(getResources(), R.raw.bball);
canvas.drawBitmap(blueb, rX, rY, null);
if(x-test.getWidth()/2 <=rX+40 && x-test.getWidth()/2 >=rX-40 && y-test.getHeight()/2 <=rY+40 && y-test.getHeight()/2 >=rY-40 ) {
MediaPlayer mp1=MediaPlayer.create(GFXSurface.this, R.raw.im);
MyAudio beep=new MyAudio(mp1);
beep.getAudio().start();
rX = r.nextInt(350 + 1);
rY = r.nextInt(450 + 1);
canvas.drawBitmap(blueb, rX, rY, null);
}
}
注意:gball中心位于(x-test.getWidth()/ 2,y-test.getHeight()/ 2) 而40是蓝色半径。
答案 0 :(得分:0)
检查球重叠的条件是否有效。仔细看..
x-test.getWidth()/2 <=rX+40 && x-test.getWidth()/2 >=rX-40
条件评估为true的唯一方法是'test'的中心是否在'x'的确切中心。 'x'的中心不能小于和大于一个值;所以这只适用于平等情况。我假设你有一些物理系统或用户输入移动球,这意味着它将很少满足完全相等的情况,但它们将重叠很多。
你应该做的是获得每个球的半径,将它们加在一起,并检查'x'中心和'test'中心之间的距离是否小于组合半径。这会让你知道它们是否重叠。
答案 1 :(得分:0)
让我们一个接一个地看看条件。
if(x-test.getWidth()/2 <=rX+40 && x-test.getWidth()/2 >=rX-40 && y-test.getHeight()/2 <=rY+40 && y-test.getHeight()/2 >=rY-40 )
为了更好地理解我建议使用变量。我认为Tansir1没有注意到第二个条件有一个减号:
int gballCenterXCoordinate = x-test.getWidth()/2;
int gballCenterYCoordinate = y-test.getHeight()/2;
int bluebCenterXCoordinate = rX;
int bluebRightX = bluebCenterXCoordinate + 40;
int bluebLeftX = bluebCenterXCoordinate - 40;
int bluebCenterYCoordinate = rY;
int bluebTopY = bluebCenterYCoordinate + 40;
int bluebBottomY = bluebCenterYCoordinate - 40;
在此之后你的情况如下:
if(gballCenterXCoordinate <= bluebRightX &&
gballCenterXCoordinate >= bluebLeftX &&
gballCenterYCoordinate <= bluebTopY &&
gballCenterYCoordinate >= bluebBottomY )
如果gball以(bluebCenterX,bluebCenterY)为中心进入广场,则此条件为真。
您是否尝试调试代码到达if? 也许你的条件是真的,但if块中的代码不起作用?
希望这有帮助