I'm working on a (rather) simple 2D project in OpenGL. It's some sort of asteroids clone.
The ship is basically an isosceles triangle of height H, with the base have a length of H/2.
The way I've been doing it so far is simply storing the center point (CP) of the triangle and then calculating the final vertex positions on the fly. The 'point' of the ship is (vectors are x,y) the (CP.x, CP.y + H/2). The other two points are (CP.X - H/4, CP.Y - H/2) and (CP.X + H/4, CP.Y - H/2).
To get the ship facing the right direction, I first call glRotate on the current rotation angle.
This part is working fine however I'm running into issues with collision detection. Currently I'm trying to implement triangle-plane collision detection however to do that, I first need to figure out the actual points of the ship vertices after rotation. I've tried using trigonometry to calculate these points, however I've failed.
The way I've attempted is was to use the cosine rule to find the distance between the unrotated triangle and the triangle after rotation. To give an example, the following is how I've tried to calculate the 'pointy' vertex position after rotation:
//pA is a vector struct holding the position of the pointy vertex of the ship (centerPoint.x, centerPoint.y + height / 2)
//Distance between pA and the rotated pointy vertex - using the cosine rule
float distance = sqrt((2 * pow(size / 2, 2)) * (1 - cosf(rotAngle)));
//The angle to the calculated point
float newPointAngle = (M_PI / 2) - rotAngle;
float xDif = distance * cosf(newPointAngle);
float yDif = distance * sinf(newPointAngle);
//Actually drawing the new point
glVertex2f(pA.x - xDif, pA.y - yDif);
Any idea what I could be doing wrong?
Rotation calculations need to be centered at the origin, so you may need to first translate the coordinates so the center of rotation is aligned with the origin.
Then use the new points to get the rotated coordinates:
where f is the angle of rotation.
Then you translate the new coordinates back to where you started (the reverse of the first translation.
Check out this article for some diagrams and clarification.
Thanks for the help guys but I think those explanations were a bit too technical for me. Nonetheless you made it clear to me that there's no special case for a triangle (which, in hindsight, I should've known) so I tried my hand at searching and after trying a few methods, found one which worked for me.
The post from estain at the GameDev forums did the trick. To quote his post (sorry for the c&p but may be useful for someone else who runs into a similar issue):
Calculating the new points is relatively simple. Assume the x and y are the coordinates of a certain point on the triangle (i.e. the vertices) relative to the point of rotation (or center).
You must convert the coords to a square distance and angle component:
Then rotate:
Then convert back: