views:

774

answers:

2

I am trying to solve a tricky math problem, in a cocos2d for iphone context.

Basically I have a roullette wheel which is rotating over time.

I want to have a Sprite latch onto the wheel at certain points (like compass ordinal points N, S, E, W) and bounce off at all other points.

I have the image of the wheel rotating, and just need to solve the part where I can test for whether a sprite has intersected with the circle at the right point on the circle as it is rotating.

I think this question is going in the right direction, but I can't get my head around it. Can anyone help explain?

http://stackoverflow.com/questions/300871/best-way-to-find-a-point-on-a-circle-closest-to-a-given-point

A: 

So you have a circle of radius r, with center (x0,y0).

A point lies outside of the circle, at coordinates (x,y). Your question is to find the closest point on the circle itself to the point (x,y).

The solution is simple. The closest projection of a point onto a circle is accomplished by a simple scaling. Thus,

d = sqrt((x-x0)^2 + (y-y0)^2)
xp = x0 + (x - x0)*r/d
yp = y0 + (y - y0)*r/d

The new point (xp,yp) will lie on the circle itself. To be honest, you would be better off to work in polar coordinates, with the origin at the center of the circle. Then everything gets much easier.

Your next question will be where did it hit on the circle? Don't forget the points of the compass on the circle are rotating with time. An atan2 function will give you the angle that the point (xp-x0,yp-y0) lies at. Most toolsets will have that functionality. See that I've subtracted off the origin here.

woodchips
+1  A: 

If I understand correctly:

First check the distance between the sprite and the centre of the roulette wheel. This will tell you if the sprite is at the edge of the wheel. (If not, nothing happens, right?)

Then, find the angle that the sprite makes from the "x-axis" of the roulette wheel.

spriteAngle = atan2(sprite.x - rouletteCentre.x, sprite.y - rouletteCentre.y)

You'll need to find the equivalent of the atan2() function. It usually returns an answer in radians; you may want to convert it to degrees or quarter-turns or something if you prefer.

Then, subtract the angle that the roulette wheel itself is rotated by (if the wheel itself is rotating, if not then you're already done). Make sure your angle measurement is consistent.

actualAngle = spriteAngle - rouletteRotationAngle

Note that actualAngle may be outside the range 0-360 degrees, and you will need to make it "wrap around".

Lastly, you will want to allow a small range of values as acceptable (e.g. 98 degrees to 102 might count as "North").

Artelius