I am trying to make the ball image to move randomly within the relativeLayoutGame layout using Timer and Random class. Please would you mind help me How to make sure the ball stay moving within the layout ( Not going off it ).
public void hide(View view){
final Timer tmr = new Timer();
final ImageView imgBall = (ImageView)findViewById(R.id.imgBall);
final RelativeLayout relativeLayGame = (RelativeLayout)findViewById(R.id.relativeLayGame);
final float gameLayoutWidth = relativeLayGame.getWidth();
final float gameLayoutHeiht = relativeLayGame.getHeight();
tmr.schedule(
new TimerTask() {
@Override
public void run() {
Random rnd = new Random();
int xRnd = rnd.nextInt(996)-996;
int yRnd = rnd.nextInt(1358)-1358;
if(xRnd == gameLayoutWidth || yRnd == gameLayoutHeiht){
xRnd = rnd.nextInt(996)-996;
yRnd = rnd.nextInt(1358)-1358;
imgBall.animate().xBy(xRnd).yBy(yRnd);
}else {
imgBall.animate().xBy(xRnd).yBy(yRnd);
}
}
},0,2000
);
}
Don't worry about the Random numbers I have, I was just frustrating after trying :D...
Note: I have googled it a lot but always I find a whole different thing far from Timer and Random. Also I am beginner so please try stick to the simplest for now or advice me on something advanced it would help ( But I would appreciate if it sort it out simply for now).
Thank you very much.
Aucun commentaire:
Enregistrer un commentaire