I am making a game. In the game there is a method called movement() listed below that moves one circle down. I want the game to run the gamelost() method once the circle tbc's y value goes greater than yc's y value. So basically once tbc falls from the top of the phone screen past yc, the game runs the gamelost() method.
I tried putting the if statement in the main method after movement(); and even in the movement() method, for both the game does not say game over... Instead the circle just falls below from the top of the screen to the bottom an disappears. Did I do something wrong. Can someone please help me with this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onCreateNew();
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onPlayClick();
getColor();
movement();
}
});
protected void movement(){
final int delay = delay();
h.postDelayed(new Runnable() {
public void run() {
tgc.setY(tgc.getY() + 8);
tbc.setY(tbc.getY() + 8);
trc.setY(trc.getY() + 8);
tyc.setY(tyc.getY() + 8);
h.postDelayed(this, delay);
}
},delay);
if (tbc.getY() > yc.getY()){
gameLost();
} }
}
1 Answer 1
Welcome to Asynchronous Programming.
PostDelayed is starting an asynchronous thread. So the code to check for gameLost should be inside the new Runnable
protected void movement(){
final int delay = delay();
h.postDelayed(new Runnable() {
public void run() {
tgc.setY(tgc.getY() + 8);
tbc.setY(tbc.getY() + 8);
trc.setY(trc.getY() + 8);
tyc.setY(tyc.getY() + 8);
if (tbc.getY() > yc.getY()){
gameLost();
}
h.postDelayed(this, delay);
}
},delay);
}
}