Libgdx Drag And Drop, как синхронизировать курсор и спрайт/актер?

GDX-версия: 1.9.8

Привет, я создаю JRPG, и у меня есть инвентарь с системами перетаскивания, проблема в том, что когда я нажимаю на элемент, он позиционируется в левом верхнем углу далеко от курсора (см. Скриншот), как сделать так, чтобы спрайт был в центре курсора (как это обычно должно быть)???

СКРИНШОТ!!!Как это выглядит

import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Target;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Source;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Payload;
import com.redsoft.redrune.InventoryItem;

public class InventorySlotTarget extends Target {

    InventorySlot _targetSlot;

    public InventorySlotTarget(InventorySlot actor) {
        super(actor);
        _targetSlot = actor;
    }

    @Override
    public boolean drag(Source source, Payload payload, float x, float y, int pointer) {
        return true;
    }

    @Override
    public void reset(Source source, Payload payload) {
    }

    @Override
    public void drop(Source source, Payload payload, float x, float y, int pointer) {

        InventoryItem sourceActor = (InventoryItem) payload.getDragActor();
        InventoryItem targetActor = _targetSlot.getTopInventoryItem();
        InventorySlot sourceSlot = ((InventorySlotSource) source).getSourceSlot();

        if (sourceActor == null) {
            return;
        }

        //First, does the slot accept the source item type?
        if (!_targetSlot.doesAcceptItemUseType(sourceActor.getItemUseType())) {
            //Put item back where it came from, slot doesn't accept item
            sourceSlot.add(sourceActor);
            return;
        }

        if (!_targetSlot.hasItem()) {
            _targetSlot.add(sourceActor);
        } else {
            //If the same item and stackable, add
            if (sourceActor.isSameItemType(targetActor) && sourceActor.isStackable()) {
                _targetSlot.add(sourceActor);
            } else {
                //If they aren't the same items or the items aren't stackable, then swap
                InventorySlot.swapSlots(sourceSlot, _targetSlot, sourceActor);
            }
        }

    }
}

ОБНОВИТЬ!

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Source;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Payload;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Target;

public class InventorySlotSource extends Source {

    private DragAndDrop _dragAndDrop;
    private InventorySlot _sourceSlot;

    public InventorySlotSource(InventorySlot sourceSlot, DragAndDrop dragAndDrop) {
        super(sourceSlot.getTopInventoryItem());
        this._sourceSlot = sourceSlot;
        this._dragAndDrop = dragAndDrop;
    }

    @Override
    public Payload dragStart(InputEvent event, float x, float y, int pointer) {
        Payload payload = new Payload();
        Actor actor = getActor();
        if (actor == null) {
            return null;
        }

        InventorySlot source = (InventorySlot) actor.getParent();
        if (source == null) {
            return null;
        } else {
            _sourceSlot = source;
        }

        _sourceSlot.decrementItemCount(true);

        payload.setDragActor(getActor());
        _dragAndDrop.setDragActorPosition(-x, -y + getActor().getHeight());

        return payload;
    }

    @Override
    public void dragStop(InputEvent event, float x, float y, int pointer, Payload payload, Target target) {
        if (target == null) {
            _sourceSlot.add(payload.getDragActor());
        }
    }

    public InventorySlot getSourceSlot() {
        return _sourceSlot;
    }
}

person Redas Shuliakas    schedule 22.03.2018    source источник


Ответы (1)


Это задается в объекте DragAndDrop. Положение по умолчанию предполагает, что вы хотите, чтобы нижний правый угол актера совпадал с курсором. Вы можете центрировать его следующим образом:

dragAndDrop.setDragActorPosition(dragActor.getWidth() / 2, -dragActor.getHeight() / 2);

Вам нужно вызвать это только один раз после установки актера перетаскивания. Я думаю, что имя метода вводит в заблуждение (должно быть указано смещение вместо положения).

person Tenfour04    schedule 23.03.2018
comment
общественное логическое перетаскивание (исходный источник, полезная нагрузка, число с плавающей запятой x, число с плавающей точкой y, указатель типа int) { DragAndDrop dragAndDrop = new DragAndDrop(); dragAndDrop.setDragActorPosition(dragAndDrop.getWidth()/2, -dragAndDrop.getHeight()/2); вернуть истину; } - person Redas Shuliakas; 23.03.2018
comment
getWidth и getHeight выделены красным цветом и говорят, что не могут разрешить метод. - person Redas Shuliakas; 23.03.2018
comment
@RedasShuliakas Вы не можете просто создать случайный другой DragAndDrop. Сделайте это с тем, который у вас уже есть, который управляет этим целевым элементом. Кроме того, getWidth() следует вызывать для актера перетаскивания, но вы вызвали его для неправильного объекта. - person Tenfour04; 23.03.2018
comment
Вы не поделились своим кодом, в котором вы настроили DragAndDrop, который вы используете, или установили актера перетаскивания. Вы бы просто поместили мою строку кода выше сразу после настройки вашего актера перетаскивания. - person Tenfour04; 23.03.2018
comment
Спасибо, все еще не повезло, я обновил свой пост, в UPDATE есть экземпляр DragAndDrop, я все еще не могу применить к нему методы Width и Height, или я делаю это не в том месте, не знаю, пожалуйста, посмотрите , благодарю вас. - person Redas Shuliakas; 23.03.2018
comment
У вас уже есть строка _dragAndDrop.setDragActorPosition(-x, -y + getActor().getHeight());. Измените его на _dragAndDrop.setDragActorPosition(getActor().getWidth() / 2, -getActor().getHeight() / 2);. Посмотрите на мой первый комментарий выше. getWidth() вызывается на актере, а не на DragAndDrop. - person Tenfour04; 23.03.2018