我在製作遊戲,玩家不能離開屏幕。我試圖做到這一點,如果玩家在屏幕一側的相反方向前進,他們會讓他們移動。但到目前爲止,它只適用於屏幕的北側和西側。只有當玩家向上或向左移動時,移動纔有效
運動方法:(每個玩家試圖移動時調用):
public static Location move(Direction dir, Mob mob, boolean checkRoomBounds, int distance) {
Location loc = mob.getLocation();
Location location = new Location();
location.setX(loc.getX());
location.setY(loc.getY());
if (dir.equals(Direction.WEST))
location.setX(loc.getX() - distance);
else if (dir.equals(Direction.EAST))
location.setX(loc.getX() + distance);
else if (dir.equals(Direction.NORTH))
location.setY(loc.getY() - distance);
else if (dir.equals(Direction.SOUTH))
location.setY(loc.getY() + distance);
else
// return original location, so it doesn't move
return loc;
if (!checkRoomBounds)
return location;
else {
// Crop the dimension so that the mob doesn't go fully out at the right side
// of the screen and it goes not fully out on the left side
Dimension mobCropped = DimensionGenerator.generate(mob.getLocation(),
mob.getSprite().getWidth(null), mob.getSprite().getHeight(null));
Location origTopLeft = mobCropped.getTopLeft();
Location origBottomRight = mobCropped.getBottomRight();
Location newTopLeft = new Location(origTopLeft.getX() +
mob.getSprite().getWidth(null), origTopLeft.getY() +
mob.getSprite().getHeight(null));
Location newBottomRight = new Location(origBottomRight.getX() -
mob.getSprite().getWidth(null), origBottomRight.getY() -
mob.getSprite().getHeight(null));
mobCropped.setTopLeft(newTopLeft);
mobCropped.setBottomRight(newBottomRight);
// if the new location is outside the room
if (!Collision.detect(mobCropped, Main.roomDimension)) {
// if player is going away from wall but they are outside the room, allow them to
// go away
if (dir.equals(Direction.WEST) && loc.getX() >= Main.width)
return location;
if (dir.equals(Direction.EAST) && loc.getX() <= mob.getSpeed())
return location;
if (dir.equals(Direction.NORTH) && loc.getY() >= Main.height)
return location;
if (dir.equals(Direction.SOUTH) && loc.getY() <= mob.getSpeed())
return location;
// if they aren't moving away from the wall, dont let them move
return loc;
}
// if they aren't outside the room
else {
return location;
}
}
}
你是通過代碼?你認爲問題在哪裏發生? – krillgar
當我讓玩家移動時,這已經發生在我的方向enum(我不認爲我必須展示它的代碼,其中沒有任何東西)。 – MCMastery
請避免混合單行ifs和多行ifs,並在if/else鏈之間放置註釋。你正在爲自己設定一個很大的錯誤。此外,我有很大的麻煩理解你的代碼,因爲它是雙重否定等等... – Pimgd