听起来非常哲学,不是吗?
无论如何,我有一个相当复杂的问题。
我的main_activity类像这样收集所有的僵尸:
//Testing Runnable (used to compare the first zombie with the player)
private Runnable updateLocations = new Runnable(){
@Override
public void run(){
try {
while(true) {
image_player.getLocationInWindow(pLoc);
Zombie zoms = zombieCollection.next();
if(!zoms.equals(null)){
zoms.getZombieImage().getLocationInWindow(zLoc);
}
System.out.println("Zombie: x = " + zLoc[0] + "; y = " + zLoc[1]);
System.out.println("Player: x = " + pLoc[0] + "; y = " + pLoc[1]);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
我的僵尸类通过以下方式收集信息:
public class Zombie{
float X, Y;
int Width, Height;
Direction fdirc;
ImageView zImage;
Player player;
boolean dead;
int[] zLoc;
public Zombie(ImageView zImage, Player player){
zLoc = new int[2];
zImage.getLocationOnScreen(zLoc);
this.zImage = zImage;
this.X = zLoc[0];
this.Y = zLoc[1];
this.Width = zImage.getWidth();
this.Height = zImage.getHeight();
this.fdirc = Direction.EAST;
this.player = player;
this.dead = false;
Thread thread = new Thread(this.startZombieChase);
thread.start();
}
public ImageView getZombieImage(){
return zImage;
}
private Runnable startZombieChase = new Runnable() {
@Override
public void run() {
try {
while(!dead) {
moveTowardsPlayer();
Thread.sleep(10);
updateZombie.sendEmptyMessage(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private Handler updateZombie = new Handler(Looper.getMainLooper()) {
public void handleMessage(android.os.Message msg) {
/** Because the zombie should always be on top! **/
zImage.getLocationOnScreen(zLoc);
zImage.bringToFront();
zImage.setX(X);
zImage.setY(Y);
}
};
private void moveTowardsPlayer(){
int player_x = player.getPosition()[0];
int player_y = player.getPosition()[1];
l("Where is it in zombie class : player - " + player_x + " " + player_y + "zombie - " + X + " " + Y);
float compareX = player_x - (int)X;
float compareY = player_y - (int)Y;
// Y is closer, so we're moving horizontally.
if(Math.abs(compareX) < Math.abs(compareY)){
//Moving North
if(player_y > Y){
Y+=1;
}
//Moving South
else if(player_y < Y){
Y-=1;
}
}
// X is closer, so we're moving vertically.
else{
//Moving East
if(player_x > X){
X+=1;
}
//Moving West
else if(player_x < X){
X-=1;
}
}
}
public void l(Object string){
System.out.println("Log - " + string);
}
}
我遇到的问题是,它会相对于某个数字移动(所以它确实会移动),但不是正确的东西。 logcat告诉我:
- 它在僵尸类中的位置:玩家 - 750 451 僵尸 - 750 451 - 它在main_activity中的位置:玩家 - 750 451 僵尸 - 792 619
有人能帮我理解我做错了什么吗?
整个项目位于这里.
!zoms.equals(null)
将始终返回true
或由于 NPE 失败。 - Tunakizoms.equals(null)
要么会抛出异常,要么返回false
。因此!zoms.equals(null)
要么会抛出异常,要么返回true
。这不是与null
进行比较的方式,您可以参考上面的链接。 - Tunaki