我有一些代码可以创建名为Weights的对象。现在,这些权重的子类称为 - WeightSmall,WeightMedium和WeightLarge - 每个都有自己的称为onScreen的静态变量。当添加WeightSmall,WeightMedium或WeightLarge中的一个时,该变量应该增加,但是这些变量会返回create方法的调用而不是添加到数组。我有一个Weight对象的数组 - 是否有一种方法来访问父类的数组中的某个元素所属的子类?在返回对象之前增加对象中的静态变量
以下是创建权代码:
public Weight createWeight() {
decider = Math.random() * 1;
// creates rocks randomly with the lowest chance for l, and the highest chance for m
if (decider <= 0.33) {
// small weight
return new WeightSmall(BitmapFactory.decodeResource(getResources(), R.drawable.weight_s), new Random().nextInt(screenWidth), -10);
} else if (decider <= 0.5 && decider > 0.33) {
// large weight
return new WeightLarge(BitmapFactory.decodeResource(getResources(), R.drawable.weight_l), new Random().nextInt(screenWidth), -10);
} else {
// medium weight
return new WeightMedium(BitmapFactory.decodeResource(getResources(), R.drawable.weight_m), new Random().nextInt(screenWidth), -10);
}
}
什么需要做的是WeightSmall可以说,它需要检查WeightSmalls屏幕上的变量,看它是否小于,假设3.如果是返回重量。然而,我想不出一种方式来访问WeightSmall的onScreen变量,因为它需要多次创建,我尝试将它们实现到一个ArrayList中,但它会导致更新方法的复杂性。下面是代码(即事项)该类的其余部分:
public void render(Canvas canvas) {
if (canvas != null) {
canvas.drawColor(Color.WHITE);
player.draw(canvas);
Weight[] weightArray = weights.toArray(new Weight[0]);
for (Weight weight : weightArray) {
weight.draw(canvas);
}
}
}
// updates the weight's position on the screen and checks collision with the player
public void update() {
Weight[] weightArray = weights.toArray(new Weight[0]);
for (Weight weight : weightArray) {
weight.update();
if (weight.getBounds().intersect(player.getBounds())) {
player.setTouched(false);
Intent gameOverIntent = new Intent(this.getContext(), GameOverActivity.class);
this.getContext().startActivity(gameOverIntent);
((Activity) getContext()).finish();
}
}
}
// count down timer spawning weights in every tick
public void timer() {
if (start == true) {
if (weightSpawnTimer != null) {
weightSpawnTimer.cancel();
weightSpawnTimer = null;
}
weightSpawnTimer = new CountDownTimer(30000, 800) {
public void onTick(long millisUntilFinished) {
weights.add(createWeight());
}
public void onFinish() {
weightSpawnTimer.start();
}
}.start();
}
}
编辑为清楚:我需要什么样的情况发生,在onTick方法,检查是否重的屏幕变量的子类是< = 3 ,如果是的话,创造一个新的重量,如果它不是什么都不做。一旦权重然后脱离屏幕,减少此变量,以便可以创建该子类的新权重。
您正试图计算屏幕上每个子类的权利? – Trenin
如果是这样,只需在每个Weight *子类中声明一个静态整数。在Weight超类中,声明一个名为'getNumberOnScreen'的方法。这被子类覆盖以返回特定子类的值。 – Trenin
是的。好吧,我已经实现了你所说的,但是我从哪里去调用这个方法来检查每种类型的权重? 编辑:如在我可以执行以下操作: 公共无效onTick(长millisUntilFinished){ \t \t \t \t \t重量[] weightArray = weights.toArray(新重量[0]); \t \t \t \t \t为(重量重量:weightArray){ \t \t \t \t \t \t如果(weight.getOnScreen()<= 3){ \t \t \t \t \t \t \t weights.add(createWeight()); \t \t \t \t \t \t} \t \t \t \t \t} \t \t \t \t} 但将这个回暖取决于权重的子类中加入了正确屏幕上的变量?另外,一旦对象完成,我将如何减少这个变量? –