开发者

Seemingly simple ball & line collision?

开发者 https://www.devze.com 2023-03-09 21:14 出处:网络
I have a开发者_Go百科 ball accelerating due to gravity 9.81. I also have some lines, which can be moved around and have their slopes changes by the user. How do I handle bouncing collisions between th

I have a开发者_Go百科 ball accelerating due to gravity 9.81. I also have some lines, which can be moved around and have their slopes changes by the user. How do I handle bouncing collisions between the ball and the lines to make them bounce off at the correct angle. All my collision detection works fine, I was just wondering if there was a way of using the slope of the line to find the resultant vector of the ball after collision.

I am writing in Objective-C with XCode 4 on Mac OS 10.6.8


I think you need the "normal" vector of the "surface" with which the ball collided, and then "flip" the "velocity" vector of the ball accordingly.

To clarify: The "normal" of the line is a perpendicular vector to the line, of unit length. Think of it like: The line represents a plane, which would have a normal vector.

From the top of my head: Let N be the normalized (unit lenght) "normal" vector of the line, let v be the velocity vector of the ball.

  1. Project v onto N using a dot product (p = v DOT N)

  2. Add the vector 2*p*N to v (v = v + 2*p*N)

I think that should do the trick...

I would also recommend using a physics engine as already pointed out.


Have you considered enlisting one of the handful of engines out there to do the dirty work for you? Cocos2D, Box2D and Chipmunk are three that come to mind.


The easy way to do it (in my opinion):

  • When you create the line calculate the matrix that would rotate it to be horizontal and calculate the inverse of that matrix.
  • When the ball collides with the line:
    1. rotate the velocity vector by the rotation matrix
    2. change the sign of the y component
    3. rotate the velocity vector by the inverse of the rotation matrix.

The rotation matrix is given by:

( cos A ,  sin A )
( -sin A , cos A )

The inverse rotation matrix is given by:

( cos A , -sin A )
( sin A ,  cos A )

where A is the angle between the line and the horizontal.

The above uses standard mathematical conventions (positive x and y is the upper right quadrant, 0 radians is in the positive direction along the x axis and angles increase anticlockwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号