Android 圆形与矩形碰撞
我的屏幕上有一个球在弹跳,并且有一个静态矩形,它可以与之碰撞并应该弹开。我已经弄清楚如何测试球是否与矩形碰撞,效果很好。现在我需要确定球击中了矩形的哪一侧。我目前正在尝试这段代码(它适用于测试四个侧面,但似乎在角上有问题)......
if(Math.abs(ball.centerY-boundingBox.top) < ball.radius) {
// Hit the top
}
else if(Math.abs(ball.centerY-boundingBox.bottom) < ball.radius) {
// Hit the bottom
}
else if(Math.abs(ball.centerX-boundingBox.left) < ball.radius) {
// Hit the left
}
else if(Math.abs(ball.centerX-boundingBox.right) < ball.radius) {
// Hit the right
}
有谁有任何想法如何改进这个?或者针对此事提出更好的解决方案?
我基本上只需要确定圆碰撞后碰撞到矩形的哪一侧。我已经想出了如何测试它们是否发生碰撞。
谢谢!
I have a ball bouncing on my screen and there is a static rectangle that it can collide with and should bounce off of. I have already figured out how to test if the ball has collided with the rectangle and that works great. Now I need to determine which side of the rectangle that the ball has hit. I am currently trying this code (which works for testing the four sides but seems to have problems with the corners)...
if(Math.abs(ball.centerY-boundingBox.top) < ball.radius) {
// Hit the top
}
else if(Math.abs(ball.centerY-boundingBox.bottom) < ball.radius) {
// Hit the bottom
}
else if(Math.abs(ball.centerX-boundingBox.left) < ball.radius) {
// Hit the left
}
else if(Math.abs(ball.centerX-boundingBox.right) < ball.radius) {
// Hit the right
}
... Does anyone have any ideas how I can improve this? Or come up with a better solution for that matter?
I just basically need to determine which side a circle has hit on a rectangle after they collide. And I have already figured out how to test whether they collide or not.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可能不适用于角球,因为当球击中角球时,它会同时击中两侧。如果你想让它准确地弹跳,相关的法线向量是从球的中心到角的法线向量,这将是水平和垂直之间的某个对角线。
假设您总是在球的中心位于矩形之外时检测到重叠,您可能想要做的是这样的:
处理内部和外部碰撞的更好的测试是找到到每侧最近点的距离,选择最小距离,如果最近点是角点则为角碰撞,否则为侧面碰撞。
It presumably doesn't work for corners because when the ball hits a corner, it hits two sides simultaneously. And if you're looking to make it bounce accurately, the relevant normal vector is that from the centre of the ball to the corner, which is going to be some diagonal between horizontal and vertical.
Assuming you always detect overlap while the centre of the ball is outside the rectangle, what you probably want to do is something like:
A better test — to handle both inside and outside collisions — would be to find distance to the closest point on each side, pick the smallest distance, then if closest point is a corner then its a corner collision, otherwise it's a side collision.