1

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();
 } }
 }
Jitesh Dalsaniya
1,9173 gold badges20 silver badges36 bronze badges
asked Mar 2, 2017 at 6:26

1 Answer 1

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);
 }
 }
answered Mar 2, 2017 at 6:31
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Thanks for the response. I have another question. Does that mean i have to make all my other methods such as score and others called inside the asynchronous thread in movement too?
You need to know async programming; and understand the code flow, it is not a simple function call. You are sending code to be called at some point in future.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.