我目前有一个球从画布的墙壁上弹开。我在屏幕中间添加了一个矩形。每当球与矩形碰撞时,我希望它也能从它上面反弹,但我不知道该怎么做。我有一个名为“r”的矩形。
如何让球将矩形视为墙壁,并在它撞击时改变方向?代码示例将不胜感激。感谢。
这是我从球墙反弹的代码:
public void handle(ActionEvent t) {
// Moves the ball depending on the values of X and Y
circle.setLayoutX(circle.getLayoutX() + X);
circle.setLayoutY(circle.getLayoutY() + Y);
final Bounds bounds = canvas.getBoundsInLocal();
// Boolean values to check if a wall has been hit
boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());
// If the bottom or top wall has been touched, the ball reverses direction.
if (bottomWall || topWall) {
Y = Y * -1;
}
// If the left or right wall has been touched, the ball reverses direction.
if (leftWall || rightWall) {
X = X * -1;
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}
答案 0 :(得分:1)
我不知道JavaFx,但这是一个想法:
while (1) {
bool btop = pos.y >= top
bool bbottom = pos.y <= bottom
bool bleft = pos.x <= left
bool bright = pos.x >= right
bool rect_btop = pos.y <= rect_top && pos.x >= rect_left && pos.x <= rect_right
bool rect_bbottom = pos.y <= rect_bottom && pos.x >= rect_left && pos.x <= rect_right
bool rect_bright = pos.x <= rect_right && pos.y >= rect_bottom && pos.y <= rect_top
bool rect_bleft = pos.x >= rect_left && pos.y >= rect_bottom && pos.y <= rect_top
if (btop || bottom || rect_btop || rect_bbottom)
vy -= vy
if (bleft || bright || rect_bleft || rect_bright)
vx -= vx
}
然而,有更好和可扩展的解决方案(编码突破砖)。
答案 1 :(得分:0)
this post对我有很大帮助
//example import for externally loaded library
//this will not form part of the bundle but will allow typescript to understand external libraries throughout the project
import _ from 'lodash';
declare global {
//Example global constant for libraries served via webpack externals. example webpack config:: externals: { _: 'lodash' }
//This assumes lodash was already load in DOM for example in <head> via CDN link before main.js is loaded.
const _: typeof _;
//example of custom types
type JSONPrimitive = string | number | boolean | null;
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
type JSONObject = { [member: string]: JSONValue };
//example of custom interface
interface JSONArray extends Array<JSONValue> {}
}