Mage2 Habibi
Mage2 Habibi

Reputation: 25

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

I'm a beginner, don't blame. I'm currently coding a simple "pingpong" game in c#, just to practice a bit because this is my second week of learning this language.

I've tried to make keyevents now to make "picsSchlägerRechts" move up and down, which worked well, but I can't manage to make a "restriction" for it to not move out of my panel. any ideas?

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;
                  

                }
            }
        

Upvotes: 0

Views: 63

Answers (1)

austin wernli
austin wernli

Reputation: 1801

You could try something like this so that it checks to make sure that your Y does not go greater than or less than 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);
    }
}

Upvotes: 1

Related Questions