typedef struct direction
{
char q; // quadrant ( up_left, up_right, low_left, low_right )
double c; // coefficient in degrees ( 0 .. 90 )
} bdir;
struct ball
{
int xpos;
int ypos;
bdir dir;
} mainball;
int ploc; // refers to paddle location
int jump; // refers to velocity
//ball_cycle is called somewhere from a real timer signal handler.
void ball_cycle( void )
{
int paddle_hit_resolution = 0;
if ( mainball.dir.q == up_left )
{ //sin and cos from math.h
mainball.xpos-=jump * cos( mainball.dir.c * PI / 180);
mainball.ypos-=jump * sin( mainball.dir.c * PI / 180);
if( mainball.xpos < 0 )
{
mainball.dir.q = up_right;
}
if( mainball.ypos < 0 )
{
mainball.dir.q = low_left;
}
return;
}
if ( mainball.dir.q == up_right )
{
mainball.xpos+=jump * cos( mainball.dir.c * PI / 180);
mainball.ypos-=jump * sin( mainball.dir.c * PI / 180);
if( mainball.xpos > window_x_size - BALL_WIDTH )
{
mainball.dir.q = up_left;
}
if( mainball.ypos < 0 )
{
mainball.dir.q = low_right;
}
return;
}
if ( mainball.dir.q == low_left )
{
mainball.xpos-=jump * cos( mainball.dir.c * PI / 180);
mainball.ypos+=jump * sin( mainball.dir.c * PI / 180);
if( mainball.xpos < 1 )
{
mainball.dir.q = low_right;
}
if( mainball.ypos > window_y_size - ( BALL_HEIGHT + PADDLE_HEIGHT ) ) // paddle hit?
{
mainball.dir.q = up_left;
if ( (mainball.xpos >= ploc ) && (mainball.xpos <= ploc + PADDLE_WIDTH ) )
{
score++;
/*
this is where the question is about.
*/
} else
{
lost();
}
}
return;
}
if ( mainball.dir.q == low_right )
{
mainball.xpos+=jump * cos( mainball.dir.c * PI / 180);
mainball.ypos+=jump * sin( mainball.dir.c * PI / 180);
if( mainball.xpos > window_x_size - BALL_WIDTH)
{
mainball.dir.q = low_left;
}
if( mainball.ypos > window_y_size - ( BALL_HEIGHT + PADDLE_HEIGHT ) ) //paddle hit?
{
mainball.dir.q = up_right;
if ( (mainball.xpos >= ploc ) && (mainball.xpos <= ploc + PADDLE_WIDTH ) )
{
score++;
/*
here too.
*/
} else
{
lost();
}
}
return;
}
return;
}
上面的代码是一个桨/球游戏的片段,我正在为我的教育写作。
这个问题涉及两个地方(见评论)。
当球向屏幕下方移动时(当mainball.dir.q为low_left或low_right时)
球击中球拍并移动到另一个象限(up_left或up_right)或者,它错过了桨,丢失了()被调用并且 游戏结束了。
在开始时,mainball.dir.c等于45.(45度,所以当球击中屏幕墙时,它也会向另一个象限反弹45度)。
在我的情况下,PADDLE_WIDTH等于120(像素)。所以我可以在(前)180个零件中坚决划桨。例如
resolution = ( (mainball.xpos - ploc) * 180 ) / PADDLE_WIDTH
(所以球击中球拍的任何地方都会以0到180之间的值表示,无论球拍宽度如何,对吗?)
在我需要计算碰撞的两个地方。 (桨具有速度,在其他地方定义为全局变量)
(球与球拍相撞后,我需要有一个新的角度让比赛开始变得平稳。)
球与球拍碰撞后新的mainball.dir.c值是什么?
我猜一个分辨率值,甚至可能通过计算新的mainball.dir.c来使用速度。
答案 0 :(得分:1)
我想我得到了你的要求,听起来你有兴趣在与球拍碰撞后获得球的方向。
我经常看到的这种方式是保持x方向和y方向的速度,并假设所有碰撞都是完全弹性的(从而允许保留动量和动能)。这样做的好处是,碰撞解决方案由四个简单的情况处理:
与比赛场地顶部碰撞,x方向的速度不受碰撞的影响,y方向的速度反转;即v_ {y} ^ {&#39;} = -v_ {y}。
与比赛区域的左侧碰撞,y方向的速度不受碰撞的影响,并且x方向的速度反转;即x_ {x} ^ {&#39;} = -v_ {x}。
与比赛区域(或球拍)底部发生碰撞,x方向的速度不受碰撞影响,y方向的速度反转。
与比赛区域的右侧发生碰撞,y方向的速度不受碰撞影响,x方向的速度反转。
这样做的好处在于我们避免了像sin和cos这样昂贵的操作,以及避免浮点运算。