我在制作 Pong 游戏时遇到了一个问题。当球(矩形)与 Racket 下方或上方的 Racket (或球棒)碰撞时,我得到一个奇怪的错误,球移动到矩形中并左右移动达到高速(因为我添加了加速度)并从对面跳出。我知道为什么会出现这个错误:
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();
}
}
ball.vy=velocity y 轴:我将它乘以 -1 来改变方向
效果=声音
错误:为了让球在 Racket 前面的任何给定位置反弹,它说球的下侧(+20)不能高于 Racket 的上侧,球的上侧必须低于 Racket 的下侧。但是因为x坐标(ball.x<=20, 20= Racket 的宽度),前面的反弹作用消耗了 Racket 的顶部和底部,然后那里的反弹就不起作用了。
当我尝试解决它时,我最好的不复杂的解决方案(因为明年我开始上中学(在我的国家是 14-18 岁)并且不知道很多花哨的数学),我不知道得到一个好的解决方案(检查下面)。
我的解决方案(我对此并不满意):我将前反弹所需的区域降低到 ball.y>=player.y 和 ball.y+20<=player.y+100(长度)和上下反弹工作,但如果球击中 Racket 的一角,同样的错误只会在这种情况下出现,球会上下移动。
我的问题:如何修复错误? 感谢您的时间!希望不会太长!
目前的解决方案(不完美):
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();
}
}
最佳答案
解决方案 1:检查速度矢量
一种解决方案是考虑 Speep 矢量 (ball.vx
) 的方向。
如果速度为负,则只允许玩家 1 翻转球 x 速度(例如,第二个玩家向左屏幕移动,反之亦然)
如果这是一个简单的乒乓球游戏,那就太好了:
// Player 1
if (ballrec.Intersects(player1rec)
&& ball.x <= 20
&& ball.y >= player.y
&& ball.y + 20 <= player.y + 100
&& ball.vx <= 0 ) //<--- Here
{
// .....
}
// Player 2
if (ballrec.Intersects(player2rec)
// ....
&& ball.vx >= 0 ) //<--- Here
{
// .....
}
方案二:保存Ball的碰撞状态
另一种解决方法是保存当前的碰撞状态(碰撞或不碰撞,并且仅在该状态从不碰撞到碰撞时翻转速度):
public class Ball
{
public bool colliding = false;
}
//In Update of Ball/Game
bool player1Collision = ballrec.Intersects(player1rec)
&& ball.x <= 20
&& ball.y >= player.y
&& ball.y + 20 <= player.y + 100;
if( player1Collision && !ball.colliding )
{
// Set state here, so reduce issues when there is a chance that different players can overlap
ball.colliding = true;
// .....
}
// Same for player 2,3,4,5 .....
//Update state for next frame
ball.colliding = player1Collision || player2Collision /* .... */;
关于c# - 边界矩形碰撞 - 球跳过 Racket 的错误一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22307662/