这是我的代码:
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()函数由代码中给定的频率自动调用。正如我们所看到的,我增加了templx和temply的值,但是当球超过了它的极限时,球就会离开屏幕。如果球与桨或墙相撞,我必须使它偏转。我怎样才能做到这一点呢?到目前为止,我所使用的所有条件都不能正常工作。
发布于 2015-03-30 10:34:38
所以,基本上,你希望有一个球,是从你的窗口边缘弹跳。(对于这个答案,我将忽略滑块,发现与滑块的碰撞与发现与墙壁的碰撞非常相似)。
templx和temply对是你球的位置。我不知道DrawCircle函数的第三个参数是什么,所以我假设它是半径。让wwidth和wheight是游戏窗口的宽度和高度。请注意,这个神奇的常数5实际上是球的速度。现在,球从左上角移动到窗口右下角。如果您将5更改为-5,它将从右下角移动到左上角。
让我们再引入两个变量vx和vy -x轴上的速度和y轴上的速度。初值是5和5。现在请注意,当球击中窗口的右边边缘时,它不会改变它的垂直速度,它仍然在上下移动,但是它改变了它的水平速度,从左->右到右->左。因此,如果vx是5,在点击窗口的右侧后,我们应该将其更改为-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;https://stackoverflow.com/questions/29342736
复制相似问题