XNA Rectangle intersection

眉间皱痕 提交于 2019-12-08 04:22:30

One way around this would be to do make the following change to your ballRect.Intersect(barXRect)) if statements:

    if (ballRect.Intersects(bat1Rect))
    {
        ballVelo.X = Math.Abs(ballVelo.X) * -1;
    }

    if (ballRect.Intersects(bat2Rect))
    {
        ballVelo.X = Math.Abs(ballVelo.X);
    }

This way the left bar will only send the ball right, and the right bar will only send it left. I may have the bars around the wrong way, so it might be best to double check, but it just means moving the * -1 to the other bat.

Lyise's solution will work, but it does not attack the actual source of the problem. In bigger games you will require a more robust solution, so I'll explain the high level fix.

The issue is that you are changing the X velocity while the ball is still inside the bat. In the next frame, the most probable outcome is that the ball will move away, but not enough to exit the bat, so a new collision is detected. The speed is changed again, and the cycle repeats until the ball exits the bat by going below or above it.

The precise solution requires moving the ball out of the bat and then inverting the speed.
Options:

  • Return the ball to where it was at the beginning of the frame. The ball will never touch the bats. If the ball speed is high enough or the frame rate low enough, this will be noticeable.
  • Calculate how far into the bat the ball has gone, and substract that amount from the ball's position.
    // Colliding from the right
    impactCorrection = bat.Right - ball.Left;
    // Colliding from the left
    impactCorrection = bat.Left - ball.Right;

    For extra points you might move the ball away 2 * impactCorrection in X so the ball always travels the same distance every frame.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!