圆圈一直卡在矩形的右上角

时间:2017-10-03 02:42:26

标签: javascript

每当我尝试在我的程序中运行此函数时,圆圈(在它自己的x位置经过矩形x位置之后),就会卡在矩形的右上角而不是像我一样反弹打算做它。

bounceOff: function(circle, rect) {
    let distX = Math.abs(circle.x - rect.x - rect.w / 2);
    let distY = Math.abs(circle.y - rect.y - rect.h / 2);
    circle.dx = distX - rect.w / 2;
    circle.dy = distY - rect.h / 2;
    return (circle.dx * circle.dx + circle.dy * circle.dy <= (circle.r * circle.r));
}

1 个答案:

答案 0 :(得分:0)

您必须检查运营商优先级。例如:if:

circle.x = 10;
rect.x = 5;
rect.w = 6;

然后

circle.x - rect.x - rect.w / 2

可以得到:10 - (5-6 / 2)= 10 - 3 = 7

或:(10-5) - (6/2)= 5 - 3 = 2

或甚至:((10-5) - 6)/ 2 = -.5

使用括号:

let distX = Math.abs(circle.x - (rect.x - (rect.w / 2)));
let distY = Math.abs(circle.y - (rect.y - (rect.h / 2)));