我有一个for循环,里面的整数x将从533增加到813.这意味着280增量。 在同一个循环中,我想在发生上述情况时将y的值从300减少到200。 这意味着当x是533时y必须是300而x是813时y必须是200.我知道这可以通过在每次迭代中将y的值减小100/280来实现。 但都是整数。
以下是我使用的一些代码示例,但它不工作:
for(int i = 0; i < b.getSize(); i++) { x = b.getCar(i).getPosX(); b.getCar(i).setPosX(++x); if(x >= ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){ y = b.getCar(i).getPosY(); y = (double)(y - (10.0f / 28.0f)); b.getCar(i).setPosY((int)y); } }我怎么可能做到这一点。 谢谢!
I have a for loop and inside that integer x will increase from 533 to 813. That means 280 increments. In side the same loop I want to decrease y's value from 300 to 200 when above happens. Which means when x is 533 y must be 300 and when x is 813 y must be 200. I know this can do by decrease y's value by 100/280 in each iteration. But both are integers.
Here are some code sample i used but it is not working.:
for(int i = 0; i < b.getSize(); i++) { x = b.getCar(i).getPosX(); b.getCar(i).setPosX(++x); if(x >= ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){ y = b.getCar(i).getPosY(); y = (double)(y - (10.0f / 28.0f)); b.getCar(i).setPosY((int)y); } }How can I possibly do this. Thanks!
最满意答案
有两种解决方案,简单和复杂。 简单的一个:
y = yoff + (int)( (double) height * x / width )其中yoff = 300, height = -100, width = 813-533 。 基本上,你做一个浮点运算,然后你围绕结果。
或者,使用Bresenham线算法也可以使用纯整数运算来完成相同的操作,但这需要更多的代码。
There are two solutions, a simple and a complex one. The simple one:
y = yoff + (int)( (double) height * x / width )where yoff = 300, height = -100, width = 813-533. Basically, you do a floating point operation and then you round the result.
Alternatively, the same can be done using pure integer math using the Bresenham line algorithm but that would take a lot more code.
更多推荐
发布评论