+ 3

Math.max Math.min

I have this code: https://code.sololearn.com/WRbW3UyyHLvM/#html My question is what is the min doing in the if statement and why is it preventing the square from moving off the screen? I would like to know this to help replicate it in the future. As well to understand it better. Any help explaining this would be very helpful thank you.

28th May 2018, 10:56 AM
Bradley
3 odpowiedzi
+ 6
Lets say we have 2 values: xPos and rightBorder. xPos is the position of the rectange, rightBorder is the position of the right side of the screen. If we do: min(xPos, rightBorder) we will be taking whichever value is smaller. Lets say xPos is 100, and keeps increasing (the rectangle moves to the right). Lets say rightBorder is 300. min(100, 300) will return 100. So, the xPos of the rectangle. As the xPos increase, it will eventually move further than the rightBorder. Lets say xPos becomes 301. min(301, 300) Now, 300 (rightBorder) is returned. No matter how high xPos goes now, 300 will keep getting returned. Here's a slightly different example: if (rightKey) xPos = min(xPos + dist, rightBorder); If the right key is pressed, assign the value of xPos. If xPos becomes to high, rightBorder is returned. If it is small, it will be increased by dist. This means once rightBorder is returned, xPos is equal to the rightBorder. Thus, the rectangle will no longer move more to the right.
28th May 2018, 12:16 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
Thank you very much; that makes sense now.
28th May 2018, 1:32 PM
Bradley
+ 1
Bradley You can ask me to original question 😉
28th May 2018, 5:54 PM
KrOW
KrOW - avatar