计算砖块杀手游戏中与球拍碰撞时的球偏转角

Calculating ball deflection angle when colliding with paddle in brick slayer game

这是我的代码:

void Draw()
{
    int x = 59;
    int y = 500;
    int temp = x;
    int colour;
    for (int i = 0; i < 9; ++i)
    {
        for (int j = 0; j < 10; ++j)
        {
            if (i % 2 == 0)
                colour = 2;
            else
                colour = 3;
            DrawRectangle(x, y, 65, 25, colors[colour]);
            x += 67;
        }
        x = temp;
        y -= 39;
    }
    DrawRectangle(tempx, 0, 85, 12, colors[5]);
    DrawCircle(templx, temply, 10, colors[7]);
}

// This function will be called automatically by this frequency: 1000.0 / FPS
void Animate()
{
    templx +=5;
    temply +=5;
    /*if(templx>350)
        templx-=300;
    if(temply>350)
        temply-=300;*/
    glutPostRedisplay(); // Once again call the Draw member function
}
// This function is called whenever the arrow keys on the keyboard are pressed...
//

我正在为这个项目使用 OpenGL。函数 Draw() 用于打印积木、滑块和球。 Animate() 函数由代码中给出的频率自动调用。可以看出,我已经增加了 templxtemply 的值,但球在越过其限制时超出了屏幕。如果球与球拍或墙壁发生碰撞,我必须使球偏转。我该怎么做才能实现这一目标?我现在使用的所有条件都无法正常工作。

所以基本上你想要一个从你的 window 边缘弹跳的球。 (对于这个答案我会忽略滑块,发现与滑块的碰撞与发现与墙壁的碰撞非常相似)。

templxtemply 对是你的球的位置。我不知道 DrawCircle 函数的第三个参数是什么,所以我假设它是半径。设 wwidthwheight 为游戏的宽度和高度 window。请注意,这个魔法常数 5 实际上是球的速度。现在球从 window 的左上角移动到右下角。如果将 5 更改为 -5,它将从右下角移动到左上角。

让我们再引入两个变量 vxvy - x 轴上的速度和 y 轴上的速度。初始值将是 5 和 5。现在请注意,当球击中 window 的右边缘时,它不会改变其垂直速度,它仍在移动 up/down 但它会将水平速度从左->右到右->左。因此,如果 vx5,在到达 window 的右边缘后,我们应该将其更改为 -5

下一个问题是如何判断我们是否碰到了window的边缘。 请注意,球上最右边的点的位置为 templx + radius,球上最左边的点的位置为 templx - radius 等等。现在要确定我们是否撞到了墙,我们应该只需将此值与 window 尺寸进行比较即可。

// check if we hit right or left edge
if (templx + radius >= wwidth || templx - radius <= 0) {
    vx = -vx;
}
// check if we hit top or bottom edge
if (temply + radius >= wheight || temply - radius <= 0) {
    vy = -vy;
}

// update position according to velocity
templx += vx;
temply += vy;