Collision accuracy

邮差的信 提交于 2019-12-11 06:16:40

问题


Not quite sure how to word this but I've been using

if (CGRectIntersectsRect(ball.frame, bottom.frame)) {
    [self finish ];
}

for my collision detection and it run the code perfectly but the ball sometimes collides with the bottom and runs the code but you can clearly see there is a gap in between the objects. i have created the images my self and they have no background around them. i was wondering if theres any other way of coding it or making it so the it doesn't run the code until the intersect x amount of pixels into one another.


回答1:


You can implement ball-line collision in many ways. Your solution is in fact a rectangle - rectangle collision detection. Here is how I did it in one of my small gaming projects. It gave me best results and it's simple.

Let's say that a ball has a ballRadius, and location (xBall, yBall). The line is defined with two points (xStart, yStart) and (xEnd, yEnd).

Implementation of a simple collision detection:

float ballRadius = ...;
float x1 = xStart - xBall;
float y1 = yStart - yBall;

float x2 = xEnd - xBall;
float y2 = yEnd - yBall;

float dx = x2 - x1;
float dy = y2 - y1;
float dr = sqrtf(powf(dx, 2) + powf(dy, 2));
float D = x1*y2 - x2*y1;

float delta = powf(ballRadius*0.9,2)*powf(dr,2) - powf(D,2);

if (delta >= 0) 
{ 
    // Collision detected 
}

If delta is greater than zero there are two intersections between ball (circle) and line. If delta is equal to zero there is one intersection – perfect collision.



来源:https://stackoverflow.com/questions/22047904/collision-accuracy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!