I have a custom drawn rectangle which i want to move in a circular path based on touch events. It follows the direction of the touch for clockwise or anticlockwise movement but basically move in circular motion, as if moving on the edge of the circle.
My current thought process is as follows: Based on the users current and previous x,y i shall find the angle in degrees and then move this rectangle by the same angle by re-drawing in the new position, just making sure that it moves on the edge of a circle. But this leads to some confusion on the following: 1. how do i decide whether angle movement is clockwise or anti-clockwise. 2. I am not being able to figure out the math for this properly.
Would this be the best approach or is there a better idea for doing this? Also, if this is the best approach, could someone please tell me the formula for calculating the angle by which i should move it while taking care of the clocking and anticlockwise ?
could someone please help? please let me know if any more details are required. Thanks
Steps
Here are a few steps in order to move your rectangle along a circle's rim when the user taps and holds to the side of the circle:
1. Obtain direction desired.
2. Obtain angle from current x and y coordinates.
3. Add direction (+1 if counterclockwise, -1 if clockwise) to angle.
4. Calculate new x and y coordinates.
5. Update/display rectangle.
Details
1. In pseudocode,
direction = sign(Rectangle1.x - UsersFingerPosition.x)
. Here sign is a function returning -1 if the number was negative, 0 if it is 0, and 1 if it is positive. Note thatsign(0)
will only result when the user is on the exact x and y of your rectangle's location. In that case, the rectangle would not move (which should be good). In Java, the sign function isMath.signum()
.2. To obtain the current angle use the following java code:
Note the order of
Circle.y-Rectangle.y
andRectangle.x...Circle.x
. This is a result of the coordinate (0, 0) being in the top left corner instead of the center of the screen.3. Simple enough, just add direction to angle. If desired, do something like
4. To get the new x and y coordinates of your rectangle, use the trigonometric functions sine and cosine:
(where Circle.x and Circle.y are the coordinates of the center of your circle and Circle.radius is naturally it's radius).
5. This one you'll have to take care of (or have already) :)!
Hope this helps you!