【问题标题】:Calculating ball deflection angle when colliding with paddle in brick slayer game在砖块杀手游戏中与桨碰撞时计算球偏转角
【发布时间】:2017-08-18 12:40:50
【问题描述】:

这是我的代码:

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 的值,但是当球越过极限时,球就会离开屏幕。如果球与桨或墙壁碰撞,我必须偏转球。我能做些什么来实现这一目标?我现在使用的所有条件都无法正常工作。

【问题讨论】:

    标签: c++ opengl


    【解决方案1】:

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

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多