Kri*_*ice 5 java events inventory handler eventhandler
对于我的游戏,我实施了一个库存系统.单击屏幕时,a MousePressedEvent
将通过layers
游戏中的所有对象传递给所有继承EventListener
(My EventListener
)的对象.该EventListener
级工作正常,并使用它,如下图所示,我已经成功地让我的库存,这样你可以删除一个槽物品,将它们放回.然而,我想要做的是能够将它们从任何包含项目的插槽中取出,并将它们放在任何其他插槽中(只要目标插槽为空).我认为我所拥有的将允许这样做,因为在if
声明中我没有检查如果选择了插槽,我将其添加到插槽中.但这实际上并不奏效.有任何想法吗?
Slot.java
课堂代码:
public boolean onMousePressed(MousePressedEvent e) {
Point p = new Point(Mouse.getX(), Mouse.getY());
if (!this.getBounds().contains(p)) return false;
boolean left = (e.getButton() == MouseEvent.BUTTON1);
boolean right = (e.getButton() == MouseEvent.BUTTON3);
boolean hasItems = (items.size() > 0);
if (this.getBounds().contains(p)){
if (right && !selected && hasItems){
select(true);
s = new Slot(new Vector2i(Mouse.getX(), Mouse.getY()));
addComponent(s);
s.add(items.get(0));
remove(items.get(items.size() - 1));
} else if (right && selected){
s.add(items.get(0));
remove(items.get(items.size() - 1));
if (items.size() == 0) {
setBackgroundImage(ImageUtil.getImage("/ui/panels/inventory/slot.png"));
selected = false;
return true;
}
return true;
} else if ((left || right) && s==null) {
return true;
} else if (left && s != null){ //If left clicked, add to the slot from s regardless of if we are selected.
add(s.getItems().get(0));
s.remove(s.getItems().get(s.getItems().size() - 1));
if (s.getItems().size() == 0){
s.setBackgroundImage(ImageUtil.getImage("/ui/panels/inventory/slot.png"));
removeComponent(s);
s = null;
selected = false;
return true;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
在伪代码中:
If (Mouse is clicked) :
if (the mouse isn't the bounds of the slot) return false (alert we haven't handled the event)
if (we contain the mouse cursor) :
if (right is pressed and we aren't selected) :
select
create a temporary slot at the mouse location
remove item from this slot
add it to the temporary slot
return true
else if (right is pressed and we are selected) :
add item to temporary slot
remove item from selected slot
return true
else if (we press left or right while temporary slot is null) :
return true (tell the dispatcher we have handled the event)
//This following else if statement is supposed to add an item to a clicked slot whether that slot is selected or not, but doesn't work
else if (left is pressed and temporary slot isn't null) :
add the item to the clicked slot
remove it from the temporary one
return true
return false if none of the above applies
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
通过在每个语句中添加打印行else if
,我发现当我尝试将临时槽中的项目添加到另一个槽中时,临时槽为空。这是因为,创建临时槽时,它是由您第一次选择的槽实例创建的,因此您尝试添加的槽无法访问临时槽。为了解决这个问题,我将临时槽作为每个实例的变量移动,将其设为静态。代码现在工作正常
归档时间: |
|
查看次数: |
76 次 |
最近记录: |