如何将 x 和 y 围绕屏幕包裹?

huangapple go评论73阅读模式
英文:

How to wrap x and y around the screen?

问题

例如,如果一个移动的球超出了屏幕,应该采取什么确切的方法?

我目前是这样做的:

if (x < 0.0) x = 屏幕宽度() - 1;
else if (x >= 屏幕宽度()) x = 0;
// y轴同理

但我看到了这个版本:

if (x < 0.0) x = x + 屏幕宽度();
else if (x >= 屏幕宽度()) x = x - 屏幕宽度();
// y轴同理

第二个版本不是在做无用的加法/减法吗?

英文:

For example, if a moving ball goes beyond the screen, what is the exact method to do it?

I currently do this:

if (x &lt; 0.0) x = screenWidth() - 1;
else if (x &gt;= screenWidth()) x = 0;
// same for y

But I saw this version:

if (x &lt; 0.0) x = x + screenWidth();
else if (x &gt;= screenWidth()) x = x - screenWidth();
// same for y

Isn't the second version doing useless addition/subtraction?

答案1

得分: 2

它们执行略有不同的操作:一个执行循环包装(第二个版本),另一个只是将其带到边缘(第一个版本)。

请注意,您用于循环包装的代码通常可能是错误的。例如,考虑screen_size = 800;x = -10000;。您的代码将使它变为x = -9200。您可能希望在使用循环包装的代码之前执行x = x % screen_size,或者您可以使用以下代码:((x % screen_size) + screen_size) % screen_size

英文:

They do slightly different things: one does a cyclic wrapping (the second version) the other one just brings it to the edge (the first version).

Note that the code you are using for the cyclic wrapping may in general be wrong. Consider for example a screen_size = 800; and x = -10000;. Your code will bring it to x = -9200. You probably want to do x = x % screen_size before using your code for the cyclic wrapping, or you could use: ((x % screen_size) + screen_size) % screen_size instead.

答案2

得分: 1

在你的版本中,如果球移出了屏幕,你只是将球移动到屏幕边缘,但在另一个版本中,它会保持球在理论上在屏幕外行进的距离,以便在其新位置考虑。这有助于显示球以相同速度行进。

英文:

In your version you just move the ball to the edge of the screen if it went out of it, but in the other version it keeps the distance that the balls travelled theoretically outside the screen to be considered in its new position. This helps to show the ball as travelling with the same speed.

huangapple
  • 本文由 发表于 2020年1月7日 01:35:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定