【发布时间】:2013-11-27 21:02:40
【问题描述】:
此方法返回 true、false 和另一个值。
public boolean Intersection (Circle circle, Rectangle rectangle) {
... // test something
... return true;
... // test another thing
... return false;
...
... return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; //Third return value
}
这是一个 2D 游戏,其中一个球应该从一个矩形反弹,包括矩形的边缘。我在上面链接的第三个返回值应该检测球和矩形边缘之间的碰撞。问题是,一旦我调用该方法,我不知道如何在我的代码中使用它。
我目前拥有的是这个
这是方法的完整代码:
public boolean Intersection (Circle circle, Rectangle rectangle) {
double cx = Math.abs(circle.getLayoutX() - rectangle.getLayoutX() - rectangle.getWidth() / 2);
double xDist = rectangle.getWidth() / 2 + circle.getRadius();
if (cx > xDist) { return false; }
double cy = Math.abs(circle.getLayoutY() - rectangle.getLayoutY() - rectangle.getHeight() / 2) ;
double yDist = rectangle.getHeight() / 2 + circle.getRadius();
if (cy > yDist) { return false; }
if (cx <= rectangle.getWidth() / 2 || cy <= rectangle.getHeight() / 2) { return true; }
double xCornerDist = cx - rectangle.getWidth() / 2;
double yCornerDist = cy - rectangle.getHeight() / 2;
double xCornerDistSq = xCornerDist * xCornerDist;
double yCornerDistSq = yCornerDist * yCornerDist;
double maxCornerDistSq = circle.getRadius() * circle.getRadius();
return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
}
那么,当我调用该函数时,我该如何去实现它呢?我也想让我的球从边缘反弹,但我不知道如何使用这种方法来调用它。
我目前拥有的是这样的:
boolean intersection = Intersection(circle1, rect1);
if (intersection == true) {
double x = (rect1.getLayoutX() + rect1.getWidth() / 2) - (circle1.getLayoutX() + circle1.getRadius());
double y = (rect1.getLayoutY() + rect1.getHeight() / 2) - (circle1.getLayoutY() + circle1.getRadius());
if (Math.abs(x) > Math.abs(y)) {
c1SpeedX = -c1SpeedX;
} else {
c1SpeedY = -c1SpeedY;
}
}
}
}
【问题讨论】:
-
对,错,也许?你可以写一个枚举。
-
显示的代码将只返回两个可能的值。最后一行将返回真或假。如果您需要返回两个以上的值,则必须使用不同的类型 -
boolean将不起作用 -
抱歉,不知道该怎么做。能否提供一个代码示例?
-
枚举可能有效,您也可以返回 int、-1、0 和 1。
-
@ÓscarLópez,这很有趣。所以我不需要添加枚举或做任何类似的事情,因为第三个值将返回为真或假。那为什么我的代码不起作用?
标签: java methods boolean collision-detection