how to rotate a group of primitives in allegro c ++

191 Views Asked by At

I have a method in my class that displays a spacecraft based on height and width.

The question is how to turn the ship?

I mean rotating all the elements so that the appearance of the ship does not change, despite the rotation.

void StarShip::draw(unsigned char rand) {
  ALLEGRO_COLOR c = al_map_rgb(64, 64, 64);
  ALLEGRO_COLOR c1 = al_map_rgb(192, 192, 192);
  ALLEGRO_COLOR c2 = al_map_rgb(128, 128, 128);
  ALLEGRO_COLOR c3 = al_map_rgba(rand, 0, 0, 1);
  draw_rectangle(x - (w * 0.3), y + (h * 0.9), (x - (w * 0.2)) + w * 0.1, y + h, c3, c3, c3, c3);
  draw_rectangle(x + (w * 0.3) + w, y + (h * 0.9), x + (w * 0.1) + w, y + h, c3, c3, c3, c3);* draw_rectangle(x - (w0 .3), y + (h * 0.1), (x - (w * 0.2)) + w * 0.1, y + (h * 0.9), c2, c2, c2, c2);
  draw_rectangle(x + (w * 0.3) + w, y + (h * 0.1), x + (w * 0.1) + w, y + (h * 0.9), c2, c2, c2, c2);
  draw_triangle(x - (w * 0.2), y + (h * 0.3), x - (w * 0.2), y + (h * 0.7), x + (w * 0.5), y + (h * 0.5), c, c, c);
  draw_triangle(x + (w * 0.2) + w, y + (h * 0.3), x + (w * 0.2) + w, y + (h * 0.7), x + (w * 0.5), y + (h * 0.5), c, c, c);
  draw_octogonal(x, y, w, h, c, c, c, c, c, c, c, c);
  draw_triangle(x + (w * 0.25), y, x + (w * 0.75), y, x + (w * 0.5), y + (h * 0.5), c, c, c1);
  draw_triangle(x + (w * 0.25), y + h, x + (w * 0.75), y + h, x + (w * 0.5), y + (h * 0.5), c, c, c1);
  draw_triangle(x, y + (h * 0.25), x, y + (h * 0.75), x + (w * 0.5), y + (h * 0.5), c, c, c1);
  draw_triangle(x + w, y + (h * 0.25), x + w, y + (h * 0.75), x + (w * 0.5), y + (h * 0.5), c, c, c1);
  draw_ellipse(x + (w * 0.5), y + (h * 0.5), w * 0.2, h * 0.2, c, c1);
}

I tried to turn the figures one by one, but the render picture no longer looked like a ship. I count more on a hint than on a solution to the problem.

1

There are 1 best solutions below

2
Space.cpp On

For rendering anything more complex than a single quad using transforms is the way to go. It lets you simplify your code a lot and leave all the complex calculations for the GPU. First, modify your code to put your ship centered on the (0, 0) point. Let's call it the origin point.

In allegro 5 you handle transformations in the following way:

ALLEGRO_TRANSFORM t;

// initializes the matrix
al_identity_transform(&t); 

// rotates the object around the origin point. the angle must be in radians
al_rotate_transform(&t, angle); 

// optional. if you normalize the object dimensions (make the length equal to 1) you can simply use the width and the height as the scale factors
al_scale_transform(&t, scale_x, scale_y);

// moves the ship in 2 dimensions
al_translate_transform(&t, x, y);

// apply
al_use_transform(&t);

// *your ship draw code here*

// anything drawn past this point will also use the currently active transformation. let's reset it
al_identity_transform(&t);
al_use_transform(&t);

Please note that the order of the operations matters.