an3
an3

Reputation: 566

Why does Rect from Canvas move up and down when changing it's y coordinates?

I'm making a simple 2d game with Canvas. I have rectangles dropping from the top of the screen. When I decrease the frames per second I can see that the rectangles move up and down a little bit when I increase the rectangle's y coordinates. This is how I move the rectangles it:

public void incrementY(float y) {
    rectangle.top += y;
    rectangle.bottom += y;
}

I simply increase the top and bottom of the rectangle by a float to move it down. Is there a problem with how I'm moving the rectangle? Why is the rectangle moving up when it should only go down?

Upvotes: 0

Views: 54

Answers (1)

Northern Poet
Northern Poet

Reputation: 2045

Your coordinates are float, but pixels are integers. Use some case of strict rounding to convert coordinates to pixels, as instance ceiling:

public void incrementY(float y) {
    rectangle.top = Math.ceil(rectangle.top + y);
    rectangle.bottom = Math.ceil(rectangle.bottom + y);
}

Upvotes: 1

Related Questions