Reputation: 4721
I'm programming a game in 2D. What I achieved is to move a sprite on the basis of a custom path. The path may be represented mathematically as: y = sin (x) ..So the movement is a wave. I wanna to rotate this wave in such way so the movement is not horizontal but vertical or with some custom angle respect the origin. I'm a litte bit weak with math. Sorry. Anyone can help. My code is this
for (int i=0; i<300; i++) {
coordinatesX[i] = i;
coordinatesY[i] = (float) (50 * Math.sin(coordinatesX[i]));
}
createpath (coordinatesX, coordinatesY);
...
Upvotes: 4
Views: 970
Reputation: 7164
Well, your object is represented with some starting coordinates (x,y)^t. In order to rotate that in 2D space, you would use the rotation matrix
R = [ cos(a) -sin(a)]
[ sin(a) cos(a) ]
Since you also want to perform a translation T (move along the sine wave), you can make up an affine transformation by extending you 2D coordinates to 3D homogenous coordinates. Assume your translation will be (tx,ty) and your angle of rotation (in radians) is a, the transformation matrix will be
T = [ cos(a) -sin(a) tx
sin(a) cos(a) ty
0 0 1 ]
When you transform your original (x,y) point to (x,y,1) a simple
T * (x,y,1)^t
will do the trick.
You can go back from homogenous to cartesian coordinates by dividing all elements by the last one (i.e. you loose one dimension). Since in this simple case they are always 1 you can simply drop the last coordinate and are back in 2D.
Edit: Mulitplying T and (x,y,1)^t yields:
T*(x,y,1)^t = [ cos(a) -sin(a) tx ] [ x ]
[ sin(a) cos(a) ty ]*[ y ] =
[ 0 0 1 ] [ 1 ]
= [ cos(a)*x - sin(a)*y + tx ]
[ sin(a)*x + cos(a)*y + ty ] =
[ 1 ]
= (cos(a)*x - sin(a)*y + tx, sin(a)*x + cos(a)*y + ty, 1)^t
Upvotes: 4