Перекрывающиеся объекты в Java - PullRequest
1 голос
/ 06 мая 2020

Как сказано в заголовке, у меня проблема с перекрытием объектов. Я хочу, чтобы они могли перекрываться, потому что мне нужно, чтобы объект X находился поверх объекта Y, чтобы получить точку, и если я удаляю объект X из положения поверх Y, я удаляю указанную точку. Моя проблема в том, что если объект Y создается до объекта X, как только я помещаю объект X поверх Y, я больше не могу его перемещать, и он всегда выводит на консоль объект Y. Мне было интересно, будет ли проще способ исправить это.

Я пытаюсь двигаться вперед, но Box не сдвигается с места:

[https://i.stack.imgur.com/pXAOe.png

Это код, который я использую для генерации Уровень Data

 private List<ImageTile> createLevel(){
    ArrayList<Movable> aux1 = new ArrayList<>();
    ArrayList<Immovable> aux2 = new ArrayList<>();

    try {
        Scanner sc = new Scanner(new File ("levels/level" + levelID + ".txt"));
        String line = "";

        while(sc.hasNextLine()) {
            for (int y = 0; y < HEIGHT; y++) {
                line = sc.nextLine();
                for(int x = 0; x < WIDTH ; x++) {
                    levelObjects.add(new floor(new Point2D(x,y), "Floor", 0));//adding the floor before anything else
                    char letter = line.charAt(x); // checking the character in the X coordinate
                    if (letter == 'E') { // in case, there's a E, that's the starting position of the player
                        player = new Forklift(new Point2D(x,y), "Forklift_U", 2);
                        levelObjects.add(player);
                        objects.add(player);
                    } else if(letter != ' ') {
                        AbstractObject obj = ObjectCreation.readChar(letter, x, y); // going to look for the object in Factory to be put in the X and Y position
                        if(obj instanceof Immovable) {
                            aux2.add((Immovable) obj);
                        }else if(obj instanceof Movable) {
                            aux1.add((Movable) obj);
                        }
                        //                          comp.comprator(obj, obj);
                        objects.add(obj);
                        levelObjects.add(obj);//implementing said object into the Level
                    }
                }
            }
        }
        sc.close(); //Closing Scanner
    } catch (FileNotFoundException e) {
        System.out.println("No levels found!");
    }
    still = aux2;
    moving = aux1;
    return levelObjects;
}

Затем я проверяю с помощью общей функции перемещения, может ли блок (или любая часть объекта экземпляра Movable) переместиться в следующую позицию

public void move(Direction direction) {
    Vector2D pos = direction.asVector(); // Transforming the direction in a vector right off the bat.
    Point2D currentPosition = getPosition(); // getting the current position of either player or object.
    Point2D nextPosition = currentPosition.plus(pos); // the next position as to which the player or the object intend to go to.

    if(isTransposable(nextPosition)) { // calls the function to see if the object is able to move to the next position, this prevents the boxes from pushing up into the walls and from into each other {
        setPosition(nextPosition); //if it can, then the object will go to the next position
    }
}

И это для проверки, может ли объект перейти на следующую позицию;

public boolean isTransposable(Point2D pos) { // is the object able to move to the next position
    for(AbstractObject obj1 : Game.getInstance().getObjects()) { // for-each to get all the objects, with the exception of the floor, from the game.
        if((obj1.isBlockable() && obj1.getPosition().equals(pos))){ // if the object is able to block and if it's position is the same as the nextPosition.
            return false;
        }
    }
    return true; // otherwise it's able to be walked on.
}
...