简体   繁体   English

磁盘和垂直矩形之间的碰撞检测

[英]collision detection between a disk and an vertical rectangle

this is my jsfiddle : http://jsfiddle.net/whZ44/8/ 这是我的jsfiddle: http//jsfiddle.net/whZ44/8/

what I am trying to do is to detect when the ball hit the top border of a stand.if it does than the new coordinate of the ball should be the coordinate of the stand like the doodle jump game. 我想要做的是检测球何时击中一个支架的顶部边框。如果它确实比球的新坐标应该是支架的坐标,就像涂鸦跳跃游戏一样。 but it seems like my collision detection function isn't working 但似乎我的碰撞检测功能不起作用

if (Collision(ball, std4)) {
                            console.log("collision");
                            ball.y = std2.x;
                        }

the collision function i am currently using and i don't really know if it work under my conditions : 我正在使用的碰撞功能,我真的不知道它是否在我的条件下工作:

 function Collision(circle, rect) {
            var distX = Math.abs(circle.x - rect.x - rect.w / 2);
            var distY = Math.abs(circle.y - rect.y - rect.h / 2);

            if (distX > (rect.w / 2 + circle.r)) { return false; }
            if (distY > (rect.h / 2 + circle.r)) { return false; }

            if (distX <= (rect.w / 2)) { return true; }
            if (distY <= (rect.h / 2)) { return true; }

            var dx = distX - rect.w / 2;
            var dy = distY - rect.h / 2;
            return (dx * dx + dy * dy <= (circle.r * circle.r));
        }

If you are not too worried about working out how the circle will react afterwards then have you considered using a bounding rectangle for the circle? 如果您不太担心圆圈之后会如何反应,那么您是否考虑过使用圆形的边界矩形?

This post also talks about circle colission: 这篇文章还谈到了圆圈的分裂:

2d collision response between circles 圆圈之间的2d碰撞响应

This article is a nice explanation of 2d physics: 这篇文章是对2d物理学的一个很好的解释:

http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/ http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/

The collision function was ok, you just had some variables name wrong: 碰撞功能还可以,你刚才有一些变量名称错误:

 if (Collision(ball, std4)) {
                        console.log("collision");
                        ball.y = std2.x;
 }

TO

 if (Collision(ball, std2)) {
                        console.log("collision");
                        ball.y = std2.y;
 }

Demo: http://jsfiddle.net/whZ44/9/ 演示: http//jsfiddle.net/whZ44/9/

For further development you should store all obstacles in an array, as you have to check collisions with them all, not only one. 为了进一步开发,您应该将所有障碍物存储在一个数组中,因为您必须检查所有障碍物,而不仅仅是一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM