Pages

Tuesday, October 11, 2011

2D Ball Rolling

When you picture a ball rolling around, you notice that it rotates as it travels in a direction. This effect is due to friction between the ball's surface and the surface it's rolling on. We will try to emulate this effect in two dimensions -- and to make it simple we will assume perfect friction between the ball and the surface.



Understanding the Anatomy of a circle
One concept that may be difficult to understand is the anatomy of a circle. Especially if you haven't learned trigonometry, these concepts may be completely new. Luckily, for this tutorial there are only a couple things you need to know. One is that there are 360 degrees in a circle. No more, no less, exactly 360 degrees.

The second is the relationship between the distance across a circle(diameter), and the distance around a circle(circumference). It turns out that the distance around a circle is exactly PI(3.14... a constant that we know) times the distance across a circle. This is useful because given the size of a circle, we can compute the distance around the circle.

Okay, boring. So what?
At this point, you need to know three things to compute what we call rotational velocity. Or how many degrees per unit of time to rotate the 2d ball:


  1. The ball's size(therefore we can compute that circumference)
  2. The velocity of the ball
  3. The fact that a ball has 360 degrees of rotation.
The first thing we do is compute a circumference given the balls size:

c = PI*Diameter

Now that we know the distance AROUND the ball, here comes the tricky part. We need to find a ratio to degrees for that distance. This means that for every 1 unit of distance the ball travels, how much rotation must occur to account for that distance? You find this number with the results from above, and the fact that a circle has 360 degrees:

degree_per_distance = 360/c

Now that you know how much to rotate the ball given a unit of distance(lets say 1 pixel for simplicity). We only need to know the ball's speed now(and you know that). So basically what we have to do is that for every time we update the ball, we must figure out how much it traveled, and apply that to the ratio we computed. We can then figure out how much to rotate the ball, fooling the user into believing that the ball is rolling:

BALL_POSITION += BALL_SPEED
BALL_ROTATION += BALL_SPEED*degrees_per_distance

And VOLA! You have a ball rolling exactly how fast it should be for the speed that it's going! So if the ball is going SUPER FAST it will rotate SUPER FAST to make up for it.


No comments:

Post a Comment