Game Development Reference
In-Depth Information
float ScreenToX(int x)
{
return ((float)(x - Width / 2) - XOfs) / XScale;
}
float ScreenToY(int y)
{
return -((float)(y - Height / 2) - YOfs) / YScale;
}
4.
We also introduce a shortcut for the
Line2D()
routine with vector-valued arguments
to use the
Vec2
type of the Box2D library directly:
void LineW(float x1, float y1, float x2, float y2, int col)
{
Line( XToScreen(x1),YToScreen(y1),
XToScreen(x2),YToScreen(y2),col );
}
void Line2DLogical(const Vec2& p1, const Vec2& p2)
{
LineW(p1.x, p1.y, p2.x, p2.y);
}
How it works…
To render a single box, we only need to draw four lines, connecting the corner points. If an
angle of a body is
Alpha
, the center of mass coordinates are
x
and
y,
and the dimensions
are speciied by the width
w
and height
h
, then the corner points' coordinates are calculated
as:
Vec2 pt[4];
pt[0] = x + w * cos(Alpha) + h * sin(Alpha)
pt[1] = x - w * cos(Alpha) + h * sin(Alpha)
pt[2] = x - w * cos(Alpha) - h * sin(Alpha)
pt[3] = x + w * cos(Alpha) - h * sin(Alpha)
Finally, the box is rendered as four lines:
for(int i = 0 ; i < 4 ; i++)
{
Line2DLogical(pt[i], pt[(i+1)%4]);
}
See also …
F
Chapter 6
,
Unifying OpenGL ES 3 and OpenGL 3