简体   繁体   中英

c# multiple If statements does not work correctly

I've encountered really strange issue with if statement. I got image in canvas, which i want to move/drag with mouse/touch. Movement of image works fine. I want to add boundaries, so image would never leave viewport.. image is scaled (its height) to height of canvas, so I just need to add left and right border..

if (planTranslate.X < 0)
{
   planTranslate.X = 0;
}
else planTranslate.X = startPosition.X - vector.X;

if (planTranslate.X > maxX)
{
   planTranslate.X = maxX;
}
else planTranslate.X = startPosition.X - vector.X;

First condition works as expected, but second does not and I have no idea why..

when i put if planTranslate.X > maxX before if planTranslate.X < 0 image stops on right side of viewport but keep going on left.

Any suggestions or help would be greatly appreciated.. thx in advance..

It seems that you simply need to compute the difference and then check the max/min values

planTranslate.X = startPosition.X - vector.X;

if (planTranslate.X < 0)
{
   planTranslate.X = 0;
}

if (planTranslate.X > maxX)
{
   planTranslate.X = maxX;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM