如何使图片框沿屏幕边缘移动而不会剪切?

时间:2019-01-15 03:51:33

标签: c# winforms

在一个示例汽车游戏中,我希望能够使汽车在屏幕内移动,并且希望它被边缘“束缚”。但是,它会不断剪切并超出屏幕范围。

我使图片框为正方形,并使用了汽车图片的尺寸(该图片位于图片框的中心)来建立代码模型。图片框为100x100,汽车图片(面向侧面时)约为50x100。例如,如果汽车相对于屏幕边缘向侧面行驶,则我将图片框的Y位置设为-25。但是,我觉得这很不方便,因为我可能需要更改汽车的图片。

Point pNewLoc = carLocation;

int iX = Width - pbCar.Width;
int iY = Height - pbCar.Height;

if (pNewLoc.X <= 0 || pNewLoc.X >= iX)
{
    if (pNewLoc.X <= 0)
    {
        if (iDirection == CarDirection.UP || iDirection == CarDirection.DOWN)
        {
            pNewLoc.X = -25;
        }
        else
        {
            pNewLoc.X = 0;
        }
    }
    if (pNewLoc.X >= iX)
    {
        if (iDirection == CarDirection.UP || iDirection == CarDirection.DOWN)
        {
            pNewLoc.X = iX + 25;
        }
        else
        {
            pNewLoc.X = iX;
        }
    }
}

if (pNewLoc.Y <= 0 || pNewLoc.Y >= iY)
{
    if (pNewLoc.Y <= 0)
    {
        if (iDirection == CarDirection.LEFT || iDirection == CarDirection.RIGHT)
        {
            pNewLoc.Y = -25;
        }
        else
        {
            pNewLoc.Y = 0;
        }
    }
    if (pNewLoc.Y >= iY)
    {
        if (iDirection == CarDirection.LEFT || iDirection == CarDirection.RIGHT)
        {
            pNewLoc.Y = iY + 25;
        }
        else
        {
            pNewLoc.Y = iY;
        }
    }
}

carLocation = pNewLoc;

此代码可以正常工作,但我觉得它太长且太不方便。

1 个答案:

答案 0 :(得分:0)

如果代码有效,则可以明确地进行总结:

int verticalDirection = Convert.ToInt32(iDirection == CarDirection.UP || iDirection == CarDirection.DOWN);
int horizontalDirection = Convert.ToInt32(iDirection == CarDirection.LEFT || iDirection == CarDirection.RIGHT);
if (pNewLoc.X <= 0)
{
    pNewLoc.X = -25 * verticalDirection;
}
else
{
    pNewLoc.X = iX + 25 * verticalDirection;
}
if (pNewLoc.Y <= 0)
{
    pNewLoc.Y = -25 * horizontalDirection;
}
else
{
    pNewLoc.Y = iY + 25 * horizontalDirection;
}

如果更改图片的大小,则不必使用25之类的常量,而是声明一个取决于汽车图片大小的变量。