创建从屏幕边缘移动的球

时间:2012-04-24 10:37:42

标签: android canvas

我在做游戏。 它会让球从屏幕边缘移动。为此,我使用了随机函数

public void random(){
    Random rnd = new Random(System.currentTimeMillis());
    x = rnd.nextInt(gameView.getWidth() - bmp.getWidth());
    y = rnd.nextInt(gameView.getHeight() - bmp.getHeight());
    xSpeed = rnd.nextInt(10) - 5;
    ySpeed = rnd.nextInt(10) - 5;
    x = x + xSpeed;
    y = y + ySpeed;
}

如果我用过:

x = rnd.nextInt(gameView.getWidth() - bmp.getWidth()); 
y = rnd.nextInt(gameView.getHeight() - bmp.getHeight()); 

球将出现在任何位置。如果我用过:

x = 0, y = rnd.nextInt(gameView.getHeight() - bmp.getHeight());

球将沿着Oy轴出现。

但我不能在屏幕的所有边缘出现球。 请帮帮我。谢谢,

1 个答案:

答案 0 :(得分:0)

你可以在函数中添加一些逻辑,如...

   x = rnd.nextInt(gameView.getWidth() - bmp.getWidth());
y = rnd.nextInt(gameView.getHeight() - bmp.getHeight());
//here
if(x<y){
 x=0;
}

else if(y<x){
  y=0;
}
 else{
 x=0;
  y=0;
  }

这将始终将球放在框架的两侧......