必须检查球的x坐标是否在对象的范围内(objW是对象的宽度):
circle_x > x && circle_x < x + objW
并且如果球的y坐标已达到对象的高度(objH是对象的高度,而circleR是球的半径):
circle_y > objH - circleR
此外,重要的是要先进行命中测试,然后在物体反弹后再进行测试.一个好的样式是在else if语句中执行此操作:
int objX1 = -20;
int objX2 = 70;
int objH = 390;
int circleR = 25/2;
if (circle_x > x + objX1 && circle_x < x + objX2 && circle_y > objH - circleR ) {
circle_y = objH-circleR;
move_y = -move_y;
}
else if (circle_y > height) {
circle_y = height;
move_y = -move_y;
}
else if (circle_y < 0) {
circle_y = 0;
move_y= -move_y;
}
此外,我建议先计算球的位置,然后在当前位置绘制球:
float x;
float easing = 1;
float circle_x = 1;
float circle_y = 30;
float rad = 12.5;
float gravity = 0.98;
float move_x = 5;
float move_y = 5;
void setup() {
size(640,80);
float targetX = mouseX;
float dx = targetX - x;
x += dx * easing;
circle_x = circle_x + move_x;
circle_y = circle_y + move_y;
if (circle_x > width) {
circle_x = width;
move_x = -move_x;
}
else if (circle_x < 0) {
circle_x = 0;
move_x = -move_x;
}
int objW = 70;
int objH = 390;
int circleR = 25/2;
if (circle_x > x && circle_x < x + objW && circle_y > objH-circleR ) {
circle_y = objH-circleR;
move_y = -move_y;
}
else if (circle_y > height) {
circle_y = height;
move_y = -move_y;
}
else if (circle_y < 0) {
circle_y = 0;
move_y= -move_y;
}
fill(#000000);
rect(x,20);
ellipse(circle_x,25);
}