此方法返回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;
}
}
}
}
答案 0 :(得分:4)
“假设的”枚举可能看起来像
public enum Ternary {
TRUE, FALSE, MAYBE;
}
答案 1 :(得分:2)
您可以将方法执行结果作为代码表示为int
。您的代码将如下所示:
public int Intersection (Circle circle, Rectangle rectangle) {
... // test something
... return 0;
... // test another thing
... return 1;
...
... return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq) ? 2 : 3;
}
您可以返回枚举,而不是int
cource。例如,您可以创建并使用以下枚举作为方法的返回值:
public enum ReturnCode {
CODE1,
CODE2,
CODE3,
CODE4,
CODEN;
}
代码将如下所示:
public ReturnCode Intersection (Circle circle, Rectangle rectangle) {
... // test something
... return ReturnCode.CODE1;
... // test another thing
... return ReturnCode.CODE2;
...
... return (xCornerDistSq + yCornerDistSq <= maxCornerDistSq) ? ReturnCode.CODE3 : ReturnCode.CODE4;
}