我有一个游戏,可以从图像框中在屏幕上生成 4 个敌人,当计时器达到零时,屏幕上就会生成一个敌人。我想要一种方法来不断检查敌人是否在屏幕上可见。
我的类当前包含一个 while 循环来检查可见性:
public class rear_gunner extends AppCompatActivity {
int clickcount=0;
CountDownTimer countDownTimer;
int score = 0;
int health2 = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rear_gunner);
final TextView text = (TextView) findViewById(R.id.textView2);
final TextView scoreText = (TextView) findViewById(R.id.score);
final TextView health = (TextView) findViewById(R.id.Health);
health.setText("Health:"+ health2);
//Enemy ImageViews
final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
final ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
final ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
final ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);
//sets screen orientation on created
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//sets imageViews into array
final ImageView[] enemies = new ImageView[4];
enemies[0] = enemy1;
enemies[1] = enemy2;
enemies[2] = enemy3;
enemies[3] = enemy4;
boolean running = true;
while (!running) {
if (enemy1.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy2.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy3.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy4.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
}
上面的代码根本不起作用。当我开始 Activity 时,屏幕变黑并保持这种状态直到关闭。这与我使用 while 循环运行的方式有什么关系吗?
我的计时器代码(如果需要):
//random number generator between 10-25
Random r = new Random();
int Low = 10000;
int High = 25000;
int Result = r.nextInt(High-Low) + Low;
//count down timer for spawing enemies
countDownTimer = new CountDownTimer(Result, 1000) {
@Override
public void onTick(long millisUntilFinished) {
text.setText("seconds remaining: " + millisUntilFinished / 1000);
if (score == 500)
{
countDownTimer.cancel();
}
}
@Override
public void onFinish() {
Random r = new Random();
int Low = 0;
int High = 4;
int Result = r.nextInt(High-Low) + Low;
enemies[Result].setVisibility(View.VISIBLE);
countDownTimer.start();
if (score == 500)
{
countDownTimer.cancel();
}
}
};
countDownTimer.start();
}
}
感谢您的所有帮助,对于更有效的方法的任何建议,我们将不胜感激。
最佳答案
boolean running = true;
while (!running) {
...
你的while循环永远没有机会运行,如果你想刷新UI,你必须在另一个地方编写这段代码,也许是后台定时器任务线程或使用Handler
来处理这个。
关于java - Android工作室: Check object states,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058640/