我一直试图让我的球从桨(矩形)上弹起,桨(矩形)具有固定的 y 位置,但 x 位置由 mouseX 控制,但它不起作用,我不确定做错了什么,因为我'我已经尝试了所有我认为有意义的事情,但它只是从来没有做我认为正确的事情。
我已经尝试过这样的代码,球直接穿过。
// Check collision with the rectangle and change velocity accordingly
if ((x + ballSize/2 >= rectX && x + ballSize/2 <= rectX + rectWidth) &&( y+ballSize/2 >= rectY && y+ballSize/2 <= rectY + rectHeight/2)) {
vx = -vx;
vy = -vy;
}
我也尝试过这个,它也直接通过了
if (x + ballSize/2 >= rectX && x + ballSize/2 <= rectX + rectWidth) {
if(y - ballSize/2 >= rectY && y - ballSize/2 <= rectY ) {
vx = -vx;
vy = -vy;
}
}
这是我的全部代码供参考
int x = 100;
int y = 100;
float vx = 3.0;
float vy = 2.5;
float rectX = mouseX;
float rectY = 400;
int ballSize = 30;
int rectWidth = 80;
int rectHeight =25;
void setup() {
size(500, 500);
}
void draw() {
background(255);
fill(0);
rect(constrain(mouseX, 0, width-rectWidth), rectY, rectWidth, rectHeight);
fill(200);
ellipse(x, y, ballSize, ballSize);
x += vx;
y += vy;
// Preventing ball from going off the sides of the window
if (x >= width - 15 || x <= 15) {
vx = -vx;
}
if (y >= height - 15 || y <= 15) {
vy = -vy;
}
// Check collision with the rectangle and change velocity accordingly
if (x + ballSize/2 >= rectX && x + ballSize/2 <= rectX + rectWidth) {
if(y - ballSize/2 >= rectY && y - ballSize/2 <= rectY ) {
vx = -vx;
vy = -vy;
}
}
}//draw closing bracket
最有可能在这里:
if(y - ballSize/2 >= rectY && y - ballSize/2 <= rectY )
你想要:
if(y + ballSize/2 >= rectY && y + ballSize/2 <= rectY + rectHeight )
不管怎样,只有当球的中心接触到垫子时,它才会弹起。如果你想要更精确的碰撞,你必须在这里进行更复杂的数学计算:
https://gamedev.stackexchange.com/questions/96337/collision- Between-aabb-and-circle