2012-04-24 57 views
0

我正在做一个游戏。 它有球会从屏幕。要边来做到这一点,我用随机创建从屏幕边缘移动的球

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出现。

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

回答

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; 
    } 

这会始终把你的球沿着你的框架的两侧......

+0

你有没有尝试这个? – 5hssba 2012-04-26 11:10:30