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

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

本文关键字:碰撞 偏转 游戏 计算      更新时间:2023-10-16

这是我的代码:

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的值,但当球越过它的极限时,它就离开了屏幕。如果球碰到球拍或墙壁,我就得把它偏转。我能做些什么来实现这一点?到目前为止,我使用的所有条件都不能正常工作。

所以基本上你想要一个从窗口边缘反弹的球。(对于这个答案,我将忽略滑块,查找与滑块的碰撞与查找与墙的碰撞非常相似)。

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

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

下一个问题是如何确定我们是否撞到了窗户的边缘。请注意,球上最右边的点的位置为templx + radius,球上的最左边的点的地址为templx - radius等。现在,要想知道我们是否撞到了墙,我们应该将这些值与窗口尺寸进行比较。

// 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;