简体   繁体   中英

collision detection between a disk and an vertical rectangle

this is my 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

This article is a nice explanation of 2d physics:

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/

For further development you should store all obstacles in an array, as you have to check collisions with them all, not only one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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