java - 在 swing 中查找特定位置的所有组件
问题描述
我目前正在尝试将碰撞检测添加到我的 Java 游戏中。
这是我尝试做的一个例子:
public class Player extends JLabel {
public String Name;
public ImageIcon Image;
public float Speed;
public Player() {
this.setBounds(new Rectangle (16,16));
}
public boolean isSameLayerAs(Component component) {
if (JLayeredPane.getLayer(this) == application.Layer.getLayer(component) + 1) {
return true;
} else {
return false;
}
}
public void movePlayer() {
theLayer layer = application.Layer;
Component ObjectAbove = layer.getComponentAt(this.getLocation().x + 8, this.getLocation().y + 14);
if (ObjectAbove == null || (!isSameLayerAs(ObjectAbove) && this.getBounds().intersects(ObjectAbove.getBounds()))) {
moveUp();
}
else if (ObjectAbove == null || (!isSameLayerAs(ObjectAbove) && !this.getBounds().intersects(ObjectAbove.getBounds()))) {
moveUp();
}
layer.setLayer(this, ((this.getLocation().y) / 16) + 1);
}
}
播放器大小为 16x16 像素。在 MovePlayer() 方法中,它将播放器上方的对象层与播放器的层进行比较。如果玩家与对象相交并且与对象具有相同的层,则玩家无法向上移动。对象的层是 y 位置除以 16。为了将对象置于玩家上方,我尝试使用 getComponentAt(),如果我选择玩家不在的位置,它就可以正常工作,例如:
this.getLocation().y - 1
然而,我希望玩家将对象重叠一点。 像这样的东西
所以我尝试了layer.getComponentAt(this.getLocation().x + 8, this.getLocation().y + 14);
getComponentAt() 然而返回播放器,因为播放器也在这个位置(播放器大小为 16x16 像素)。
所以我的问题是:有没有办法在特定位置找到所有组件?
解决方案
推荐阅读
- excel - 在 Google 表格上提取具有 2 个条件(仅适用于 1 个)的列表子集
- android - Flutter:获取所有注册的 Firebase 用户
- java - 我将如何使用 hashMap?
- spring-boot - Mybatis @Insert 错误:嵌套异常是 org.apache.ibatis.reflection.ReflectionException
- jsp - 将值从一个 servlet 传递到另一个
- php - Wordpress PHP从表中选择行的正确方法
- visual-studio-code - 如何使用 es5 和 Visual Studio Code 获取外部 JavaScript 库的智能感知
- c# - 如何让玩家朝着unity3d的方向走
- r - 库存少于 10 个月的值的平均值
- ios - 在不使用 xcode 的情况下,在 mac 中将 lldb 用于 iphone 项目