简体   繁体   中英

Collision detection not detecting

I have an array of objects that are all 'rectangles'. I also have a circle that is the object. The equation I use for gravity is:

newYPos = oldYPos + prevFallingSpeed + gravity

Basically, I am adding the rate of gravity to the number of pixels the circle 'fell' in the previous frame and then adding that to the position of the circle in the last frame.

I am detecting if any part of the ball is inside of any of the objects using this code:

for(var i = 0; i < objects.length; i++){
    if(ball.x > objects[i].x - ball.r && ball.y > objects[i].y - ball.r && ball.x < ball.r + objects[i].x + objects[i].w && ball.y < ball.r + objects[i].y + objects[i].h){
        alert('test');
        gSy = (-1 * gSy);
    }
}

The code checks if the circle's coordinates plus or minus the radius is greater than the top/left positions of the walls of the box and less than the right/bottom positions of the walls of the box.

The ball is inside the object at one point, but I never get an alert. I've tried everything I can think of. Hopefully I'm just making some dumb mistake I can't see...

Here is a jsfiddle if you are up for messing with my code or don't understand the variables:

http://jsfiddle.net/JGKx5/

The small problem:

You have four objects.

  • Two of them (numbers 1 and 3) are tall and thin, and off to the left or right. The ball never goes near them.
  • One of them (number 2) is short and wide, and at y-coordinates smaller than the ball ever attains.
  • The other one (number 0) is short and wide, and its y-coordinates are ones that a real physical ball would pass through -- but because your ball moves in discrete steps your script never actually sees it do so. (It goes from y=580.4 to y=601.2.)

The big problem:

In the jsfiddle, all your comparisons in the collision test appear to be exactly the wrong way around :-). (Which is odd since the ones in the code here are the right way around.)

With both of these changed (I made the ball move by 0.1*gSy instead of by gSy, and flipped all the comparison operators), collisions are detected.

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