注意:我正在使用Greenfoot IDEJava:如何檢查某個對象的特定實例是否在世界中?
所以我的任務是創建一個Balloon項目,其中Balloon類的對象浮動到屏幕的頂部。任何其他細節都取決於我的決定。
所以我做了這個,讓我的氣球彈出一個pop方法,這個方法被另外兩個方法調用。其他兩種方法是topPop(),其中pop()在if(getY()< = 0)和hitCopter()時被調用,其中如果氣球與我的直升機玩家對象相交,則調用pop()。
這裏的問題是,在我的Act()方法中,程序在碰到我首先調用的任何一個方法hitCopter()或topPop()後崩潰,並且說另一個是因爲崩潰而導致的,要通過這兩種方法,但不能做另一種方法,因爲當世界不再存在時,您無法檢查它是否相交或其getY()。
所以我想如果我可以在執行topPop()或hitCopter()之前檢查該對象的實例是否仍然在世界中,它將解決我的問題。問題是我不知道該怎麼做,而且我無法在網上找到有關如何明確這樣做的答案。
我試圖通過一個列表,我的代碼在這裏反映,但我實際上不知道如何檢查一個列表,所以我的if語句檢查反映了我的無知。
這是目前我的代碼:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
* Write a description of class Balloon here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Balloon extends Actor
{
//variable declaration
private int yAxis;
private int num;
private int size;
private int health;
private int dmg;
private int rndmSize;
private int setSize;
private Balloon thisBalloon;
public Balloon()
{
rndmSize = Greenfoot.getRandomNumber(6)+1;
rndmSize();
setSize(setSize);
num=0;
yAxis=0;
thisBalloon = this;
}
public void rndmSize()
{
if (rndmSize==1)
{
setSize = 5;
}
else if(rndmSize==2)
{
setSize = 10;
}
else if(rndmSize==3)
{
setSize = 15;
}
else if(rndmSize==4)
{
setSize = 20;
}
else if(rndmSize==5)
{
setSize = 25;
}
else
{
setSize = 30;
}
}
public void act()
{
fly();
if (getWorld().getObjects(Balloon.class) != Balloon.this)
{
topPop();
}
List<Balloon> balloon = this;
for(Actor actor : balloon)
{
if (actor instanceof balloon)
return true;
}
if (getWorld().getObjects(Balloon.class) != Balloon.this)
{
hitCopter();
}
setSize(health);
}
public void fly()
{
num++;
yAxis=getWorld().getHeight()-num;
setLocation(getX(),yAxis);
turn(1);
}
public void setSize(int size2)
{
health = size2;
this.size = size2;
dmg = size2/2;
GreenfootImage image=getImage();
image.scale(size2,size2);
}
public void topPop()
{
if(getY()<=5)
{
pop();
}
}
public void hit(int damage)
{
health-=damage;
if(health <=0)
{
getWorld().removeObject(this);
return;
}
}
public void hitCopter()
{
Helicopter copter = (Helicopter) getOneIntersectingObject(Helicopter.class);
if (copter != null)
{
copter.hit(dmg);
pop();
}
}
public int returnSize()
{
return size;
}
public void pop()
{
//popping animation
//remove the balloon
getWorld().removeObject(this);
}
}
謝謝你,至少我刪除崩潰。我仍然對看到我的方法是否可行感興趣,但我很高興它不會崩潰。 – 2014-09-24 21:19:10