我正在制作一个乒乓球游戏,但遇到了一个问题。当球(一个矩形)与球拍(或球棒)在下面或上面发生碰撞时,会出现一个奇怪的错误:球会进入矩形并左右移动,速度越来越快(因为我添加了加速度),最后从相反的一侧弹出。我知道这个错误出现的原因:
if (ballrec.Intersects(player1rec)
&& ball.x <= 20
&& ball.y + 20 >= player.y
&& ball.y <= player.y + 100) //checks the front rebound-here's the bug
{
ball.vx *= -1; //changes x-direction
if (ball.vx < 0)
ball.vx -= 1; //increases x-velocity
effect.Play();
if (R.Next(4) == 0)
{
if (ball.vy < 0) ball.vy--;
else ball.vy++; //increases y-velocity on a special occasion
}
}
else
{
if (ballrec.Intersects(player1rec))
{
ball.vy *= -1;
effect.Play();
}
}
球的vy代表速度y轴方向的值,我将其乘以-1来改变方向。
效果为声音。
问题在于:为了使球在球拍前的任何位置反弹,代码表示球的下侧(即+20)不能高于球拍的上侧,而球的上侧不能低于球拍的下侧。但是由于x坐标(ball.x<=20,20为球拍的宽度),前面的反弹效果使用了球拍的上下两侧,因此无法工作。
我尝试解决它,我的最佳简单解决方案(因为明年我就要开始初中了,不会很多高深数学知识)没有得到好的解决方案(请查看下面)。
我的解决方案(我不满意):我降低了需要前面反弹的区域,即 ball.y>=player.y 且 ball.y+20<=player.y+100(长度),这样上下反弹就可以了,但如果球撞击球拍的角落,同样的问题就出现了,此时球会上下移动。
我的问题是:如何解决这个问题?
谢谢你的时间!希望这不算太长!
目前的解决方案(不完美):
if (ballrec.Intersects(player1rec)
&& ball.x <= 20
&& ball.y >= player.y
&& ball.y + 20 <= player.y + 100)
{
ball.vx *= -1;
if (ball.vx < 0)
ball.vx -= 1;
effect.Play();
if (R.Next(4) == 0)
{
if (ball.vy < 0) ball.vy--;
else ball.vy++;
}
}
else
{
if (ballrec.Intersects(player1rec))
{
ball.vy *= -1;
effect.Play();
}
}