java - java中的碰撞检测问题。intersectsWith 方法总是返回 true
问题描述
我目前正在开发一款游戏,但我的碰撞检测存在问题:
这些是我实现的方法:
public boolean intersectsWith(GameObject other) {
if(getTopRightPoint(this)[1] < getBottomLeftPoint(other)[1]
|| getBottomLeftPoint(this)[1] > getTopRightPoint(other)[1]) {
return false;
}
if(getTopRightPoint(this)[0] < getBottomLeftPoint(other)[0]
|| getBottomLeftPoint(this)[0] > getTopRightPoint(other)[0]) {
return false;
}
System.out.println("COLLISION BETWEEN " + this.getClass().getSimpleName() + " and "+ other.getClass().getSimpleName());
return true;
}
private double[] getBottomLeftPoint(GameObject gameObject){
return new double[] {gameObject.actualPosition[0], gameObject.actualPosition[1]};
}
private double[] getTopRightPoint(GameObject gameObject) {
return new double[] {gameObject.actualPosition[0] + gameObject.getCurrentSprite().getWidth(), gameObject.actualPosition[1] + gameObject.getCurrentSprite().getHeight()};
}
然后,每当时间推进时,我都会使用以下方法检查碰撞:
gameObjects.stream().forEach(o1 -> gameObjects.stream().forEach(o2 -> {
if (o1 != o2 && o1.intersectsWith(o2)) {
o1.collision(o2);
}
}));
这应该可以,但它会继续打印该行
System.out.println("COLLISION BETWEEN " + this.getClass().getSimpleName() + " and "+ other.getClass().getSimpleName());
这告诉我,即使没有,也总是有碰撞。
我怎样才能解决这个问题?
解决方案
如果您的坐标是 Bottom X Left,那么您的实际 getTopRightPoint 实现将返回 Bottom + Width;左 + 高度,这实际上是在对象边界之外。
正确的是:底部-高度=顶部;左 + 宽度 = 右
private double[] getTopRightPoint(GameObject gameObject) {
return new double[] {gameObject.actualPosition[0] - gameObject.getCurrentSprite().getHeight(), gameObject.actualPosition[1] + gameObject.getCurrentSprite().getWidth()};
}
PS:您还向底部添加了宽度,该宽度必须为高度(以及向左的高度)
推荐阅读
- dart - 运行 Gradle 任务“assembleDebug”-异常:Gradle 任务 assembleDebug 失败,退出代码为 -1
- mysql - MySQL 查询返回了一个空结果集
- python - Flask 应用程序出现 werkzeug.routing.BuildError
- java - Java Json 对象到 Json 数组的转换
- flutter - 如何将 GlobalKey 字段从一个类传递到另一个类?
- linux - 使用 awk 或更简单的 #scripting 以特定形式重新排序文本文件行
- javascript - TypeError: $(...).froalaEditor 不是函数 | JSP 中的 $(document).ready(function(){})
- firebase - 如何解决 Firebase 部署功能错误:Cloud Functions 部署需要按需付费 (Blaze) 计费计划
- php - 如何强制用户仅在某些页面上进行 http?(PHP)
- python-3.x - 如何在地图功能中使用等待