我有一个我无法理解的奇怪问题。我试图通过构造函数将isNPC
布尔值应用于PlayerMP
对象,因此我可以在没有用户输入的情况下移动NPC(非玩家角色)。我创建了一个tick()
方法来覆盖超类,当玩家不是NPC时再次调用它(允许玩家使用键盘输入来移动角色),如下所示:
public class PlayerMP extends Player {
public InetAddress ipAddress;
public int port;
protected boolean isNPC; //used in server class to prevent sending of packets to NPC entities registered in PlayerMP list.
public PlayerMP(Level lvl, int x, int y, InputHandler ipt, String usr, InetAddress ipAdd, int prt, int col) {
super(lvl, x, y, ipt, usr, col);
ipAddress = ipAdd;
port = prt;
isNPC = false;
}
public PlayerMP(Level lvl, int x, int y, String usr, InetAddress ipAdd, int prt, int col) {
super(lvl, x, y, usr, col);
ipAddress = ipAdd;
port = prt;
isNPC = false;
}
public PlayerMP(Level lvl, int x, int y, String usr, InetAddress ipAdd, int prt) { //constructor for local player
super(lvl, x, y, null, usr);
ipAddress = ipAdd;
port = prt;
isNPC = false;
}
public PlayerMP(Level lvl, int x, int y, String usr, int col) {
super(lvl, x, y, usr, col);
isNPC = true;
}
@Override
public synchronized void tick(){
if(!isNPC) {
super.tick();
}
else{
int xa = 0; //reset xa and ya so character stops when no keys are pressed (i.e. doesn't move continuously)
int ya = 0;
xa++;
if (xa != 0 || ya != 0) {
move(xa, ya);
isMoving = true;
Packet02Move packet = new Packet02Move(getUsername(), x, y, 050, noSteps, isMoving, movingDir); //sending move pack to let server/other clients know that this character is moving + where to
packet.writeData(GameApplication.game.client);
} else {
isMoving = false;
}
if (level.getTile(x >> 3, y >> 3).getId() == 3) { //when tile is water
isSwimming = true;
}
if (isSwimming && level.getTile(x >> 3, y + 3 >> 3).getId() != 3) { //return to normal when tile is no longer water (y+3 to allow for collision rather than rendering coords)
isSwimming = false;
}
if (level.getTile(x >> 3, y >> 3).getId() == 8 || level.getTile(x >> 3, y >> 3).getId() == 9 || level.getTile(x >> 3, y >> 3).getId() == 10) { //when tile is tree trunk or leaves
isBehind = true;
}
//x + y coords need tweaking
if (isBehind && level.getTile(x+3 >> 3, y >> 3).getId() != 8 && level.getTile(x+3 >> 3, y >> 3).getId() != 9 && level.getTile(x+3 >> 3, y >> 3).getId() != 10) { //return to normal when tile is no longer tree trunk/leaves
isBehind = false;
}
}
}
public boolean isNPC(){return isNPC;}
}
xa++;
导致字符sx坐标增加,即它向右移动 - 这只是测试移动,但是当我使用上面的构造函数添加这些NPC实体时会初始化{ {1}}为true,它们仍会执行isNPC
而不是super.tick()
块。这有什么理由会发生吗?
当我在else{}
方法中将!isNPC
更改为isNPC
时,它会按预期向右移动,因此我知道代码正在运行。
编辑:上面的超级构造函数+上面的完整tick()
类代码:
PlayerMP
使用正确的构造函数初始化public Player(Level level, int x, int y, String usrname, int col) {
super(level, "Player", x, y, 1);
shortColour = col;
setBodyColour(col);
username = usrname;
}
对象(只有一个有5个参数):
PlayerMP
我还应该补充一点,isNPC变量正在按预期用于其他目的,例如将数据包定向到服务器类中的客户端。
Player&#39>超类(Mob)的构造函数:
PlayerMP npc2 = new PlayerMP(game.level, 316, 250, "NPC Gerald", 020);
编辑:其他人有什么建议吗? isNPC正如预期的那样在一些构造函数中应用,并且不会在其他构造函数中工作....