0

I'm making pong, and am finding it really difficult to write an algorithm that bounces the ball off the four walls properly (I will deal with scoring later on, because only part of the West+East sides will be goals). So at the moment I want the ball to bounce around the box.

Detecting whether the ball has hit a wall is easy, but I'm having trouble calculating the new angle.

This is what I've come up with so far:

        if(dstY == 0) {
            // North wall
            if(angle < 90) {
                newAngle = angle + 90;
            } else {
                newAngle = angle - 90;
            }
        } else if(dstX == maxWidth) {
            // East wall
            if(angle < 90) {
                newAngle = angle + 270;
            } else {
                newAngle = angle + 90;
            }
        } else if(dstY == maxHeight) {
            // South wall
            newAngle = angle + 90;
        } else if(dstX == 1) {
            // West wall
            if(angle < 270) {
                newAngle = angle - 90;
            } else {
                newAngle = angle - 270;
            }
        }

That only works for about half of the collisions, and looks really ugly. I'm sure this should be really simple and that it's been done many times before.

In my code, dstX/dstY are the X/Y destination coordinates. X=0 and y=0 at the top left.

4

4 回答 4

1

在此KineticModel,该方法collideWalls()使用二维矢量算法来简化粒子与平面之间弹性碰撞的模拟。

于 2010-12-29T00:35:34.917 回答
1

您可以通过 2 种方式查看:

角度:如果您知道球碰撞的角度,只需执行 180 - 角度即可找到新角度。

渐变:可能更简单。您必须每 t 毫秒以某个 dY 和 dX 移动球。因此,如果您碰壁,您可以简单地使用 dY 和 dX 的反转符号。例如,如果你撞到了右边的墙,dX 会变成 -dX,而 dY 会继续前进。

于 2010-12-29T01:07:41.433 回答
0

关于使用 jbx 的梯度法的一句话。如果球在盒子的角落附近击中,而 dx 将被反转,dy 可以将球置于顶部边界之上。

于 2010-12-29T23:11:12.997 回答
-1

谢谢@jbx,我知道有一种更简单的方法:) 但是,这似乎不适用于东西墙和桨(如果它们在那些墙上)。不过,这似乎对我在东墙和西墙上有用:

(180 - (angle + 90)) - 90.

这简化为(180-angle). 希望有帮助。

于 2011-04-12T17:43:23.617 回答