从窗体C#的边缘反弹
本文关键字:边缘 窗体 | 更新日期: 2023-09-27 18:20:38
我目前正在尝试让3个球在表单中反弹并使其工作,问题是我的代码的这一部分(使球从表单的边缘反弹)看起来非常笨拙,我觉得它可以以某种方式浓缩。有什么方法可以清理吗
public void Move(int width, int height)
{
if ((position.X >= 0) && (position.X + size <= width)) //Within X Bounds
{
if (XBounce)
{
position.X -= speed;
}
else
{
position.X += speed;
}
}
else
{
if (!XBounce)
{
position.X -= size / 2;
}
else
{
position.X += size / 2;
}
XBounce = !XBounce;
}
if ((position.Y >= 0) && (position.Y + size <= height)) //Within Y Bounds
{
if (YBounce)
{
position.Y -= speed;
}
else
{
position.Y += speed;
}
}
else
{
if (!YBounce)
{
position.Y -= size / 2;
}
else
{
position.Y += size / 2;
}
YBounce = !YBounce;
}
}
通过将Xbounce
和YBounce
更改为设置为1
或-1
的int
变量,您可以稍微简化一些:
public void Move(int width, int height)
{
if ((position.X >= 0) && (position.X + size <= width)) //Within X Bounds
{
position.X -= XBounce * speed;
}
else
{
XBounce = -XBounce;
position.X -= XBounce * size / 2;
}
if ((position.Y >= 0) && (position.Y + size <= height)) //Within Y Bounds
{
position.Y -= YBounce * speed;
}
else
{
YBounce = -YBounce;
position.Y -= YBounce * size / 2;
}
}