(C#) 无法限制移动对象

(C#) Can't manage to make restrictions for moving Object

初学者,不要怪 :),我目前正在用 c# 编写一个简单的 "pingpong" 游戏,只是为了练习一下,因为这是我学习这门语言的第二周。 我现在尝试制作 keyevents 以使 "picsSchlägerRechts" 上下移动,效果很好,但我无法制作 "restriction" 以使其不移出我的面板。有什么想法吗?

private static bool conditionUP ;
    private static bool conditionDown ;


    private void frmPingPong_KeyDown(object sender, KeyEventArgs e)
    {

        {
            if (!(picSchlägerRechts.Location.Y == 0 && picSchlägerRechts.Location.Y == 249)) {
                conditionDown = true;
                conditionUP = true;
            }

            if (e.KeyCode == Keys.W && conditionUP == true)
            {
                picSchlägerRechts.Location = new Point(picSchlägerRechts.Location.X, picSchlägerRechts.Location.Y - ms);


                    if (picSchlägerRechts.Location.Y == 0)
                    {
                        conditionUP = false;

                    }


            }
            if(e.KeyCode == Keys.S && conditionDown == true)
            {
                picSchlägerRechts.Location = new Point(picSchlägerRechts.Location.X, picSchlägerRechts.Location.Y + ms);

                if (picSchlägerRechts.Location.Y == 298)
                {
                    conditionDown = false;


                }
            }

您可以尝试这样的操作,以便它检查以确保您的 Y 不会大于或小于 max/min y

private void frmPingPong_KeyDown(object sender, KeyEventArgs e)
{
    var maxY = 298;
    var minY = 0;

    if (e.KeyCode == Keys.W)
    {
        var newY = picSchlägerRechts.Location.Y - ms;

        if (newY < minY)
        {
            newY = minY;
        }
        picSchlägerRechts.Location = new Point(picSchlägerRechts.Location.X, newY);
    }
    else if (e.KeyCode == Keys.S)
    {
        var newY = picSchlägerRechts.Location.Y + ms;

        if (newY > maxY)
        {
            newY = maxY;
        }
        picSchlägerRechts.Location = new Point(picSchlägerRechts.Location.X, newY);
    }
}