How to calculate a specified frame rate in milliseconds.

753 Views Asked by At

I am writing a program which moves a square image 1 pixel to the right every millisecond. The image starts at a x position of -469 and when it is done it ends up at an x position of 11. I want to move the image to the right 60 pixels a second but the Runnable code in java uses milliseconds to handle when it moves the pixel by a value of one. What value in milliseconds would I use to achieve that increase of 60 a second.

PS sorry if this involves programming but Im not the best at math and it is a math problem not a programming problem.

2

There are 2 best solutions below

4
On

60 pixels per second is 60/1000 pixels per millisecond; that's the same as

1000/60 milliseconds per pixel, hence 100/6, which is $16 \frac{2}{3}$. I don't know whether Java allows floats for that item within a Runnable, but if so, you should use 16 + 2.0/3.0.

If it requires an int...then you're not going to get yourself exactly 60 pixels per second.

What you can do is run it at 16 milliseconds per pixel and pause for a few milliseconds per second at some random point during the second; that'll give a slightly irregular motion, but the right number of pixels per second.

Alternatively, you can recognize that this is what's happening inside the box anyhow: you don't get to say when frames are actually rendered to the screen, so under the hood there's a "what's the current time? OK, what's that make the pixel offset be, in integers because it's easier? OK, let's go with that" kind of loop happening. :)

0
On

Converting units, we get:

$$\frac{60 \text{ pixels}}{1 \text{ sec}}=\frac{60 \text{ pixels}}{1000 \text{ ms}}=\frac{1 \text{ pixel}}{16.666... \text{ ms}}$$

This says you should move $1$ pixel every $16\frac23$ milliseconds. If you can only work with whole numbers of milliseconds, then you could either round to $17$ and call it good, or you could use one $16$, followed by two $17$s to get the right average: $16,17,17,16,17,17,16,17,17,\ldots$.