Jayanga Kaushalya
Jayanga Kaushalya

Reputation: 2744

Mathematical issue (Increasing and deceasing two variables inside one loop)

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!

Upvotes: 3

Views: 143

Answers (5)

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28551

y must be a double or a float and you need to round its value when you want to use it.


If you wanna do animation, just have a look at interpolators. You can abstract the logic of computing the values in between your extremas.

Basically at the beginning, you give your interpolator the start and end values.

Then, you give the interpolator a time and it gives you back the value between start and end for that time value.

Bonus: it will allow you to change your animation look & feel without touching the rest of the code. (what you are trying to do is in fact a linear interpolation, but it will look much nicer using a sine function for instance, or some other algorithm such as bouncing, quadratic, ...)

Upvotes: 3

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

NOt sure what you like to do, but your current solution sufers from rounding of floats to integers. To avoid this, calculate with floats / doubles and convert them to integer whensetting positions.

Upvotes: 1

Gaminic
Gaminic

Reputation: 581

Keep a helping variable double dy that keeps track of the precise value for y. At each iteration, update dy using your formula, then update y by taking the rounded/truncated value of dy.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328724

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.

Upvotes: 4

SJuan76
SJuan76

Reputation: 24895

It looks like the logic for drawing a line. The Bresenham's algorithm should be the best option.

Upvotes: 2

Related Questions